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>
45 #include "JavaScript.hpp"
47 #include "Execute.hpp"
55 #define CYObjectiveTry_ { \
57 #define CYObjectiveTry { \
58 JSContextRef context(context_); \
60 #define CYObjectiveCatch \
61 catch (const CYException &error) { \
62 @throw CYCastNSObject(NULL, context, error.CastJSValue(context)); \
68 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
70 #define CYPoolCatch(value) \
71 @catch (NSException *error) { \
72 _saved = [error retain]; \
73 throw CYJSError(context, CYCastJSValue(context, error)); \
78 [_saved autorelease]; \
84 #define CYSadCatch(value) \
85 @catch (NSException *error ) { \
86 throw CYJSError(context, CYCastJSValue(context, error)); \
91 #define class_getSuperclass GSObjCSuper
92 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
93 #define class_getName GSNameFromClass
95 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
97 #define ivar_getName(ivar) ((ivar)->ivar_name)
98 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
99 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
101 #define method_getName(method) ((method)->method_name)
102 #define method_getImplementation(method) ((method)->method_imp)
103 #define method_getTypeEncoding(method) ((method)->method_types)
104 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
107 #define objc_getClass GSClassFromName
109 #define objc_getProtocol GSProtocolFromName
111 #define object_getClass GSObjCClass
113 #define object_getInstanceVariable(object, name, value) ({ \
114 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
115 _assert(value != NULL); \
117 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
121 #define object_setIvar(object, ivar, value) ({ \
122 void *data = (value); \
123 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
126 #define protocol_getName(protocol) [(protocol) name]
129 static void (*$objc_setAssociatedObject)(id object, void *key, id value, objc_AssociationPolicy policy);
130 static id (*$objc_getAssociatedObject)(id object, void *key);
131 static void (*$objc_removeAssociatedObjects)(id object);
135 struct BlockLiteral {
139 void (*invoke)(void *, ...);
143 struct BlockDescriptor1 {
144 unsigned long int reserved;
145 unsigned long int size;
148 struct BlockDescriptor2 {
149 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
150 void (*dispose_helper)(BlockLiteral *src);
153 struct BlockDescriptor3 {
154 const char *signature;
159 BLOCK_DEALLOCATING = 0x0001,
160 BLOCK_REFCOUNT_MASK = 0xfffe,
161 BLOCK_NEEDS_FREE = 1 << 24,
162 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
163 BLOCK_HAS_CTOR = 1 << 26,
164 BLOCK_IS_GC = 1 << 27,
165 BLOCK_IS_GLOBAL = 1 << 28,
166 BLOCK_HAS_STRET = 1 << 29,
167 BLOCK_HAS_SIGNATURE = 1 << 30,
170 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
172 /* Objective-C Pool Release {{{ */
173 void CYPoolRelease_(void *data) {
174 id object(reinterpret_cast<id>(data));
178 id CYPoolRelease_(CYPool *pool, id object) {
181 else if (pool == NULL)
182 return [object autorelease];
184 pool->atexit(CYPoolRelease_);
189 template <typename Type_>
190 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
191 return (Type_) CYPoolRelease_(pool, (id) object);
194 /* Objective-C Strings {{{ */
195 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
196 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
197 char *string(new(pool) char[size]);
198 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
199 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
203 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
205 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
208 return CYCopyJSString(CYPoolCString(pool, context, value));
212 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
215 // XXX: this definition scares me; is anyone using this?!
216 NSString *string([value description]);
217 return CYCopyJSString(context, string);
220 NSString *CYCopyNSString(const CYUTF8String &value) {
222 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
224 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
228 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
230 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
233 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
237 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
238 return CYCopyNSString(context, CYJSString(context, value));
241 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
242 return CYPoolRelease(pool, CYCopyNSString(value));
245 NSString *CYCastNSString(CYPool *pool, SEL sel) {
246 const char *name(sel_getName(sel));
247 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
250 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
251 return CYPoolRelease(pool, CYCopyNSString(context, value));
254 CYUTF8String CYCastUTF8String(NSString *value) {
255 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
256 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
260 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
262 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
263 if (exception == NULL)
265 *exception = CYCastJSValue(context, error);
268 size_t CYGetIndex(NSString *value) {
269 return CYGetIndex(CYCastUTF8String(value));
272 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
273 return CYGetOffset(CYPoolCString(pool, context, value), index);
276 static JSClassRef Instance_;
278 static JSClassRef ArrayInstance_;
279 static JSClassRef BooleanInstance_;
280 static JSClassRef FunctionInstance_;
281 static JSClassRef NumberInstance_;
282 static JSClassRef ObjectInstance_;
283 static JSClassRef StringInstance_;
285 static JSClassRef Class_;
286 static JSClassRef Internal_;
287 static JSClassRef Message_;
288 static JSClassRef Messages_;
289 static JSClassRef Selector_;
290 static JSClassRef Super_;
292 static JSClassRef ObjectiveC_Classes_;
293 static JSClassRef ObjectiveC_Constants_;
294 static JSClassRef ObjectiveC_Protocols_;
297 static JSClassRef ObjectiveC_Image_Classes_;
298 static JSClassRef ObjectiveC_Images_;
302 static Class __NSMallocBlock__;
303 static Class NSCFBoolean_;
304 static Class NSCFType_;
305 static Class NSGenericDeallocHandler_;
306 static Class NSZombie_;
308 static std::set<Class> banned_;
310 static Class NSBoolNumber_;
313 static Class NSArray_;
314 static Class NSBlock_;
315 static Class NSDictionary_;
316 static Class NSNumber_;
317 static Class NSString_;
318 static Class Object_;
320 static Type_privateData *Object_type;
321 static Type_privateData *Selector_type;
323 Type_privateData *Instance::GetType() const {
327 Type_privateData *Selector_privateData::GetType() const {
328 return Selector_type;
331 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
333 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
335 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
336 else if (meta && !class_isMetaClass(self))
337 return CYGetCachedObject(context, CYJSString("Class_prototype"));
339 JSObjectRef global(CYGetGlobalObject(context));
340 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
343 sprintf(label, "i%p", self);
344 CYJSString name(label);
346 JSValueRef value(CYGetProperty(context, cy, name));
347 if (!JSValueIsUndefined(context, value))
350 JSClassRef _class(NULL);
351 JSValueRef prototype;
354 if (self == NSCFBoolean_)
356 if (self == NSBoolNumber_)
358 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
359 else if (self == NSArray_)
360 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
361 else if (self == NSBlock_)
362 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
363 else if (self == NSNumber_)
364 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
365 else if (self == NSDictionary_)
366 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
367 else if (self == NSString_)
368 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
370 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
372 JSObjectRef object(JSObjectMake(context, _class, NULL));
373 JSObjectSetPrototype(context, object, prototype);
374 CYSetProperty(context, cy, name, object);
379 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
380 return CYGetClassPrototype(context, self, class_isMetaClass(self));
383 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
384 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
385 if (Class super = class_getSuperclass(_class))
386 JSObjectSetPrototype(context, value, Messages::Make(context, super));
390 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
391 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
395 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
396 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
400 bool CYIsKindOfClass(id object, Class _class) {
401 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
407 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
408 JSObjectRef value(JSObjectMake(context, CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance_, new Instance(object, flags)));
409 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
413 Instance::~Instance() {
414 if ((flags_ & Transient) == 0)
415 [GetValue() release];
418 struct Message_privateData :
423 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
424 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
430 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
431 Instance::Flags flags;
434 flags = Instance::Transient;
436 flags = Instance::None;
437 object = [object retain];
440 return Instance::Make(context, object, flags);
443 @interface NSMethodSignature (Cycript)
444 - (NSString *) _typeString;
447 @interface NSObject (Cycript)
449 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
450 - (JSType) cy$JSType;
452 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
453 - (NSString *) cy$toCYON:(bool)objective;
455 - (bool) cy$hasProperty:(NSString *)name;
456 - (NSObject *) cy$getProperty:(NSString *)name;
457 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
458 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
459 - (bool) cy$deleteProperty:(NSString *)name;
460 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
462 + (bool) cy$hasImplicitProperties;
468 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
471 NSString *CYCastNSCYON(id value, bool objective) {
477 Class _class(object_getClass(value));
478 SEL sel(@selector(cy$toCYON:));
480 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
481 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
482 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
483 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
484 string = [value cy$toCYON:objective];
489 else if (value == NSZombie_)
490 string = @"_NSZombie_";
491 else if (_class == NSZombie_)
492 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
493 // XXX: frowny /in/ the pants
494 else if (banned_.find(value) != banned_.end())
498 string = [NSString stringWithFormat:@"%@", value];
503 string = @"undefined";
510 struct PropertyAttributes {
515 const char *variable;
528 PropertyAttributes(objc_property_t property) :
540 name = property_getName(property);
541 const char *attributes(property_getAttributes(property));
543 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
544 if ((next = strchr(token, ',')) != NULL)
547 case 'R': readonly = true; break;
548 case 'C': copy = true; break;
549 case '&': retain = true; break;
550 case 'N': nonatomic = true; break;
551 case 'G': getter_ = token + 1; break;
552 case 'S': setter_ = token + 1; break;
553 case 'V': variable = token + 1; break;
557 /*if (variable == NULL) {
558 variable = property_getName(property);
559 size_t size(strlen(variable));
560 char *name(new(pool_) char[size + 2]);
562 memcpy(name + 1, variable, size);
563 name[size + 1] = '\0';
568 const char *Getter() {
570 getter_ = pool_.strdup(name);
574 const char *Setter() {
575 if (setter_ == NULL && !readonly) {
576 size_t length(strlen(name));
578 char *temp(new(pool_) char[length + 5]);
584 temp[3] = toupper(name[0]);
585 memcpy(temp + 4, name + 1, length - 1);
588 temp[length + 3] = ':';
589 temp[length + 4] = '\0';
599 @interface CYWebUndefined : NSObject {
602 + (CYWebUndefined *) undefined;
606 @implementation CYWebUndefined
608 + (CYWebUndefined *) undefined {
609 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
615 #define WebUndefined CYWebUndefined
617 /* Bridge: CYJSObject {{{ */
618 @interface CYJSObject : NSMutableDictionary {
620 JSGlobalContextRef context_;
623 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
625 - (NSUInteger) count;
626 - (id) objectForKey:(id)key;
627 - (NSEnumerator *) keyEnumerator;
628 - (void) setObject:(id)object forKey:(id)key;
629 - (void) removeObjectForKey:(id)key;
633 /* Bridge: CYJSArray {{{ */
634 @interface CYJSArray : NSMutableArray {
636 JSGlobalContextRef context_;
639 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
641 - (NSUInteger) count;
642 - (id) objectAtIndex:(NSUInteger)index;
644 - (void) addObject:(id)anObject;
645 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
646 - (void) removeLastObject;
647 - (void) removeObjectAtIndex:(NSUInteger)index;
648 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
653 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
654 return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
657 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
658 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
661 struct CYBlockDescriptor {
663 BlockDescriptor1 one_;
664 BlockDescriptor2 two_;
665 BlockDescriptor3 three_;
668 Closure_privateData *internal_;
671 void CYDisposeBlock(BlockLiteral *literal) {
672 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
675 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
676 JSObjectRef _this(CYCastJSObject(context, values[0]));
677 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
680 static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
681 CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
684 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
685 _assert(__NSMallocBlock__ != Nil);
686 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
688 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
689 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
691 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
692 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
694 literal->isa = __NSMallocBlock__;
695 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
696 literal->reserved = 0;
697 literal->descriptor = descriptor;
699 descriptor->d_.one_.size = sizeof(descriptor->d_);
700 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
701 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
703 return reinterpret_cast<NSBlock *>(literal);
706 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
707 if (CYJSValueIsNSObject(context, object)) {
708 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
709 return internal->GetValue();
712 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
713 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
714 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
717 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
718 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
722 @interface NSBoolNumber : NSNumber {
727 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
731 switch (JSType type = JSValueGetType(context, value)) {
732 case kJSTypeUndefined:
733 object = [WebUndefined undefined];
743 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
746 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
752 object = CYCopyNSNumber(context, value);
757 object = CYCopyNSString(context, value);
762 // XXX: this might could be more efficient
763 object = CYCastNSObject(pool, context, (JSObjectRef) value);
768 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
775 return CYPoolRelease(pool, object);
777 return [object retain];
780 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
781 return CYNSObject(pool, context, value, true);
784 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
785 return CYNSObject(&pool, context, value, false);
788 /* Bridge: NSArray {{{ */
789 @implementation NSArray (Cycript)
792 return [[self mutableCopy] autorelease];
795 - (NSString *) cy$toCYON:(bool)objective {
796 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
797 [json appendString:@"@["];
801 for (id object in self) {
803 for (size_t index(0), count([self count]); index != count; ++index) {
804 id object([self objectAtIndex:index]);
807 [json appendString:@","];
810 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
811 [json appendString:CYCastNSCYON(object, true)];
813 [json appendString:@","];
818 [json appendString:@"]"];
822 - (bool) cy$hasProperty:(NSString *)name {
823 if ([name isEqualToString:@"length"])
826 size_t index(CYGetIndex(name));
827 if (index == _not(size_t) || index >= [self count])
828 return [super cy$hasProperty:name];
833 - (NSObject *) cy$getProperty:(NSString *)name {
834 size_t index(CYGetIndex(name));
835 if (index == _not(size_t) || index >= [self count])
836 return [super cy$getProperty:name];
838 return [self objectAtIndex:index];
841 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
843 if ([name isEqualToString:@"length"])
844 return CYCastJSValue(context, [self count]);
847 return [super cy$getProperty:name inContext:context];
850 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
851 [super cy$getPropertyNames:names inContext:context];
853 for (size_t index(0), count([self count]); index != count; ++index) {
854 id object([self objectAtIndex:index]);
855 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
857 sprintf(name, "%zu", index);
858 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
863 + (bool) cy$hasImplicitProperties {
869 /* Bridge: NSBlock {{{ */
876 /* Bridge: NSBoolNumber {{{ */
878 @implementation NSBoolNumber (Cycript)
880 - (JSType) cy$JSType {
881 return kJSTypeBoolean;
884 - (NSString *) cy$toCYON:(bool)objective {
885 NSString *value([self boolValue] ? @"true" : @"false");
886 return objective ? value : [NSString stringWithFormat:@"@%@", value];
889 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
890 return CYCastJSValue(context, (bool) [self boolValue]);
896 /* Bridge: NSDictionary {{{ */
897 @implementation NSDictionary (Cycript)
900 return [[self mutableCopy] autorelease];
903 - (NSString *) cy$toCYON:(bool)objective {
904 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
905 [json appendString:@"@{"];
909 for (NSObject *key in self) {
911 NSEnumerator *keys([self keyEnumerator]);
912 while (NSObject *key = [keys nextObject]) {
915 [json appendString:@","];
918 [json appendString:CYCastNSCYON(key, true)];
919 [json appendString:@":"];
920 NSObject *object([self objectForKey:key]);
921 [json appendString:CYCastNSCYON(object, true)];
924 [json appendString:@"}"];
928 - (bool) cy$hasProperty:(NSString *)name {
929 return [self objectForKey:name] != nil;
932 - (NSObject *) cy$getProperty:(NSString *)name {
933 return [self objectForKey:name];
936 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
937 [super cy$getPropertyNames:names inContext:context];
940 for (NSObject *key in self) {
942 NSEnumerator *keys([self keyEnumerator]);
943 while (NSObject *key = [keys nextObject]) {
945 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
949 + (bool) cy$hasImplicitProperties {
955 /* Bridge: NSMutableArray {{{ */
956 @implementation NSMutableArray (Cycript)
958 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
959 if ([name isEqualToString:@"length"]) {
960 // XXX: is this not intelligent?
961 NSNumber *number(reinterpret_cast<NSNumber *>(value));
963 NSUInteger size([number unsignedIntegerValue]);
965 NSUInteger size([number unsignedIntValue]);
967 NSUInteger count([self count]);
969 [self removeObjectsInRange:NSMakeRange(size, count - size)];
970 else if (size != count) {
971 WebUndefined *undefined([WebUndefined undefined]);
972 for (size_t i(count); i != size; ++i)
973 [self addObject:undefined];
978 size_t index(CYGetIndex(name));
979 if (index == _not(size_t))
980 return [super cy$setProperty:name to:value];
982 id object(value ?: [NSNull null]);
984 size_t count([self count]);
986 [self replaceObjectAtIndex:index withObject:object];
988 if (index != count) {
989 WebUndefined *undefined([WebUndefined undefined]);
990 for (size_t i(count); i != index; ++i)
991 [self addObject:undefined];
994 [self addObject:object];
1000 - (bool) cy$deleteProperty:(NSString *)name {
1001 size_t index(CYGetIndex(name));
1002 if (index == _not(size_t) || index >= [self count])
1003 return [super cy$deleteProperty:name];
1004 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1010 /* Bridge: NSMutableDictionary {{{ */
1011 @implementation NSMutableDictionary (Cycript)
1013 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1014 [self setObject:(value ?: [NSNull null]) forKey:name];
1018 - (bool) cy$deleteProperty:(NSString *)name {
1019 if ([self objectForKey:name] == nil)
1022 [self removeObjectForKey:name];
1029 /* Bridge: NSNumber {{{ */
1030 @implementation NSNumber (Cycript)
1032 - (JSType) cy$JSType {
1034 // XXX: this just seems stupid
1035 if ([self class] == NSCFBoolean_)
1036 return kJSTypeBoolean;
1038 return kJSTypeNumber;
1041 - (NSString *) cy$toCYON:(bool)objective {
1042 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1043 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1046 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1047 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1048 } CYObjectiveCatch }
1052 /* Bridge: NSNull {{{ */
1053 @implementation NSNull (Cycript)
1055 - (JSType) cy$JSType {
1059 - (NSString *) cy$toCYON:(bool)objective {
1060 NSString *value(@"null");
1061 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1064 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1065 return CYJSNull(context);
1066 } CYObjectiveCatch }
1070 /* Bridge: NSObject {{{ */
1071 @implementation NSObject (Cycript)
1077 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1078 return [self cy$valueOfInContext:context];
1081 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1083 } CYObjectiveCatch }
1085 - (JSType) cy$JSType {
1086 return kJSTypeObject;
1089 - (NSString *) cy$toCYON:(bool)objective {
1090 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true]];
1093 - (bool) cy$hasProperty:(NSString *)name {
1097 - (NSObject *) cy$getProperty:(NSString *)name {
1101 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1102 if (NSObject *value = [self cy$getProperty:name])
1103 return CYCastJSValue(context, value);
1105 } CYObjectiveCatch }
1107 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1111 - (bool) cy$deleteProperty:(NSString *)name {
1115 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1118 + (bool) cy$hasImplicitProperties {
1124 /* Bridge: NSProxy {{{ */
1125 @implementation NSProxy (Cycript)
1127 - (NSString *) cy$toCYON:(bool)objective {
1128 return [[self description] cy$toCYON:objective];
1133 /* Bridge: NSSet {{{ */
1134 @implementation NSSet (Cycript)
1136 - (NSString *) cy$toCYON:(bool)objective {
1137 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1138 [json appendString:@"[NSSet setWithArray:"];
1139 [json appendString:CYCastNSCYON([self allObjects], true)];
1140 [json appendString:@"]]"];
1146 /* Bridge: NSString {{{ */
1147 @implementation NSString (Cycript)
1150 return [[self copy] autorelease];
1153 - (JSType) cy$JSType {
1154 return kJSTypeString;
1157 - (NSString *) cy$toCYON:(bool)objective {
1158 std::ostringstream str;
1161 CYUTF8String string(CYCastUTF8String(self));
1162 CYStringify(str, string.data, string.size);
1163 std::string value(str.str());
1164 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1167 - (bool) cy$hasProperty:(NSString *)name {
1168 size_t index(CYGetIndex(name));
1169 if (index == _not(size_t) || index >= [self length])
1170 return [super cy$hasProperty:name];
1175 - (NSObject *) cy$getProperty:(NSString *)name {
1176 size_t index(CYGetIndex(name));
1177 if (index == _not(size_t) || index >= [self length])
1178 return [super cy$getProperty:name];
1180 return [self substringWithRange:NSMakeRange(index, 1)];
1183 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1184 [super cy$getPropertyNames:names inContext:context];
1186 for (size_t index(0), length([self length]); index != length; ++index) {
1188 sprintf(name, "%zu", index);
1189 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1193 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1194 return CYCastJSValue(context, CYJSString(context, self));
1195 } CYObjectiveCatch }
1199 /* Bridge: WebUndefined {{{ */
1200 @implementation WebUndefined (Cycript)
1202 - (JSType) cy$JSType {
1203 return kJSTypeUndefined;
1206 - (NSString *) cy$toCYON:(bool)objective {
1207 NSString *value(@"undefined");
1208 return value; // XXX: maybe use the below code, adding @undefined?
1209 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1212 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1213 return CYJSUndefined(context);
1214 } CYObjectiveCatch }
1219 static bool CYIsClass(id self) {
1221 return class_isMetaClass(object_getClass(self));
1223 return GSObjCIsClass(self);
1227 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1228 id self(CYCastNSObject(&pool, context, value));
1229 if (CYIsClass(self))
1230 return (Class) self;
1231 throw CYJSError(context, "got something that is not a Class");
1235 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1237 size_t size(JSPropertyNameArrayGetCount(names));
1238 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1239 for (size_t index(0); index != size; ++index)
1240 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1244 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1246 return CYJSNull(context);
1248 return CYMakeInstance(context, value, false);
1249 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1251 @implementation CYJSObject
1253 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1254 if ((self = [super init]) != nil) {
1256 context_ = CYGetJSContext(context);
1257 JSGlobalContextRetain(context_);
1258 JSValueProtect(context_, object_);
1260 } CYObjectiveCatch }
1262 - (void) dealloc { CYObjectiveTry {
1263 JSValueUnprotect(context_, object_);
1264 JSGlobalContextRelease(context_);
1266 } CYObjectiveCatch }
1268 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1270 const char *cyon(CYPoolCCYON(pool, context, object_));
1272 return [super cy$toCYON:objective];
1274 return [NSString stringWithUTF8String:cyon];
1275 } CYObjectiveCatch }
1277 - (NSUInteger) count { CYObjectiveTry {
1278 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1279 size_t size(JSPropertyNameArrayGetCount(names));
1280 JSPropertyNameArrayRelease(names);
1282 } CYObjectiveCatch }
1284 - (id) objectForKey:(id)key { CYObjectiveTry {
1285 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1286 if (JSValueIsUndefined(context, value))
1288 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1289 } CYObjectiveCatch }
1291 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1292 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1293 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1294 JSPropertyNameArrayRelease(names);
1296 } CYObjectiveCatch }
1298 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1299 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1300 } CYObjectiveCatch }
1302 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1303 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1304 } CYObjectiveCatch }
1308 @implementation CYJSArray
1310 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1312 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_)];
1313 } CYObjectiveCatch }
1315 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1316 if ((self = [super init]) != nil) {
1318 context_ = CYGetJSContext(context);
1319 JSGlobalContextRetain(context_);
1320 JSValueProtect(context_, object_);
1322 } CYObjectiveCatch }
1324 - (void) dealloc { CYObjectiveTry {
1325 JSValueUnprotect(context_, object_);
1326 JSGlobalContextRelease(context_);
1328 } CYObjectiveCatch }
1330 - (NSUInteger) count { CYObjectiveTry {
1331 return CYArrayLength(context, object_);
1332 } CYObjectiveCatch }
1334 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1335 size_t bounds([self count]);
1336 if (index >= bounds)
1337 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1338 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1339 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1340 } CYObjectiveCatch }
1342 - (void) addObject:(id)object { CYObjectiveTry {
1343 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1344 } CYObjectiveCatch }
1346 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1347 size_t bounds([self count] + 1);
1348 if (index >= bounds)
1349 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1350 JSValueRef arguments[3];
1351 arguments[0] = CYCastJSValue(context, index);
1352 arguments[1] = CYCastJSValue(context, 0);
1353 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1354 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1355 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1356 } CYObjectiveCatch }
1358 - (void) removeLastObject { CYObjectiveTry {
1359 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1360 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1361 } CYObjectiveCatch }
1363 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1364 size_t bounds([self count]);
1365 if (index >= bounds)
1366 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1367 JSValueRef arguments[2];
1368 arguments[0] = CYCastJSValue(context, index);
1369 arguments[1] = CYCastJSValue(context, 1);
1370 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1371 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1372 } CYObjectiveCatch }
1374 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1375 size_t bounds([self count]);
1376 if (index >= bounds)
1377 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1378 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1379 } CYObjectiveCatch }
1383 // XXX: inherit from or replace with CYJSObject
1384 @interface CYInternal : NSObject {
1385 JSGlobalContextRef context_;
1386 JSObjectRef object_;
1391 @implementation CYInternal
1393 - (void) dealloc { CYObjectiveTry {
1394 JSValueUnprotect(context_, object_);
1395 JSGlobalContextRelease(context_);
1397 } CYObjectiveCatch }
1399 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1400 if ((self = [super init]) != nil) {
1401 context_ = CYGetJSContext(context);
1402 JSGlobalContextRetain(context_);
1404 } CYObjectiveCatch }
1406 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1407 if (object_ == NULL)
1410 return JSObjectHasProperty(context, object_, name);
1413 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1414 if (object_ == NULL)
1417 return CYGetProperty(context, object_, name);
1420 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1421 @synchronized (self) {
1422 if (object_ == NULL) {
1423 object_ = JSObjectMake(context, NULL, NULL);
1424 JSValueProtect(context, object_);
1428 CYSetProperty(context, object_, name, value);
1431 + (CYInternal *) get:(id)object {
1432 if ($objc_getAssociatedObject == NULL)
1435 @synchronized (object) {
1436 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1443 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1444 if ($objc_getAssociatedObject == NULL)
1447 @synchronized (object) {
1448 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1451 if ($objc_setAssociatedObject == NULL)
1454 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1455 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1464 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1465 Selector_privateData *internal(new Selector_privateData(sel));
1466 return JSObjectMake(context, Selector_, internal);
1469 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1470 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1471 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1472 return reinterpret_cast<SEL>(internal->value_);
1475 return sel_registerName(CYPoolCString(pool, context, value));
1479 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1480 return (void *) [[NSAutoreleasePool alloc] init];
1481 } CYSadCatch(NULL) }
1483 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1484 return [(NSAutoreleasePool *) handle release];
1487 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1489 return Instance::Make(context, nil);
1490 if (Class _class = objc_getClass(name.data))
1491 return CYMakeInstance(context, _class, true);
1492 if (Protocol *protocol = objc_getProtocol(name.data))
1493 return CYMakeInstance(context, protocol, true);
1495 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1497 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1498 ffi_call(cif, function, value, values);
1501 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, sig::Signature *signature) {
1502 if (JSValueIsNull(context, value))
1504 JSObjectRef object(CYCastJSObject(context, value));
1506 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1507 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1509 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1510 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1514 _assert(JSObjectIsFunction(context, object));
1516 _assert(signature != NULL);
1517 _assert(signature->count != 0);
1519 sig::Signature modified;
1520 modified.count = signature->count + 1;
1521 modified.elements = new(pool) sig::Element[modified.count];
1523 modified.elements[0] = signature->elements[0];
1524 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1526 modified.elements[1].name = NULL;
1527 modified.elements[1].type = new(pool) sig::Type();
1528 modified.elements[1].offset = _not(size_t);
1530 memset(modified.elements[1].type, 0, sizeof(sig::Type));
1531 modified.elements[1].type->primitive = sig::object_P;
1533 return CYMakeBlock(context, object, modified);
1536 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1537 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1539 switch (type->primitive) {
1541 // XXX: this function might not handle the idea of a null pool
1542 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &type->data.signature);
1546 case sig::typename_P:
1547 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1550 case sig::selector_P:
1551 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1559 } CYSadCatch(false) }
1561 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1562 switch (type->primitive) {
1563 // XXX: do something epic about blocks
1566 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1567 JSValueRef value(CYCastJSValue(context, object));
1573 case sig::typename_P:
1574 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1576 case sig::selector_P:
1577 if (SEL sel = *reinterpret_cast<SEL *>(data))
1578 return CYMakeSelector(context, sel);
1582 return CYJSNull(context);
1586 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1588 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1589 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1592 #if OBJC_API_VERSION >= 2
1594 method_getReturnType(method, type, sizeof(type));
1596 const char *type(method_getTypeEncoding(method));
1602 // XXX: possibly use a more "awesome" check?
1606 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1607 JSObjectRef _this(CYCastJSObject(context, values[0]));
1608 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1611 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1612 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1615 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1616 Message_privateData *internal(new Message_privateData(sel, type, imp));
1617 return JSObjectMake(context, Message_, internal);
1620 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1621 JSObjectRef function(CYCastJSObject(context, value));
1623 sig::Signature signature;
1624 sig::Parse(pool, &signature, encoding, &Structor_);
1625 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageClosure_));
1626 // XXX: see notes in Library.cpp about needing to leak
1627 return reinterpret_cast<IMP>(internal->GetValue());
1630 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1631 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1632 Class _class(internal->GetValue());
1635 const char *name(CYPoolCString(pool, context, property));
1637 if (SEL sel = sel_getUid(name))
1638 if (class_getInstanceMethod(_class, sel) != NULL)
1644 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1645 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1646 Class _class(internal->GetValue());
1649 const char *name(CYPoolCString(pool, context, property));
1651 if (SEL sel = sel_getUid(name))
1652 if (objc_method *method = class_getInstanceMethod(_class, sel))
1653 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1658 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1659 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1660 Class _class(internal->GetValue());
1663 const char *name(CYPoolCString(pool, context, property));
1664 SEL sel(sel_registerName(name));
1669 if (JSValueIsObjectOfClass(context, value, Message_)) {
1670 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1671 type = sig::Unparse(pool, &message->signature_);
1672 imp = reinterpret_cast<IMP>(message->GetValue());
1673 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1674 type = method_getTypeEncoding(method);
1675 imp = CYMakeMessage(context, value, type);
1676 } else _assert(false);
1678 objc_method *method(NULL);
1679 #if OBJC_API_VERSION >= 2
1681 objc_method **methods(class_copyMethodList(_class, &size));
1682 for (size_t i(0); i != size; ++i)
1683 if (sel_isEqual(method_getName(methods[i]), sel)) {
1684 method = methods[i];
1689 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1690 for (int i(0); i != methods->method_count; ++i)
1691 if (sel_isEqual(method_getName(&methods->method_list[i]), sel)) {
1692 method = &methods->method_list[i];
1698 method_setImplementation(method, imp);
1701 GSMethodList list(GSAllocMethodList(1));
1702 GSAppendMethodToList(list, sel, type, imp, YES);
1703 GSAddMethodList(_class, list, YES);
1704 GSFlushMethodCacheForClass(_class);
1706 class_addMethod(_class, sel, imp, type);
1713 #if 0 && OBJC_API_VERSION < 2
1714 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1715 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1716 Class _class(internal->GetValue());
1719 const char *name(CYPoolCString(pool, context, property));
1721 if (SEL sel = sel_getUid(name))
1722 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1723 objc_method_list list = {NULL, 1, {method}};
1724 class_removeMethods(_class, &list);
1732 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1733 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1734 Class _class(internal->GetValue());
1736 #if OBJC_API_VERSION >= 2
1738 objc_method **data(class_copyMethodList(_class, &size));
1739 for (size_t i(0); i != size; ++i)
1740 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1743 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1744 for (int i(0); i != methods->method_count; ++i)
1745 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1749 static bool CYHasImplicitProperties(Class _class) {
1750 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1751 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1753 return [_class cy$hasImplicitProperties];
1756 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1757 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1758 id self(internal->GetValue());
1760 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1764 NSString *name(CYCastNSString(&pool, context, property));
1766 if (CYInternal *internal = [CYInternal get:self])
1767 if ([internal hasProperty:property inContext:context])
1770 Class _class(object_getClass(self));
1773 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1774 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1775 if ([self cy$hasProperty:name])
1777 } CYPoolCatch(false)
1779 const char *string(CYPoolCString(pool, context, name));
1782 if (class_getProperty(_class, string) != NULL)
1786 if (CYHasImplicitProperties(_class))
1787 if (SEL sel = sel_getUid(string))
1788 if (CYImplements(self, _class, sel, true))
1794 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1795 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1796 id self(internal->GetValue());
1798 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1799 return Internal::Make(context, self, object);
1802 NSString *name(CYCastNSString(&pool, context, property));
1804 if (CYInternal *internal = [CYInternal get:self])
1805 if (JSValueRef value = [internal getProperty:property inContext:context])
1809 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1813 const char *string(CYPoolCString(pool, context, name));
1814 Class _class(object_getClass(self));
1817 if (objc_property_t property = class_getProperty(_class, string)) {
1818 PropertyAttributes attributes(property);
1819 SEL sel(sel_registerName(attributes.Getter()));
1820 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1824 if (CYHasImplicitProperties(_class))
1825 if (SEL sel = sel_getUid(string))
1826 if (CYImplements(self, _class, sel, true))
1827 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1832 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1833 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1834 id self(internal->GetValue());
1838 NSString *name(CYCastNSString(&pool, context, property));
1839 NSObject *data(CYCastNSObject(&pool, context, value));
1842 if ([self cy$setProperty:name to:data])
1844 } CYPoolCatch(false)
1846 const char *string(CYPoolCString(pool, context, name));
1847 Class _class(object_getClass(self));
1850 if (objc_property_t property = class_getProperty(_class, string)) {
1851 PropertyAttributes attributes(property);
1852 if (const char *setter = attributes.Setter()) {
1853 SEL sel(sel_registerName(setter));
1854 JSValueRef arguments[1] = {value};
1855 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1861 size_t length(strlen(string));
1863 char set[length + 5];
1869 if (string[0] != '\0') {
1870 set[3] = toupper(string[0]);
1871 memcpy(set + 4, string + 1, length - 1);
1874 set[length + 3] = ':';
1875 set[length + 4] = '\0';
1877 if (SEL sel = sel_getUid(set))
1878 if (CYImplements(self, _class, sel)) {
1879 JSValueRef arguments[1] = {value};
1880 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1884 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1885 [internal setProperty:property toValue:value inContext:context];
1892 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1893 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1894 id self(internal->GetValue());
1897 NSString *name(CYCastNSString(NULL, context, property));
1898 return [self cy$deleteProperty:name];
1899 } CYPoolCatch(false)
1900 } CYCatch(false) return /*XXX*/ false; }
1902 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1903 const char *name(sel_getName(method_getName(method)));
1904 if (strchr(name, ':') != NULL)
1907 const char *type(method_getTypeEncoding(method));
1908 if (type == NULL || *type == '\0' || *type == 'v')
1911 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1914 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1915 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1916 id self(internal->GetValue());
1919 Class _class(object_getClass(self));
1924 objc_property_t *data(class_copyPropertyList(_class, &size));
1925 for (size_t i(0); i != size; ++i)
1926 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1931 if (CYHasImplicitProperties(_class))
1932 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1933 #if OBJC_API_VERSION >= 2
1935 objc_method **data(class_copyMethodList(current, &size));
1936 for (size_t i(0); i != size; ++i)
1937 Instance_getPropertyNames_message(names, data[i]);
1940 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1941 for (int i(0); i != methods->method_count; ++i)
1942 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1947 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1948 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1949 [self cy$getPropertyNames:names inContext:context];
1953 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1954 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1955 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1959 static const char *CYBlockEncoding(NSBlock *self) {
1960 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1961 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1963 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1964 descriptor += sizeof(BlockDescriptor1);
1965 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1966 descriptor += sizeof(BlockDescriptor2);
1967 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1968 return descriptor3->signature;
1971 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1972 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1973 id self(internal->GetValue());
1975 if (const char *encoding = CYBlockEncoding(self)) {
1981 sig::Signature signature;
1982 sig::Parse(pool, &signature, encoding, &Structor_);
1985 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1987 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1988 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1989 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1993 CYThrow("NSBlock without signature field passed arguments");
1997 } CYPoolCatch(NULL);
2002 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
2003 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2004 Class _class(internal->GetValue());
2005 if (!CYIsClass(_class))
2008 if (CYJSValueIsNSObject(context, instance)) {
2009 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2010 // XXX: this isn't always safe
2011 return [linternal->GetValue() isKindOfClass:_class];
2017 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2019 throw CYJSError(context, "incorrect number of arguments to Instance");
2021 id value(CYCastNSObject(&pool, context, arguments[0]));
2023 value = [NSNull null];
2024 return CYCastJSValue(context, [value cy$box]);
2027 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2028 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2031 id self(internal->GetValue());
2032 const char *name(CYPoolCString(pool, context, property));
2034 if (object_getInstanceVariable(self, name, NULL) != NULL)
2040 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2041 length = CYCastDouble(encoding + 1);
2045 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2046 for (size_t i(0); i != size; ++i)
2047 if (ivars[i] == ivar)
2049 else if (ivar_getOffset(ivars[i]) == offset) {
2050 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2051 _assert(encoding != NULL);
2052 _assert(encoding[0] == 'b');
2053 shift += CYCastDouble(encoding + 1);
2058 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2059 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2062 id self(internal->GetValue());
2063 const char *name(CYPoolCString(pool, context, property));
2066 if (strcmp(name, "isa") == 0)
2067 return CYCastJSValue(context, object_getClass(self));
2070 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2071 ptrdiff_t offset(ivar_getOffset(ivar));
2072 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2074 const char *encoding(ivar_getTypeEncoding(ivar));
2075 _assert(encoding != NULL);
2076 if (encoding[0] == 'b') {
2077 unsigned length, shift;
2078 CYBitField(length, shift, self, ivar, encoding, offset);
2079 _assert(shift + length <= sizeof(uintptr_t) * 8);
2080 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2081 uintptr_t mask((1 << length) - 1);
2082 return CYCastJSValue(context, (field >> shift) & mask);
2084 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2085 return CYFromFFI(context, type.type_, type.GetFFI(), data);
2092 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2093 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2096 id self(internal->GetValue());
2097 const char *name(CYPoolCString(pool, context, property));
2099 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2100 ptrdiff_t offset(ivar_getOffset(ivar));
2101 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2103 const char *encoding(ivar_getTypeEncoding(ivar));
2104 _assert(encoding != NULL);
2105 if (encoding[0] == 'b') {
2106 unsigned length, shift;
2107 CYBitField(length, shift, self, ivar, encoding, offset);
2108 _assert(shift + length <= sizeof(uintptr_t) * 8);
2109 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2110 uintptr_t mask((1 << length) - 1);
2111 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2113 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2114 CYPoolFFI(&pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2122 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2123 if (Class super = class_getSuperclass(_class))
2124 Internal_getPropertyNames_(super, names);
2126 #if OBJC_API_VERSION >= 2
2128 objc_ivar **data(class_copyIvarList(_class, &size));
2129 for (size_t i(0); i != size; ++i)
2130 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2133 if (objc_ivar_list *ivars = _class->ivars)
2134 for (int i(0); i != ivars->ivar_count; ++i)
2135 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2139 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2140 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2143 id self(internal->GetValue());
2144 Class _class(object_getClass(self));
2146 Internal_getPropertyNames_(_class, names);
2149 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2150 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2151 return internal->GetOwner();
2154 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2156 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2159 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2161 NSString *name(CYCastNSString(&pool, context, property));
2162 if (Class _class = NSClassFromString(name))
2163 return CYMakeInstance(context, _class, true);
2168 static Class *CYCopyClassList(size_t &size) {
2169 size = objc_getClassList(NULL, 0);
2170 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2173 size_t writ(objc_getClassList(data, size));
2179 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2191 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2194 if (Class *data = CYCopyClassList(size)) {
2195 for (size_t i(0); i != size; ++i)
2196 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2201 while (Class _class = objc_next_class(&state))
2202 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2206 #if OBJC_API_VERSION >= 2
2207 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2208 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2211 const char *name(CYPoolCString(pool, context, property));
2213 const char **data(objc_copyClassNamesForImage(internal, &size));
2215 for (size_t i(0); i != size; ++i)
2216 if (strcmp(name, data[i]) == 0) {
2217 if (Class _class = objc_getClass(name)) {
2218 value = CYMakeInstance(context, _class, true);
2229 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2230 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2232 const char **data(objc_copyClassNamesForImage(internal, &size));
2233 for (size_t i(0); i != size; ++i)
2234 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2238 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2240 const char *name(CYPoolCString(pool, context, property));
2242 const char **data(objc_copyImageNames(&size));
2243 for (size_t i(0); i != size; ++i)
2244 if (strcmp(name, data[i]) == 0) {
2253 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2254 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2258 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2260 const char **data(objc_copyImageNames(&size));
2261 for (size_t i(0); i != size; ++i)
2262 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2267 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2269 const char *name(CYPoolCString(pool, context, property));
2270 if (Protocol *protocol = objc_getProtocol(name))
2271 return CYMakeInstance(context, protocol, true);
2275 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2276 #if OBJC_API_VERSION >= 2
2278 Protocol **data(objc_copyProtocolList(&size));
2279 for (size_t i(0); i != size; ++i)
2280 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2287 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2289 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2291 return Instance::Make(context, nil);
2295 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2296 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2300 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2301 *data = reinterpret_cast<void *>(address);
2302 return KERN_SUCCESS;
2306 std::set<Class> query_;
2307 JSContextRef context_;
2308 JSObjectRef results_;
2311 struct CYObjectStruct {
2315 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2316 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2317 JSContextRef context(choice->context_);
2319 for (unsigned i(0); i != count; ++i) {
2320 vm_range_t &range(ranges[i]);
2321 void *data(reinterpret_cast<void *>(range.address));
2322 size_t size(range.size);
2324 if (size < sizeof(CYObjectStruct))
2327 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2329 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2331 Class isa(reinterpret_cast<Class>(pointers[0]));
2334 std::set<Class>::const_iterator result(choice->query_.find(isa));
2335 if (result == choice->query_.end())
2338 size_t needed(class_getInstanceSize(*result));
2339 // XXX: if (size < needed)
2341 size_t boundary(496);
2345 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2347 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2351 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2353 throw CYJSError(context, "choose() takes a class argument");
2355 CYGarbageCollect(context);
2358 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2360 vm_address_t *zones(NULL);
2362 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2363 _assert(error == KERN_SUCCESS);
2365 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2366 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2369 choice.context_ = context;
2370 choice.results_ = results;
2373 Class *classes(CYCopyClassList(number));
2374 _assert(classes != NULL);
2376 for (size_t i(0); i != number; ++i)
2377 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2378 if (current == _class) {
2379 choice.query_.insert(classes[i]);
2385 for (unsigned i(0); i != size; ++i) {
2386 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2387 if (zone == NULL || zone->introspect == NULL)
2390 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2398 #if defined(__i386__) || defined(__x86_64__)
2399 #define OBJC_MAX_STRUCT_BY_VALUE 8
2400 static int struct_forward_array[] = {
2401 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2402 #elif defined(__arm__)
2403 #define OBJC_MAX_STRUCT_BY_VALUE 1
2404 static int struct_forward_array[] = {
2406 #elif defined(__arm64__)
2409 #error missing objc-runtime-info
2413 static bool stret(ffi_type *ffi_type) {
2414 return ffi_type->type == FFI_TYPE_STRUCT && (
2415 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2416 struct_forward_array[ffi_type->size] != 0
2422 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2426 _class = object_getClass(self);
2430 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2431 imp = method_getImplementation(method);
2432 type = method_getTypeEncoding(method);
2437 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2439 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2440 type = CYPoolCString(pool, context, [method _typeString]);
2448 sig::Signature signature;
2449 sig::Parse(pool, &signature, type, &Structor_);
2451 size_t used(count + 3);
2452 if (used > signature.count) {
2453 sig::Element *elements(new (pool) sig::Element[used]);
2454 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2456 for (size_t index(signature.count); index != used; ++index) {
2457 sig::Element *element(&elements[index]);
2458 element->name = NULL;
2459 element->offset = _not(size_t);
2461 sig::Type *type(new (pool) sig::Type);
2462 memset(type, 0, sizeof(*type));
2463 type->primitive = sig::object_P;
2464 element->type = type;
2467 signature.elements = elements;
2468 signature.count = used;
2472 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2477 if (stret(cif.rtype))
2478 imp = class_getMethodImplementation_stret(_class, _cmd);
2481 imp = class_getMethodImplementation(_class, _cmd);
2483 objc_super super = {self, _class};
2484 imp = objc_msg_lookup_super(&super, _cmd);
2488 void (*function)() = reinterpret_cast<void (*)()>(imp);
2489 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2492 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2494 throw CYJSError(context, "too few arguments to objc_msgSend");
2504 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2505 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2506 self = internal->GetValue();
2507 _class = internal->class_;;
2508 uninitialized = false;
2509 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2510 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2511 self = internal->GetValue();
2513 uninitialized = internal->IsUninitialized();
2515 internal->value_ = nil;
2517 self = CYCastNSObject(&pool, context, arguments[0]);
2519 uninitialized = false;
2523 return CYJSNull(context);
2525 _cmd = CYCastSEL(context, arguments[1]);
2527 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2530 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2531 return $objc_msgSend(context, object, _this, count, arguments);
2534 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2535 JSValueRef setup[count + 2];
2538 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2539 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2542 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2544 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2546 // XXX: handle Instance::Uninitialized?
2547 id self(CYCastNSObject(&pool, context, _this));
2551 setup[1] = &internal->sel_;
2553 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2556 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2558 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2560 id self(CYCastNSObject(&pool, context, arguments[0]));
2561 Class _class(CYCastClass(pool, context, arguments[1]));
2562 return cy::Super::Make(context, self, _class);
2565 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2567 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2569 const char *name(CYPoolCString(pool, context, arguments[0]));
2570 return CYMakeSelector(context, sel_registerName(name));
2573 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2575 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2576 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2577 return CYMakeInstance(context, self, false);
2580 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2581 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2582 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2585 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2586 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2587 Type_privateData *typical(internal->GetType());
2592 if (typical == NULL) {
2596 type = typical->type_;
2597 ffi = typical->ffi_;
2600 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2603 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2604 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2605 const char *encoding(CYBlockEncoding(internal->GetValue()));
2606 if (encoding == NULL)
2607 return CYJSNull(context);
2608 // XXX: this should be stored on a FunctionInstance private value subclass
2610 sig::Signature signature;
2611 sig::Parse(pool, &signature, encoding, &Structor_);
2612 return CYMakeType(context, &signature);
2615 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2616 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2617 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2620 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2621 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2622 id self(internal->GetValue());
2623 if (!CYIsClass(self))
2624 return CYJSUndefined(context);
2625 return CYGetClassPrototype(context, self);
2628 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2629 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2630 id self(internal->GetValue());
2631 if (!CYIsClass(self))
2632 return CYJSUndefined(context);
2633 return Messages::Make(context, (Class) self);
2636 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2637 if (!CYJSValueIsNSObject(context, _this))
2640 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2641 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2644 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2645 if (!CYJSValueIsNSObject(context, _this))
2648 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2649 id value(internal->GetValue());
2656 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2658 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2659 return CYJSUndefined(context);
2660 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2663 return CYCastJSValue(context, CYJSString(context, [value description]));
2665 } CYCatch(NULL) return /*XXX*/ NULL; }
2667 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2668 if (!CYJSValueIsNSObject(context, _this))
2671 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2672 id value(internal->GetValue());
2674 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2677 if (JSValueRef result = [value cy$valueOfInContext:context])
2681 } CYCatch(NULL) return /*XXX*/ NULL; }
2683 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2684 if (!CYJSValueIsNSObject(context, _this))
2687 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2688 // XXX: but... but... THIS ISN'T A POINTER! :(
2689 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2690 } CYCatch(NULL) return /*XXX*/ NULL; }
2692 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2693 if (!CYJSValueIsNSObject(context, _this))
2696 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2697 id value(internal->GetValue());
2700 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2701 return CYCastJSValue(context, CYJSString(context, [value description]));
2703 } CYCatch(NULL) return /*XXX*/ NULL; }
2705 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2706 if (!CYJSValueIsNSObject(context, _this))
2709 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2710 id value(internal->GetValue());
2712 if (!CYIsClass(value))
2713 CYThrow("non-Class object cannot be used as Type");
2715 // XXX: this is a very silly implementation
2717 std::ostringstream type;
2719 type << class_getName(value);
2723 return CYMakeType(context, type.str().c_str());
2725 } CYCatch(NULL) return /*XXX*/ NULL; }
2727 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2728 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2729 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2732 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2733 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2736 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2737 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2738 const char *name(sel_getName(internal->GetValue()));
2741 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2742 return CYCastJSValue(context, CYJSString(context, string));
2744 } CYCatch(NULL) return /*XXX*/ NULL; }
2746 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2748 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2751 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2752 SEL sel(internal->GetValue());
2754 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2755 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2756 const char *encoding(method_getTypeEncoding(method));
2758 sig::Signature signature;
2759 sig::Parse(pool, &signature, encoding, &Structor_);
2760 return CYMakeType(context, &signature);
2763 static JSStaticValue Selector_staticValues[2] = {
2764 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2765 {NULL, NULL, NULL, 0}
2768 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2769 static JSStaticValue Instance_staticValues[5] = {
2770 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2771 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2772 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2773 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2774 {NULL, NULL, NULL, 0}
2777 static JSStaticValue FunctionInstance_staticValues[6] = {
2778 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2779 // XXX: this is sadly a duplicate of Instance_staticValues
2780 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2781 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2782 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2783 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2784 {NULL, NULL, NULL, 0}
2787 static JSStaticFunction Instance_staticFunctions[7] = {
2788 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2789 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2790 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2791 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2792 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2793 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2797 static JSStaticFunction Class_staticFunctions[2] = {
2798 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2802 static JSStaticFunction Internal_staticFunctions[2] = {
2803 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2807 static JSStaticFunction Selector_staticFunctions[5] = {
2808 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2809 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2810 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2811 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2816 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2817 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2818 } CYObjectiveCatch }
2821 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2822 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2823 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2824 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2826 CYPool &pool(CYGetGlobalPool());
2828 Object_type = new(pool) Type_privateData("@");
2829 Selector_type = new(pool) Type_privateData(":");
2831 NSArray_ = objc_getClass("NSArray");
2832 NSBlock_ = objc_getClass("NSBlock");
2833 NSDictionary_ = objc_getClass("NSDictionary");
2834 NSNumber_ = objc_getClass("NSNumber");
2835 NSString_ = objc_getClass("NSString");
2836 Object_ = objc_getClass("Object");
2839 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2841 // XXX: apparently, iOS now has both of these
2842 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2843 if (NSCFBoolean_ == nil)
2844 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2846 NSCFType_ = objc_getClass("NSCFType");
2848 NSZombie_ = objc_getClass("_NSZombie_");
2850 banned_.insert(Object_);
2851 banned_.insert(objc_getClass("__NSAtom"));
2852 banned_.insert(objc_getClass("__NSGenericDeallocHandler"));
2853 banned_.insert(objc_getClass("NSMessageBuilder"));
2854 banned_.insert(objc_getClass("__NSMessageBuilder"));
2856 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2859 JSClassDefinition definition;
2861 definition = kJSClassDefinitionEmpty;
2862 definition.className = "Instance";
2863 definition.staticValues = Instance_staticValues;
2864 definition.staticFunctions = Instance_staticFunctions;
2865 definition.hasProperty = &Instance_hasProperty;
2866 definition.getProperty = &Instance_getProperty;
2867 definition.setProperty = &Instance_setProperty;
2868 definition.deleteProperty = &Instance_deleteProperty;
2869 definition.getPropertyNames = &Instance_getPropertyNames;
2870 definition.callAsConstructor = &Instance_callAsConstructor;
2871 definition.hasInstance = &Instance_hasInstance;
2872 definition.finalize = &CYFinalize;
2873 Instance_ = JSClassCreate(&definition);
2875 definition.className = "ArrayInstance";
2876 ArrayInstance_ = JSClassCreate(&definition);
2878 definition.className = "BooleanInstance";
2879 BooleanInstance_ = JSClassCreate(&definition);
2881 definition.className = "NumberInstance";
2882 NumberInstance_ = JSClassCreate(&definition);
2884 definition.className = "ObjectInstance";
2885 ObjectInstance_ = JSClassCreate(&definition);
2887 definition.className = "StringInstance";
2888 StringInstance_ = JSClassCreate(&definition);
2890 definition.className = "FunctionInstance";
2891 definition.staticValues = FunctionInstance_staticValues;
2892 definition.callAsFunction = &FunctionInstance_callAsFunction;
2893 FunctionInstance_ = JSClassCreate(&definition);
2895 definition = kJSClassDefinitionEmpty;
2896 definition.className = "Class";
2897 definition.staticFunctions = Class_staticFunctions;
2898 Class_ = JSClassCreate(&definition);
2900 definition = kJSClassDefinitionEmpty;
2901 definition.className = "Internal";
2902 definition.staticFunctions = Internal_staticFunctions;
2903 definition.hasProperty = &Internal_hasProperty;
2904 definition.getProperty = &Internal_getProperty;
2905 definition.setProperty = &Internal_setProperty;
2906 definition.getPropertyNames = &Internal_getPropertyNames;
2907 definition.finalize = &CYFinalize;
2908 Internal_ = JSClassCreate(&definition);
2910 definition = kJSClassDefinitionEmpty;
2911 definition.className = "Message";
2912 definition.staticFunctions = cy::Functor::StaticFunctions;
2913 definition.staticValues = cy::Functor::StaticValues;
2914 definition.callAsFunction = &Message_callAsFunction;
2915 definition.finalize = &CYFinalize;
2916 Message_ = JSClassCreate(&definition);
2918 definition = kJSClassDefinitionEmpty;
2919 definition.className = "Messages";
2920 definition.hasProperty = &Messages_hasProperty;
2921 definition.getProperty = &Messages_getProperty;
2922 definition.setProperty = &Messages_setProperty;
2923 #if 0 && OBJC_API_VERSION < 2
2924 definition.deleteProperty = &Messages_deleteProperty;
2926 definition.getPropertyNames = &Messages_getPropertyNames;
2927 definition.finalize = &CYFinalize;
2928 Messages_ = JSClassCreate(&definition);
2930 definition = kJSClassDefinitionEmpty;
2931 definition.className = "Selector";
2932 definition.staticValues = Selector_staticValues;
2933 definition.staticFunctions = Selector_staticFunctions;
2934 definition.callAsFunction = &Selector_callAsFunction;
2935 definition.finalize = &CYFinalize;
2936 Selector_ = JSClassCreate(&definition);
2938 definition = kJSClassDefinitionEmpty;
2939 definition.className = "Super";
2940 definition.staticFunctions = Internal_staticFunctions;
2941 definition.finalize = &CYFinalize;
2942 Super_ = JSClassCreate(&definition);
2944 definition = kJSClassDefinitionEmpty;
2945 definition.className = "ObjectiveC::Classes";
2946 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2947 definition.getProperty = &ObjectiveC_Classes_getProperty;
2948 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2949 ObjectiveC_Classes_ = JSClassCreate(&definition);
2951 definition = kJSClassDefinitionEmpty;
2952 definition.className = "ObjectiveC::Constants";
2953 definition.getProperty = &ObjectiveC_Constants_getProperty;
2954 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2955 ObjectiveC_Constants_ = JSClassCreate(&definition);
2957 #if OBJC_API_VERSION >= 2
2958 definition = kJSClassDefinitionEmpty;
2959 definition.className = "ObjectiveC::Images";
2960 definition.getProperty = &ObjectiveC_Images_getProperty;
2961 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2962 ObjectiveC_Images_ = JSClassCreate(&definition);
2964 definition = kJSClassDefinitionEmpty;
2965 definition.className = "ObjectiveC::Image::Classes";
2966 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2967 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2968 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2971 definition = kJSClassDefinitionEmpty;
2972 definition.className = "ObjectiveC::Protocols";
2973 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2974 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2975 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2978 // XXX: this is horrible; there has to be a better way to do this
2980 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24");
2982 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2987 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2988 JSObjectRef global(CYGetGlobalObject(context));
2989 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2990 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2991 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2992 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2994 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2995 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2997 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2998 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2999 CYArrayPush(context, alls, protocols);
3001 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
3002 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
3003 CYArrayPush(context, alls, classes);
3005 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
3006 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
3007 CYArrayPush(context, alls, constants);
3009 #if OBJC_API_VERSION >= 2
3010 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3013 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
3014 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3015 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3016 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3017 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
3019 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
3020 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3022 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
3023 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
3024 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
3025 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
3026 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
3028 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
3029 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
3030 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
3031 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
3032 JSObjectSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
3034 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
3035 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
3036 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
3037 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
3038 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
3040 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
3041 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
3042 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
3043 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
3044 JSObjectSetPrototype(context, NumberInstance_prototype, Number_prototype);
3046 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3047 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3048 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3049 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3050 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3052 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3053 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3054 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3055 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3056 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
3058 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
3059 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
3060 JSObjectSetPrototype(context, Class_prototype, Instance_prototype);
3062 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3063 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3064 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3066 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3067 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3070 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3073 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3075 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3076 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3079 static CYHooks CYObjectiveCHooks = {
3080 &CYObjectiveC_ExecuteStart,
3081 &CYObjectiveC_ExecuteEnd,
3082 &CYObjectiveC_CallFunction,
3083 &CYObjectiveC_Initialize,
3084 &CYObjectiveC_SetupContext,
3085 &CYObjectiveC_PoolFFI,
3086 &CYObjectiveC_FromFFI,
3089 struct CYObjectiveC {
3091 hooks_ = &CYObjectiveCHooks;
3092 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
3093 _assert(hooks_ != NULL);
3097 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3098 CYSetupContext(context);
3099 } CYObjectiveCatch }
3101 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3104 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3105 CYStream stream(utf8.data, utf8.data + utf8.size);
3106 utf8 = CYPoolCode(pool, stream);
3108 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3109 size_t bytes(utf16.size * sizeof(uint16_t));
3110 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3111 memcpy(copy, utf16.data, bytes);
3115 } catch (const CYException &exception) {
3117 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];