1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2013 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
22 #include <Foundation/Foundation.h>
24 #include "ObjectiveC/Internal.hpp"
26 #include <objc/objc-api.h>
28 #include "cycript.hpp"
30 #include "ObjectiveC/Internal.hpp"
33 #include <CoreFoundation/CoreFoundation.h>
34 #include <JavaScriptCore/JSStringRefCF.h>
35 #include <objc/runtime.h>
39 #include <malloc/malloc.h>
40 #include <mach/mach.h>
44 #include "JavaScript.hpp"
46 #include "Execute.hpp"
54 #define CYObjectiveTry_ { \
56 #define CYObjectiveTry { \
57 JSContextRef context(context_); \
59 #define CYObjectiveCatch \
60 catch (const CYException &error) { \
61 @throw CYCastNSObject(NULL, context, error.CastJSValue(context)); \
67 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
69 #define CYPoolCatch(value) \
70 @catch (NSException *error) { \
71 _saved = [error retain]; \
72 throw CYJSError(context, CYCastJSValue(context, error)); \
77 [_saved autorelease]; \
83 #define CYSadCatch(value) \
84 @catch (NSException *error ) { \
85 throw CYJSError(context, CYCastJSValue(context, error)); \
90 #define class_getSuperclass GSObjCSuper
91 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
92 #define class_getName GSNameFromClass
94 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
96 #define ivar_getName(ivar) ((ivar)->ivar_name)
97 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
98 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
100 #define method_getName(method) ((method)->method_name)
101 #define method_getImplementation(method) ((method)->method_imp)
102 #define method_getTypeEncoding(method) ((method)->method_types)
103 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
106 #define objc_getClass GSClassFromName
108 #define objc_getProtocol GSProtocolFromName
110 #define object_getClass GSObjCClass
112 #define object_getInstanceVariable(object, name, value) ({ \
113 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
114 _assert(value != NULL); \
116 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
120 #define object_setIvar(object, ivar, value) ({ \
121 void *data = (value); \
122 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
125 #define protocol_getName(protocol) [(protocol) name]
128 static void (*$objc_setAssociatedObject)(id object, void *key, id value, objc_AssociationPolicy policy);
129 static id (*$objc_getAssociatedObject)(id object, void *key);
130 static void (*$objc_removeAssociatedObjects)(id object);
132 struct BlockLiteral {
136 void (*invoke)(void *, ...);
140 struct BlockDescriptor1 {
141 unsigned long int reserved;
142 unsigned long int size;
145 struct BlockDescriptor2 {
146 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
147 void (*dispose_helper)(BlockLiteral *src);
150 struct BlockDescriptor3 {
151 const char *signature;
156 BLOCK_DEALLOCATING = 0x0001,
157 BLOCK_REFCOUNT_MASK = 0xfffe,
158 BLOCK_NEEDS_FREE = 1 << 24,
159 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
160 BLOCK_HAS_CTOR = 1 << 26,
161 BLOCK_IS_GC = 1 << 27,
162 BLOCK_IS_GLOBAL = 1 << 28,
163 BLOCK_HAS_STRET = 1 << 29,
164 BLOCK_HAS_SIGNATURE = 1 << 30,
167 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
169 /* Objective-C Pool Release {{{ */
170 void CYPoolRelease_(void *data) {
171 id object(reinterpret_cast<id>(data));
175 id CYPoolRelease_(CYPool *pool, id object) {
178 else if (pool == NULL)
179 return [object autorelease];
181 pool->atexit(CYPoolRelease_);
186 template <typename Type_>
187 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
188 return (Type_) CYPoolRelease_(pool, (id) object);
191 /* Objective-C Strings {{{ */
192 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
193 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
194 char *string(new(pool) char[size]);
195 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
196 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
200 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
202 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
205 return CYCopyJSString(CYPoolCString(pool, context, value));
209 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
212 // XXX: this definition scares me; is anyone using this?!
213 NSString *string([value description]);
214 return CYCopyJSString(context, string);
217 NSString *CYCopyNSString(const CYUTF8String &value) {
219 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
221 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
225 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
227 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
230 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
234 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
235 return CYCopyNSString(context, CYJSString(context, value));
238 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
239 return CYPoolRelease(pool, CYCopyNSString(value));
242 NSString *CYCastNSString(CYPool *pool, SEL sel) {
243 const char *name(sel_getName(sel));
244 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
247 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
248 return CYPoolRelease(pool, CYCopyNSString(context, value));
251 CYUTF8String CYCastUTF8String(NSString *value) {
252 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
253 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
257 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
259 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
260 if (exception == NULL)
262 *exception = CYCastJSValue(context, error);
265 size_t CYGetIndex(NSString *value) {
266 return CYGetIndex(CYCastUTF8String(value));
269 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
270 return CYGetOffset(CYPoolCString(pool, context, value), index);
273 static JSClassRef Instance_;
275 static JSClassRef ArrayInstance_;
276 static JSClassRef BooleanInstance_;
277 static JSClassRef FunctionInstance_;
278 static JSClassRef NumberInstance_;
279 static JSClassRef ObjectInstance_;
280 static JSClassRef StringInstance_;
282 static JSClassRef Class_;
283 static JSClassRef Internal_;
284 static JSClassRef Message_;
285 static JSClassRef Messages_;
286 static JSClassRef Selector_;
287 static JSClassRef Super_;
289 static JSClassRef ObjectiveC_Classes_;
290 static JSClassRef ObjectiveC_Constants_;
291 static JSClassRef ObjectiveC_Protocols_;
294 static JSClassRef ObjectiveC_Image_Classes_;
295 static JSClassRef ObjectiveC_Images_;
299 static Class __NSMallocBlock__;
300 static Class NSCFBoolean_;
301 static Class NSCFType_;
302 static Class NSGenericDeallocHandler_;
303 static Class NSZombie_;
305 static std::set<Class> banned_;
307 static Class NSBoolNumber_;
310 static Class NSArray_;
311 static Class NSBlock_;
312 static Class NSDictionary_;
313 static Class NSNumber_;
314 static Class NSString_;
315 static Class Object_;
317 static Type_privateData *Object_type;
318 static Type_privateData *Selector_type;
320 Type_privateData *Instance::GetType() const {
324 Type_privateData *Selector_privateData::GetType() const {
325 return Selector_type;
328 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
330 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
332 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
333 else if (meta && !class_isMetaClass(self))
334 return CYGetCachedObject(context, CYJSString("Class_prototype"));
336 JSObjectRef global(CYGetGlobalObject(context));
337 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
340 sprintf(label, "i%p", self);
341 CYJSString name(label);
343 JSValueRef value(CYGetProperty(context, cy, name));
344 if (!JSValueIsUndefined(context, value))
347 JSClassRef _class(NULL);
348 JSValueRef prototype;
351 if (self == NSCFBoolean_)
353 if (self == NSBoolNumber_)
355 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
356 else if (self == NSArray_)
357 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
358 else if (self == NSBlock_)
359 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
360 else if (self == NSNumber_)
361 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
362 else if (self == NSDictionary_)
363 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
364 else if (self == NSString_)
365 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
367 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
369 JSObjectRef object(JSObjectMake(context, _class, NULL));
370 JSObjectSetPrototype(context, object, prototype);
371 CYSetProperty(context, cy, name, object);
376 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
377 return CYGetClassPrototype(context, self, class_isMetaClass(self));
380 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
381 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
382 if (Class super = class_getSuperclass(_class))
383 JSObjectSetPrototype(context, value, Messages::Make(context, super));
387 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
388 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
392 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
393 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
397 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
398 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
399 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
403 Instance::~Instance() {
404 if ((flags_ & Transient) == 0)
405 [GetValue() release];
408 struct Message_privateData :
413 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
414 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
420 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
421 Instance::Flags flags;
424 flags = Instance::Transient;
426 flags = Instance::None;
427 object = [object retain];
430 return Instance::Make(context, object, flags);
433 @interface NSMethodSignature (Cycript)
434 - (NSString *) _typeString;
437 @interface NSObject (Cycript)
439 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
440 - (JSType) cy$JSType;
442 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
443 - (NSString *) cy$toCYON:(bool)objective;
445 - (bool) cy$hasProperty:(NSString *)name;
446 - (NSObject *) cy$getProperty:(NSString *)name;
447 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
448 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
449 - (bool) cy$deleteProperty:(NSString *)name;
450 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
452 + (bool) cy$hasImplicitProperties;
458 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
461 NSString *CYCastNSCYON(id value, bool objective) {
467 Class _class(object_getClass(value));
468 SEL sel(@selector(cy$toCYON:));
470 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
471 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
472 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
473 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
474 string = [value cy$toCYON:objective];
479 else if (value == NSZombie_)
480 string = @"_NSZombie_";
481 else if (_class == NSZombie_)
482 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
483 // XXX: frowny /in/ the pants
484 else if (banned_.find(value) != banned_.end())
488 string = [NSString stringWithFormat:@"%@", value];
493 string = @"undefined";
500 struct PropertyAttributes {
505 const char *variable;
518 PropertyAttributes(objc_property_t property) :
530 name = property_getName(property);
531 const char *attributes(property_getAttributes(property));
533 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
534 if ((next = strchr(token, ',')) != NULL)
537 case 'R': readonly = true; break;
538 case 'C': copy = true; break;
539 case '&': retain = true; break;
540 case 'N': nonatomic = true; break;
541 case 'G': getter_ = token + 1; break;
542 case 'S': setter_ = token + 1; break;
543 case 'V': variable = token + 1; break;
547 /*if (variable == NULL) {
548 variable = property_getName(property);
549 size_t size(strlen(variable));
550 char *name(new(pool_) char[size + 2]);
552 memcpy(name + 1, variable, size);
553 name[size + 1] = '\0';
558 const char *Getter() {
560 getter_ = pool_.strdup(name);
564 const char *Setter() {
565 if (setter_ == NULL && !readonly) {
566 size_t length(strlen(name));
568 char *temp(new(pool_) char[length + 5]);
574 temp[3] = toupper(name[0]);
575 memcpy(temp + 4, name + 1, length - 1);
578 temp[length + 3] = ':';
579 temp[length + 4] = '\0';
589 @interface CYWebUndefined : NSObject {
592 + (CYWebUndefined *) undefined;
596 @implementation CYWebUndefined
598 + (CYWebUndefined *) undefined {
599 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
605 #define WebUndefined CYWebUndefined
607 /* Bridge: CYJSObject {{{ */
608 @interface CYJSObject : NSMutableDictionary {
610 JSGlobalContextRef context_;
613 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
615 - (NSUInteger) count;
616 - (id) objectForKey:(id)key;
617 - (NSEnumerator *) keyEnumerator;
618 - (void) setObject:(id)object forKey:(id)key;
619 - (void) removeObjectForKey:(id)key;
623 /* Bridge: CYJSArray {{{ */
624 @interface CYJSArray : NSMutableArray {
626 JSGlobalContextRef context_;
629 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
631 - (NSUInteger) count;
632 - (id) objectAtIndex:(NSUInteger)index;
634 - (void) addObject:(id)anObject;
635 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
636 - (void) removeLastObject;
637 - (void) removeObjectAtIndex:(NSUInteger)index;
638 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
643 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
644 return JSValueIsObjectOfClass(context, value, Instance_);
647 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
648 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
651 struct CYBlockDescriptor {
653 BlockDescriptor1 one_;
654 BlockDescriptor2 two_;
655 BlockDescriptor3 three_;
658 Closure_privateData *internal_;
661 void CYDisposeBlock(BlockLiteral *literal) {
662 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
665 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
666 JSObjectRef _this(CYCastJSObject(context, values[0]));
667 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
670 static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
671 CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
674 NSObject *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
675 _assert(__NSMallocBlock__ != Nil);
676 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
678 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
679 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
681 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
682 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
684 literal->isa = __NSMallocBlock__;
685 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
686 literal->reserved = 0;
687 literal->descriptor = descriptor;
689 descriptor->d_.one_.size = sizeof(descriptor->d_);
690 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
691 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
693 return reinterpret_cast<NSObject *>(literal);
696 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
697 if (CYJSValueIsNSObject(context, object)) {
698 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
699 return internal->GetValue();
702 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
703 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
704 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
707 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
708 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
712 @interface NSBoolNumber : NSNumber {
717 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
721 switch (JSType type = JSValueGetType(context, value)) {
722 case kJSTypeUndefined:
723 object = [WebUndefined undefined];
733 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
736 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
742 object = CYCopyNSNumber(context, value);
747 object = CYCopyNSString(context, value);
752 // XXX: this might could be more efficient
753 object = CYCastNSObject(pool, context, (JSObjectRef) value);
758 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
765 return CYPoolRelease(pool, object);
767 return [object retain];
770 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
771 return CYNSObject(pool, context, value, true);
774 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
775 return CYNSObject(&pool, context, value, false);
778 /* Bridge: NSArray {{{ */
779 @implementation NSArray (Cycript)
782 return [[self mutableCopy] autorelease];
785 - (NSString *) cy$toCYON:(bool)objective {
786 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
787 [json appendString:@"@["];
791 for (id object in self) {
793 for (size_t index(0), count([self count]); index != count; ++index) {
794 id object([self objectAtIndex:index]);
797 [json appendString:@","];
800 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
801 [json appendString:CYCastNSCYON(object, true)];
803 [json appendString:@","];
808 [json appendString:@"]"];
812 - (bool) cy$hasProperty:(NSString *)name {
813 if ([name isEqualToString:@"length"])
816 size_t index(CYGetIndex(name));
817 if (index == _not(size_t) || index >= [self count])
818 return [super cy$hasProperty:name];
823 - (NSObject *) cy$getProperty:(NSString *)name {
824 size_t index(CYGetIndex(name));
825 if (index == _not(size_t) || index >= [self count])
826 return [super cy$getProperty:name];
828 return [self objectAtIndex:index];
831 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
833 if ([name isEqualToString:@"length"])
834 return CYCastJSValue(context, [self count]);
837 return [super cy$getProperty:name inContext:context];
840 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
841 [super cy$getPropertyNames:names inContext:context];
843 for (size_t index(0), count([self count]); index != count; ++index) {
844 id object([self objectAtIndex:index]);
845 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
847 sprintf(name, "%zu", index);
848 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
853 + (bool) cy$hasImplicitProperties {
859 /* Bridge: NSBlock {{{ */
866 /* Bridge: NSBoolNumber {{{ */
868 @implementation NSBoolNumber (Cycript)
870 - (JSType) cy$JSType {
871 return kJSTypeBoolean;
874 - (NSString *) cy$toCYON:(bool)objective {
875 NSString *value([self boolValue] ? @"true" : @"false");
876 return objective ? value : [NSString stringWithFormat:@"@%@", value];
879 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
880 return CYCastJSValue(context, (bool) [self boolValue]);
886 /* Bridge: NSDictionary {{{ */
887 @implementation NSDictionary (Cycript)
890 return [[self mutableCopy] autorelease];
893 - (NSString *) cy$toCYON:(bool)objective {
894 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
895 [json appendString:@"@{"];
899 for (NSObject *key in self) {
901 NSEnumerator *keys([self keyEnumerator]);
902 while (NSObject *key = [keys nextObject]) {
905 [json appendString:@","];
908 [json appendString:CYCastNSCYON(key, true)];
909 [json appendString:@":"];
910 NSObject *object([self objectForKey:key]);
911 [json appendString:CYCastNSCYON(object, true)];
914 [json appendString:@"}"];
918 - (bool) cy$hasProperty:(NSString *)name {
919 return [self objectForKey:name] != nil;
922 - (NSObject *) cy$getProperty:(NSString *)name {
923 return [self objectForKey:name];
926 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
927 [super cy$getPropertyNames:names inContext:context];
930 for (NSObject *key in self) {
932 NSEnumerator *keys([self keyEnumerator]);
933 while (NSObject *key = [keys nextObject]) {
935 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
939 + (bool) cy$hasImplicitProperties {
945 /* Bridge: NSMutableArray {{{ */
946 @implementation NSMutableArray (Cycript)
948 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
949 if ([name isEqualToString:@"length"]) {
950 // XXX: is this not intelligent?
951 NSNumber *number(reinterpret_cast<NSNumber *>(value));
953 NSUInteger size([number unsignedIntegerValue]);
955 NSUInteger size([number unsignedIntValue]);
957 NSUInteger count([self count]);
959 [self removeObjectsInRange:NSMakeRange(size, count - size)];
960 else if (size != count) {
961 WebUndefined *undefined([WebUndefined undefined]);
962 for (size_t i(count); i != size; ++i)
963 [self addObject:undefined];
968 size_t index(CYGetIndex(name));
969 if (index == _not(size_t))
970 return [super cy$setProperty:name to:value];
972 id object(value ?: [NSNull null]);
974 size_t count([self count]);
976 [self replaceObjectAtIndex:index withObject:object];
978 if (index != count) {
979 WebUndefined *undefined([WebUndefined undefined]);
980 for (size_t i(count); i != index; ++i)
981 [self addObject:undefined];
984 [self addObject:object];
990 - (bool) cy$deleteProperty:(NSString *)name {
991 size_t index(CYGetIndex(name));
992 if (index == _not(size_t) || index >= [self count])
993 return [super cy$deleteProperty:name];
994 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1000 /* Bridge: NSMutableDictionary {{{ */
1001 @implementation NSMutableDictionary (Cycript)
1003 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1004 [self setObject:(value ?: [NSNull null]) forKey:name];
1008 - (bool) cy$deleteProperty:(NSString *)name {
1009 if ([self objectForKey:name] == nil)
1012 [self removeObjectForKey:name];
1019 /* Bridge: NSNumber {{{ */
1020 @implementation NSNumber (Cycript)
1022 - (JSType) cy$JSType {
1024 // XXX: this just seems stupid
1025 if ([self class] == NSCFBoolean_)
1026 return kJSTypeBoolean;
1028 return kJSTypeNumber;
1031 - (NSString *) cy$toCYON:(bool)objective {
1032 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1033 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1036 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1037 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1038 } CYObjectiveCatch }
1042 /* Bridge: NSNull {{{ */
1043 @implementation NSNull (Cycript)
1045 - (JSType) cy$JSType {
1049 - (NSString *) cy$toCYON:(bool)objective {
1050 NSString *value(@"null");
1051 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1054 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1055 return CYJSNull(context);
1056 } CYObjectiveCatch }
1060 /* Bridge: NSObject {{{ */
1061 @implementation NSObject (Cycript)
1067 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1068 return [self cy$valueOfInContext:context];
1071 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1073 } CYObjectiveCatch }
1075 - (JSType) cy$JSType {
1076 return kJSTypeObject;
1079 - (NSString *) cy$toCYON:(bool)objective {
1080 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true]];
1083 - (bool) cy$hasProperty:(NSString *)name {
1087 - (NSObject *) cy$getProperty:(NSString *)name {
1091 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1092 if (NSObject *value = [self cy$getProperty:name])
1093 return CYCastJSValue(context, value);
1095 } CYObjectiveCatch }
1097 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1101 - (bool) cy$deleteProperty:(NSString *)name {
1105 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1108 + (bool) cy$hasImplicitProperties {
1114 /* Bridge: NSProxy {{{ */
1115 @implementation NSProxy (Cycript)
1117 - (NSString *) cy$toCYON:(bool)objective {
1118 return [[self description] cy$toCYON:objective];
1123 /* Bridge: NSSet {{{ */
1124 @implementation NSSet (Cycript)
1126 - (NSString *) cy$toCYON:(bool)objective {
1127 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1128 [json appendString:@"[NSSet setWithArray:"];
1129 [json appendString:CYCastNSCYON([self allObjects], true)];
1130 [json appendString:@"]]"];
1136 /* Bridge: NSString {{{ */
1137 @implementation NSString (Cycript)
1140 return [[self copy] autorelease];
1143 - (JSType) cy$JSType {
1144 return kJSTypeString;
1147 - (NSString *) cy$toCYON:(bool)objective {
1148 std::ostringstream str;
1151 CYUTF8String string(CYCastUTF8String(self));
1152 CYStringify(str, string.data, string.size);
1153 std::string value(str.str());
1154 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1157 - (bool) cy$hasProperty:(NSString *)name {
1158 size_t index(CYGetIndex(name));
1159 if (index == _not(size_t) || index >= [self length])
1160 return [super cy$hasProperty:name];
1165 - (NSObject *) cy$getProperty:(NSString *)name {
1166 size_t index(CYGetIndex(name));
1167 if (index == _not(size_t) || index >= [self length])
1168 return [super cy$getProperty:name];
1170 return [self substringWithRange:NSMakeRange(index, 1)];
1173 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1174 [super cy$getPropertyNames:names inContext:context];
1176 for (size_t index(0), length([self length]); index != length; ++index) {
1178 sprintf(name, "%zu", index);
1179 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1183 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1184 return CYCastJSValue(context, CYJSString(context, self));
1185 } CYObjectiveCatch }
1189 /* Bridge: WebUndefined {{{ */
1190 @implementation WebUndefined (Cycript)
1192 - (JSType) cy$JSType {
1193 return kJSTypeUndefined;
1196 - (NSString *) cy$toCYON:(bool)objective {
1197 NSString *value(@"undefined");
1198 return value; // XXX: maybe use the below code, adding @undefined?
1199 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1202 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1203 return CYJSUndefined(context);
1204 } CYObjectiveCatch }
1209 static bool CYIsClass(id self) {
1211 return class_isMetaClass(object_getClass(self));
1213 return GSObjCIsClass(self);
1217 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1218 id self(CYCastNSObject(&pool, context, value));
1219 if (CYIsClass(self))
1220 return (Class) self;
1221 throw CYJSError(context, "got something that is not a Class");
1225 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1227 size_t size(JSPropertyNameArrayGetCount(names));
1228 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1229 for (size_t index(0); index != size; ++index)
1230 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1234 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1236 return CYJSNull(context);
1238 return CYMakeInstance(context, value, false);
1239 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1241 @implementation CYJSObject
1243 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1244 if ((self = [super init]) != nil) {
1246 context_ = CYGetJSContext(context);
1247 JSGlobalContextRetain(context_);
1248 JSValueProtect(context_, object_);
1250 } CYObjectiveCatch }
1252 - (void) dealloc { CYObjectiveTry {
1253 JSValueUnprotect(context_, object_);
1254 JSGlobalContextRelease(context_);
1256 } CYObjectiveCatch }
1258 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1260 const char *cyon(CYPoolCCYON(pool, context, object_));
1262 return [super cy$toCYON:objective];
1264 return [NSString stringWithUTF8String:cyon];
1265 } CYObjectiveCatch }
1267 - (NSUInteger) count { CYObjectiveTry {
1268 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1269 size_t size(JSPropertyNameArrayGetCount(names));
1270 JSPropertyNameArrayRelease(names);
1272 } CYObjectiveCatch }
1274 - (id) objectForKey:(id)key { CYObjectiveTry {
1275 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1276 if (JSValueIsUndefined(context, value))
1278 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1279 } CYObjectiveCatch }
1281 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1282 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1283 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1284 JSPropertyNameArrayRelease(names);
1286 } CYObjectiveCatch }
1288 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1289 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1290 } CYObjectiveCatch }
1292 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1293 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1294 } CYObjectiveCatch }
1298 @implementation CYJSArray
1300 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1302 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_)];
1303 } CYObjectiveCatch }
1305 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1306 if ((self = [super init]) != nil) {
1308 context_ = CYGetJSContext(context);
1309 JSGlobalContextRetain(context_);
1310 JSValueProtect(context_, object_);
1312 } CYObjectiveCatch }
1314 - (void) dealloc { CYObjectiveTry {
1315 JSValueUnprotect(context_, object_);
1316 JSGlobalContextRelease(context_);
1318 } CYObjectiveCatch }
1320 - (NSUInteger) count { CYObjectiveTry {
1321 return CYArrayLength(context, object_);
1322 } CYObjectiveCatch }
1324 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1325 size_t bounds([self count]);
1326 if (index >= bounds)
1327 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1328 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1329 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1330 } CYObjectiveCatch }
1332 - (void) addObject:(id)object { CYObjectiveTry {
1333 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1334 } CYObjectiveCatch }
1336 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1337 size_t bounds([self count] + 1);
1338 if (index >= bounds)
1339 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1340 JSValueRef arguments[3];
1341 arguments[0] = CYCastJSValue(context, index);
1342 arguments[1] = CYCastJSValue(context, 0);
1343 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1344 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1345 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1346 } CYObjectiveCatch }
1348 - (void) removeLastObject { CYObjectiveTry {
1349 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1350 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1351 } CYObjectiveCatch }
1353 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1354 size_t bounds([self count]);
1355 if (index >= bounds)
1356 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1357 JSValueRef arguments[2];
1358 arguments[0] = CYCastJSValue(context, index);
1359 arguments[1] = CYCastJSValue(context, 1);
1360 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1361 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1362 } CYObjectiveCatch }
1364 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1365 size_t bounds([self count]);
1366 if (index >= bounds)
1367 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1368 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1369 } CYObjectiveCatch }
1373 // XXX: inherit from or replace with CYJSObject
1374 @interface CYInternal : NSObject {
1375 JSGlobalContextRef context_;
1376 JSObjectRef object_;
1381 @implementation CYInternal
1383 - (void) dealloc { CYObjectiveTry {
1384 JSValueUnprotect(context_, object_);
1385 JSGlobalContextRelease(context_);
1387 } CYObjectiveCatch }
1389 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1390 if ((self = [super init]) != nil) {
1391 context_ = CYGetJSContext(context);
1392 JSGlobalContextRetain(context_);
1394 } CYObjectiveCatch }
1396 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1397 if (object_ == NULL)
1400 return JSObjectHasProperty(context, object_, name);
1403 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1404 if (object_ == NULL)
1407 return CYGetProperty(context, object_, name);
1410 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1411 @synchronized (self) {
1412 if (object_ == NULL) {
1413 object_ = JSObjectMake(context, NULL, NULL);
1414 JSValueProtect(context, object_);
1418 CYSetProperty(context, object_, name, value);
1421 + (CYInternal *) get:(id)object {
1422 if ($objc_getAssociatedObject == NULL)
1425 @synchronized (object) {
1426 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1433 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1434 if ($objc_getAssociatedObject == NULL)
1437 @synchronized (object) {
1438 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1441 if ($objc_setAssociatedObject == NULL)
1444 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1445 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1454 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1455 Selector_privateData *internal(new Selector_privateData(sel));
1456 return JSObjectMake(context, Selector_, internal);
1459 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1460 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1461 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1462 return reinterpret_cast<SEL>(internal->value_);
1464 return CYCastPointer<SEL>(context, value);
1467 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1468 return (void *) [[NSAutoreleasePool alloc] init];
1469 } CYSadCatch(NULL) }
1471 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1472 return [(NSAutoreleasePool *) handle release];
1475 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1477 return Instance::Make(context, nil);
1478 if (Class _class = objc_getClass(name.data))
1479 return CYMakeInstance(context, _class, true);
1480 if (Protocol *protocol = objc_getProtocol(name.data))
1481 return CYMakeInstance(context, protocol, true);
1483 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1485 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1486 ffi_call(cif, function, value, values);
1489 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1490 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1492 switch (type->primitive) {
1493 case sig::block_P: {
1494 _assert(type->data.signature.count != 0);
1495 sig::Signature signature;
1496 sig::Copy(*pool, signature, type->data.signature);
1498 sig::Element *elements(new(*pool) sig::Element[++signature.count]);
1499 elements[0] = signature.elements[0];
1500 memcpy(elements + 2, signature.elements + 1, sizeof(sig::Element) * (signature.count - 2));
1501 signature.elements = elements;
1503 elements[1].name = NULL;
1504 elements[1].type = new(*pool) sig::Type();
1505 elements[1].offset = _not(size_t);
1507 memset(elements[1].type, 0, sizeof(sig::Type));
1508 elements[1].type->primitive = sig::object_P;
1510 JSObjectRef function(CYCastJSObject(context, value));
1511 *reinterpret_cast<id *>(data) = CYMakeBlock(context, function, signature);
1515 case sig::typename_P:
1516 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1519 case sig::selector_P:
1520 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1528 } CYSadCatch(false) }
1530 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1531 switch (type->primitive) {
1532 // XXX: do something epic about blocks
1535 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1536 JSValueRef value(CYCastJSValue(context, object));
1542 case sig::typename_P:
1543 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1545 case sig::selector_P:
1546 if (SEL sel = *reinterpret_cast<SEL *>(data))
1547 return CYMakeSelector(context, sel);
1551 return CYJSNull(context);
1555 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1557 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1558 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1561 #if OBJC_API_VERSION >= 2
1563 method_getReturnType(method, type, sizeof(type));
1565 const char *type(method_getTypeEncoding(method));
1571 // XXX: possibly use a more "awesome" check?
1575 static const char *CYPoolTypeEncoding(CYPool &pool, JSContextRef context, SEL sel, objc_method *method) {
1577 return method_getTypeEncoding(method);
1579 const char *name(sel_getName(sel));
1580 size_t length(strlen(name));
1582 char keyed[length + 2];
1584 keyed[length + 1] = '\0';
1585 memcpy(keyed + 1, name, length);
1587 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1588 return entry->value_;
1593 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1594 JSObjectRef _this(CYCastJSObject(context, values[0]));
1595 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1598 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1599 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1602 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1603 Message_privateData *internal(new Message_privateData(sel, type, imp));
1604 return JSObjectMake(context, Message_, internal);
1607 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1608 JSObjectRef function(CYCastJSObject(context, value));
1610 sig::Signature signature;
1611 sig::Parse(pool, &signature, encoding, &Structor_);
1612 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageClosure_));
1613 // XXX: see notes in Library.cpp about needing to leak
1614 return reinterpret_cast<IMP>(internal->GetValue());
1617 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1618 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1619 Class _class(internal->GetValue());
1622 const char *name(CYPoolCString(pool, context, property));
1624 if (SEL sel = sel_getUid(name))
1625 if (class_getInstanceMethod(_class, sel) != NULL)
1631 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1632 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1633 Class _class(internal->GetValue());
1636 const char *name(CYPoolCString(pool, context, property));
1638 if (SEL sel = sel_getUid(name))
1639 if (objc_method *method = class_getInstanceMethod(_class, sel))
1640 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1645 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1646 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1647 Class _class(internal->GetValue());
1650 const char *name(CYPoolCString(pool, context, property));
1652 SEL sel(sel_registerName(name));
1654 objc_method *method(class_getInstanceMethod(_class, sel));
1659 if (JSValueIsObjectOfClass(context, value, Message_)) {
1660 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1661 type = sig::Unparse(pool, &message->signature_);
1662 imp = reinterpret_cast<IMP>(message->GetValue());
1664 type = CYPoolTypeEncoding(pool, context, sel, method);
1665 imp = CYMakeMessage(context, value, type);
1669 method_setImplementation(method, imp);
1672 GSMethodList list(GSAllocMethodList(1));
1673 GSAppendMethodToList(list, sel, type, imp, YES);
1674 GSAddMethodList(_class, list, YES);
1675 GSFlushMethodCacheForClass(_class);
1677 class_addMethod(_class, sel, imp, type);
1684 #if 0 && OBJC_API_VERSION < 2
1685 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1686 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1687 Class _class(internal->GetValue());
1690 const char *name(CYPoolCString(pool, context, property));
1692 if (SEL sel = sel_getUid(name))
1693 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1694 objc_method_list list = {NULL, 1, {method}};
1695 class_removeMethods(_class, &list);
1703 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1704 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1705 Class _class(internal->GetValue());
1707 #if OBJC_API_VERSION >= 2
1709 objc_method **data(class_copyMethodList(_class, &size));
1710 for (size_t i(0); i != size; ++i)
1711 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1714 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1715 for (int i(0); i != methods->method_count; ++i)
1716 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1720 static bool CYHasImplicitProperties(Class _class) {
1721 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1722 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1724 return [_class cy$hasImplicitProperties];
1727 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1728 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1729 id self(internal->GetValue());
1731 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1735 NSString *name(CYCastNSString(&pool, context, property));
1737 if (CYInternal *internal = [CYInternal get:self])
1738 if ([internal hasProperty:property inContext:context])
1741 Class _class(object_getClass(self));
1744 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1745 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1746 if ([self cy$hasProperty:name])
1748 } CYPoolCatch(false)
1750 const char *string(CYPoolCString(pool, context, name));
1753 if (class_getProperty(_class, string) != NULL)
1757 if (CYHasImplicitProperties(_class))
1758 if (SEL sel = sel_getUid(string))
1759 if (CYImplements(self, _class, sel, true))
1765 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1766 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1767 id self(internal->GetValue());
1769 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1770 return Internal::Make(context, self, object);
1773 NSString *name(CYCastNSString(&pool, context, property));
1775 if (CYInternal *internal = [CYInternal get:self])
1776 if (JSValueRef value = [internal getProperty:property inContext:context])
1780 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1784 const char *string(CYPoolCString(pool, context, name));
1785 Class _class(object_getClass(self));
1788 if (objc_property_t property = class_getProperty(_class, string)) {
1789 PropertyAttributes attributes(property);
1790 SEL sel(sel_registerName(attributes.Getter()));
1791 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1795 if (CYHasImplicitProperties(_class))
1796 if (SEL sel = sel_getUid(string))
1797 if (CYImplements(self, _class, sel, true))
1798 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1803 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1804 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1805 id self(internal->GetValue());
1809 NSString *name(CYCastNSString(&pool, context, property));
1810 NSObject *data(CYCastNSObject(&pool, context, value));
1813 if ([self cy$setProperty:name to:data])
1815 } CYPoolCatch(false)
1817 const char *string(CYPoolCString(pool, context, name));
1818 Class _class(object_getClass(self));
1821 if (objc_property_t property = class_getProperty(_class, string)) {
1822 PropertyAttributes attributes(property);
1823 if (const char *setter = attributes.Setter()) {
1824 SEL sel(sel_registerName(setter));
1825 JSValueRef arguments[1] = {value};
1826 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1832 size_t length(strlen(string));
1834 char set[length + 5];
1840 if (string[0] != '\0') {
1841 set[3] = toupper(string[0]);
1842 memcpy(set + 4, string + 1, length - 1);
1845 set[length + 3] = ':';
1846 set[length + 4] = '\0';
1848 if (SEL sel = sel_getUid(set))
1849 if (CYImplements(self, _class, sel)) {
1850 JSValueRef arguments[1] = {value};
1851 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1855 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1856 [internal setProperty:property toValue:value inContext:context];
1863 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1864 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1865 id self(internal->GetValue());
1868 NSString *name(CYCastNSString(NULL, context, property));
1869 return [self cy$deleteProperty:name];
1870 } CYPoolCatch(false)
1871 } CYCatch(false) return /*XXX*/ false; }
1873 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1874 const char *name(sel_getName(method_getName(method)));
1875 if (strchr(name, ':') != NULL)
1878 const char *type(method_getTypeEncoding(method));
1879 if (type == NULL || *type == '\0' || *type == 'v')
1882 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1885 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1886 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1887 id self(internal->GetValue());
1890 Class _class(object_getClass(self));
1895 objc_property_t *data(class_copyPropertyList(_class, &size));
1896 for (size_t i(0); i != size; ++i)
1897 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1902 if (CYHasImplicitProperties(_class))
1903 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1904 #if OBJC_API_VERSION >= 2
1906 objc_method **data(class_copyMethodList(current, &size));
1907 for (size_t i(0); i != size; ++i)
1908 Instance_getPropertyNames_message(names, data[i]);
1911 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1912 for (int i(0); i != methods->method_count; ++i)
1913 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1918 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1919 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1920 [self cy$getPropertyNames:names inContext:context];
1924 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1925 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1926 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1930 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1931 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1932 id self(internal->GetValue());
1934 if (![self isKindOfClass:NSBlock_])
1935 CYThrow("non-NSBlock object is not a function");
1936 // XXX: replace above logic with the following assertion
1937 //_assert([self isKindOfClass:NSBlock_]);
1938 // to do this, make it so FunctionInstance_ is the class of blocks
1939 // to do /that/, generalize the various "is exactly Instance_" checks
1940 // then, move Instance_callAsFunction to only be on FunctionInstance
1942 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1944 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1945 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1946 descriptor += sizeof(BlockDescriptor1);
1947 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1948 descriptor += sizeof(BlockDescriptor2);
1949 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1951 if (const char *type = descriptor3->signature) {
1957 sig::Signature signature;
1958 sig::Parse(pool, &signature, type, &Structor_);
1961 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1963 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1964 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1969 CYThrow("NSBlock without signature field passed arguments");
1973 } CYPoolCatch(NULL);
1978 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1979 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1980 Class _class(internal->GetValue());
1981 if (!CYIsClass(_class))
1984 if (CYJSValueIsNSObject(context, instance)) {
1985 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1986 // XXX: this isn't always safe
1987 return [linternal->GetValue() isKindOfClass:_class];
1993 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1995 throw CYJSError(context, "incorrect number of arguments to Instance");
1997 id value(CYCastNSObject(&pool, context, arguments[0]));
1999 value = [NSNull null];
2000 return CYCastJSValue(context, [value cy$box]);
2003 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2004 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2007 id self(internal->GetValue());
2008 const char *name(CYPoolCString(pool, context, property));
2010 if (object_getInstanceVariable(self, name, NULL) != NULL)
2016 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2017 length = CYCastDouble(encoding + 1);
2021 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2022 for (size_t i(0); i != size; ++i)
2023 if (ivars[i] == ivar)
2025 else if (ivar_getOffset(ivars[i]) == offset) {
2026 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2027 _assert(encoding[0] == 'b');
2028 shift += CYCastDouble(encoding + 1);
2033 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2034 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2037 id self(internal->GetValue());
2038 const char *name(CYPoolCString(pool, context, property));
2041 if (strcmp(name, "isa") == 0)
2042 return CYCastJSValue(context, object_getClass(self));
2045 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2046 ptrdiff_t offset(ivar_getOffset(ivar));
2047 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2049 const char *encoding(ivar_getTypeEncoding(ivar));
2050 if (encoding[0] == 'b') {
2051 unsigned length, shift;
2052 CYBitField(length, shift, self, ivar, encoding, offset);
2053 _assert(shift + length <= sizeof(uintptr_t) * 8);
2054 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2055 uintptr_t mask((1 << length) - 1);
2056 return CYCastJSValue(context, (field >> shift) & mask);
2058 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2059 return CYFromFFI(context, type.type_, type.GetFFI(), data);
2066 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2067 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2070 id self(internal->GetValue());
2071 const char *name(CYPoolCString(pool, context, property));
2073 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2074 ptrdiff_t offset(ivar_getOffset(ivar));
2075 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2077 const char *encoding(ivar_getTypeEncoding(ivar));
2078 if (encoding[0] == 'b') {
2079 unsigned length, shift;
2080 CYBitField(length, shift, self, ivar, encoding, offset);
2081 _assert(shift + length <= sizeof(uintptr_t) * 8);
2082 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2083 uintptr_t mask((1 << length) - 1);
2084 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2086 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2087 CYPoolFFI(&pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2095 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2096 if (Class super = class_getSuperclass(_class))
2097 Internal_getPropertyNames_(super, names);
2099 #if OBJC_API_VERSION >= 2
2101 objc_ivar **data(class_copyIvarList(_class, &size));
2102 for (size_t i(0); i != size; ++i)
2103 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2106 if (objc_ivar_list *ivars = _class->ivars)
2107 for (int i(0); i != ivars->ivar_count; ++i)
2108 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2112 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2113 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2116 id self(internal->GetValue());
2117 Class _class(object_getClass(self));
2119 Internal_getPropertyNames_(_class, names);
2122 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2123 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2124 return internal->GetOwner();
2127 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2129 NSString *name(CYCastNSString(&pool, context, property));
2130 if (Class _class = NSClassFromString(name))
2131 return CYMakeInstance(context, _class, true);
2136 static Class *CYCopyClassList(size_t &size) {
2137 size = objc_getClassList(NULL, 0);
2138 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2141 size_t writ(objc_getClassList(data, size));
2147 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2159 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2162 if (Class *data = CYCopyClassList(size)) {
2163 for (size_t i(0); i != size; ++i)
2164 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2169 while (Class _class = objc_next_class(&state))
2170 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2174 #if OBJC_API_VERSION >= 2
2175 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2176 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2179 const char *name(CYPoolCString(pool, context, property));
2181 const char **data(objc_copyClassNamesForImage(internal, &size));
2183 for (size_t i(0); i != size; ++i)
2184 if (strcmp(name, data[i]) == 0) {
2185 if (Class _class = objc_getClass(name)) {
2186 value = CYMakeInstance(context, _class, true);
2197 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2198 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2200 const char **data(objc_copyClassNamesForImage(internal, &size));
2201 for (size_t i(0); i != size; ++i)
2202 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2206 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2208 const char *name(CYPoolCString(pool, context, property));
2210 const char **data(objc_copyImageNames(&size));
2211 for (size_t i(0); i != size; ++i)
2212 if (strcmp(name, data[i]) == 0) {
2221 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2222 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2226 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2228 const char **data(objc_copyImageNames(&size));
2229 for (size_t i(0); i != size; ++i)
2230 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2235 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2237 const char *name(CYPoolCString(pool, context, property));
2238 if (Protocol *protocol = objc_getProtocol(name))
2239 return CYMakeInstance(context, protocol, true);
2243 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2244 #if OBJC_API_VERSION >= 2
2246 Protocol **data(objc_copyProtocolList(&size));
2247 for (size_t i(0); i != size; ++i)
2248 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2255 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2257 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2259 return Instance::Make(context, nil);
2263 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2264 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2268 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2269 *data = reinterpret_cast<void *>(address);
2270 return KERN_SUCCESS;
2274 std::set<Class> query_;
2275 JSContextRef context_;
2276 JSObjectRef results_;
2279 struct CYObjectStruct {
2283 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2284 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2285 JSContextRef context(choice->context_);
2287 for (unsigned i(0); i != count; ++i) {
2288 vm_range_t &range(ranges[i]);
2289 void *data(reinterpret_cast<void *>(range.address));
2290 size_t size(range.size);
2292 if (size < sizeof(CYObjectStruct))
2295 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2297 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2299 Class isa(reinterpret_cast<Class>(pointers[0]));
2302 std::set<Class>::const_iterator result(choice->query_.find(isa));
2303 if (result == choice->query_.end())
2306 // XXX: if (size < class_getInstanceSize(*result))
2307 if ((class_getInstanceSize(*result) + 15) / 16 * 16 != size)
2309 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2313 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2315 throw CYJSError(context, "choose() takes a class argument");
2317 CYGarbageCollect(context);
2320 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2322 vm_address_t *zones(NULL);
2324 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2325 _assert(error == KERN_SUCCESS);
2327 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2328 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2331 choice.context_ = context;
2332 choice.results_ = results;
2335 Class *classes(CYCopyClassList(number));
2336 _assert(classes != NULL);
2338 for (size_t i(0); i != number; ++i)
2339 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2340 if (current == _class) {
2341 choice.query_.insert(classes[i]);
2347 for (unsigned i(0); i != size; ++i) {
2348 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2349 if (zone == NULL || zone->introspect == NULL)
2352 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2360 #if defined(__i386__) || defined(__x86_64__)
2361 #define OBJC_MAX_STRUCT_BY_VALUE 8
2362 static int struct_forward_array[] = {
2363 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2364 #elif defined(__arm__)
2365 #define OBJC_MAX_STRUCT_BY_VALUE 1
2366 static int struct_forward_array[] = {
2368 #elif defined(__arm64__)
2371 #error missing objc-runtime-info
2375 static bool stret(ffi_type *ffi_type) {
2376 return ffi_type->type == FFI_TYPE_STRUCT && (
2377 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2378 struct_forward_array[ffi_type->size] != 0
2384 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2388 _class = object_getClass(self);
2392 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2393 imp = method_getImplementation(method);
2394 type = method_getTypeEncoding(method);
2399 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2401 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2402 type = CYPoolCString(pool, context, [method _typeString]);
2410 sig::Signature signature;
2411 sig::Parse(pool, &signature, type, &Structor_);
2413 size_t used(count + 3);
2414 if (used > signature.count) {
2415 sig::Element *elements(new (pool) sig::Element[used]);
2416 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2418 for (size_t index(signature.count); index != used; ++index) {
2419 sig::Element *element(&elements[index]);
2420 element->name = NULL;
2421 element->offset = _not(size_t);
2423 sig::Type *type(new (pool) sig::Type);
2424 memset(type, 0, sizeof(*type));
2425 type->primitive = sig::object_P;
2426 element->type = type;
2429 signature.elements = elements;
2430 signature.count = used;
2434 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2439 if (stret(cif.rtype))
2440 imp = class_getMethodImplementation_stret(_class, _cmd);
2443 imp = class_getMethodImplementation(_class, _cmd);
2445 objc_super super = {self, _class};
2446 imp = objc_msg_lookup_super(&super, _cmd);
2450 void (*function)() = reinterpret_cast<void (*)()>(imp);
2451 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2454 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2456 throw CYJSError(context, "too few arguments to objc_msgSend");
2466 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2467 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2468 self = internal->GetValue();
2469 _class = internal->class_;;
2470 uninitialized = false;
2471 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2472 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2473 self = internal->GetValue();
2475 uninitialized = internal->IsUninitialized();
2477 internal->value_ = nil;
2479 self = CYCastNSObject(&pool, context, arguments[0]);
2481 uninitialized = false;
2485 return CYJSNull(context);
2487 _cmd = CYCastSEL(context, arguments[1]);
2489 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2492 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2493 return $objc_msgSend(context, object, _this, count, arguments);
2496 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2497 JSValueRef setup[count + 2];
2500 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2501 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2504 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2506 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2508 // XXX: handle Instance::Uninitialized?
2509 id self(CYCastNSObject(&pool, context, _this));
2513 setup[1] = &internal->sel_;
2515 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2518 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2520 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2522 id self(CYCastNSObject(&pool, context, arguments[0]));
2523 Class _class(CYCastClass(pool, context, arguments[1]));
2524 return cy::Super::Make(context, self, _class);
2527 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2529 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2531 const char *name(CYPoolCString(pool, context, arguments[0]));
2532 return CYMakeSelector(context, sel_registerName(name));
2535 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2537 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2538 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2539 return CYMakeInstance(context, self, false);
2542 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2543 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2544 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2547 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2548 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2549 Type_privateData *typical(internal->GetType());
2554 if (typical == NULL) {
2558 type = typical->type_;
2559 ffi = typical->ffi_;
2562 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2565 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2566 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2567 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2570 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2571 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2572 id self(internal->GetValue());
2573 if (!CYIsClass(self))
2574 return CYJSUndefined(context);
2575 return CYGetClassPrototype(context, self);
2578 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2579 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2580 id self(internal->GetValue());
2581 if (!CYIsClass(self))
2582 return CYJSUndefined(context);
2583 return Messages::Make(context, (Class) self);
2586 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2587 if (!CYJSValueIsNSObject(context, _this))
2590 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2591 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2594 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2595 if (!CYJSValueIsNSObject(context, _this))
2598 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2599 id value(internal->GetValue());
2606 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2608 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2609 return CYJSUndefined(context);
2610 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2613 return CYCastJSValue(context, CYJSString(context, [value description]));
2615 } CYCatch(NULL) return /*XXX*/ NULL; }
2617 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2618 if (!CYJSValueIsNSObject(context, _this))
2621 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2622 id value(internal->GetValue());
2624 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2627 if (JSValueRef result = [value cy$valueOfInContext:context])
2631 } CYCatch(NULL) return /*XXX*/ NULL; }
2633 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2634 if (!CYJSValueIsNSObject(context, _this))
2637 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2638 // XXX: but... but... THIS ISN'T A POINTER! :(
2639 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2640 } CYCatch(NULL) return /*XXX*/ NULL; }
2642 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2643 if (!CYJSValueIsNSObject(context, _this))
2646 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2647 id value(internal->GetValue());
2650 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2651 return CYCastJSValue(context, CYJSString(context, [value description]));
2653 } CYCatch(NULL) return /*XXX*/ NULL; }
2655 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2656 if (!CYJSValueIsNSObject(context, _this))
2659 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2660 id value(internal->GetValue());
2662 if (!CYIsClass(value))
2663 CYThrow("non-Class object cannot be used as Type");
2665 // XXX: this is a very silly implementation
2667 std::ostringstream type;
2669 type << class_getName(value);
2673 return CYMakeType(context, type.str().c_str());
2675 } CYCatch(NULL) return /*XXX*/ NULL; }
2677 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2678 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2679 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2682 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2683 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2686 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2687 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2688 const char *name(sel_getName(internal->GetValue()));
2691 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2692 return CYCastJSValue(context, CYJSString(context, string));
2694 } CYCatch(NULL) return /*XXX*/ NULL; }
2696 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2698 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2701 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2702 SEL sel(internal->GetValue());
2704 objc_method *method;
2705 if (Class _class = CYCastClass(pool, context, arguments[0]))
2706 method = class_getInstanceMethod(_class, sel);
2710 const char *encoding(CYPoolTypeEncoding(pool, context, sel, method));
2711 if (encoding == NULL)
2712 return CYJSNull(context);
2714 sig::Signature signature;
2715 sig::Parse(pool, &signature, encoding, &Structor_);
2716 return CYMakeType(context, &signature);
2719 static JSStaticValue Selector_staticValues[2] = {
2720 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2721 {NULL, NULL, NULL, 0}
2724 static JSStaticValue Instance_staticValues[5] = {
2725 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2726 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2727 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2728 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2729 {NULL, NULL, NULL, 0}
2732 static JSStaticFunction Instance_staticFunctions[7] = {
2733 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2734 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2735 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2736 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2737 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2738 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2742 static JSStaticFunction Class_staticFunctions[2] = {
2743 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2747 static JSStaticFunction Internal_staticFunctions[2] = {
2748 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2752 static JSStaticFunction Selector_staticFunctions[5] = {
2753 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2754 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2755 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2756 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2761 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2762 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2763 } CYObjectiveCatch }
2766 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2767 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2768 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2769 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2771 CYPool &pool(CYGetGlobalPool());
2773 Object_type = new(pool) Type_privateData("@");
2774 Selector_type = new(pool) Type_privateData(":");
2776 NSArray_ = objc_getClass("NSArray");
2777 NSBlock_ = objc_getClass("NSBlock");
2778 NSDictionary_ = objc_getClass("NSDictionary");
2779 NSNumber_ = objc_getClass("NSNumber");
2780 NSString_ = objc_getClass("NSString");
2781 Object_ = objc_getClass("Object");
2784 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2786 // XXX: apparently, iOS now has both of these
2787 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2788 if (NSCFBoolean_ == nil)
2789 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2791 NSCFType_ = objc_getClass("NSCFType");
2793 NSZombie_ = objc_getClass("_NSZombie_");
2795 banned_.insert(Object_);
2796 banned_.insert(objc_getClass("__NSAtom"));
2797 banned_.insert(objc_getClass("__NSGenericDeallocHandler"));
2798 banned_.insert(objc_getClass("NSMessageBuilder"));
2799 banned_.insert(objc_getClass("__NSMessageBuilder"));
2801 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2804 JSClassDefinition definition;
2806 definition = kJSClassDefinitionEmpty;
2807 definition.className = "Instance";
2808 definition.staticValues = Instance_staticValues;
2809 definition.staticFunctions = Instance_staticFunctions;
2810 definition.hasProperty = &Instance_hasProperty;
2811 definition.getProperty = &Instance_getProperty;
2812 definition.setProperty = &Instance_setProperty;
2813 definition.deleteProperty = &Instance_deleteProperty;
2814 definition.getPropertyNames = &Instance_getPropertyNames;
2815 definition.callAsConstructor = &Instance_callAsConstructor;
2816 definition.callAsFunction = &Instance_callAsFunction;
2817 definition.hasInstance = &Instance_hasInstance;
2818 definition.finalize = &CYFinalize;
2819 Instance_ = JSClassCreate(&definition);
2821 definition.className = "ArrayInstance";
2822 ArrayInstance_ = JSClassCreate(&definition);
2824 definition.className = "BooleanInstance";
2825 BooleanInstance_ = JSClassCreate(&definition);
2827 definition.className = "FunctionInstance";
2828 FunctionInstance_ = JSClassCreate(&definition);
2830 definition.className = "NumberInstance";
2831 NumberInstance_ = JSClassCreate(&definition);
2833 definition.className = "ObjectInstance";
2834 ObjectInstance_ = JSClassCreate(&definition);
2836 definition.className = "StringInstance";
2837 StringInstance_ = JSClassCreate(&definition);
2839 definition = kJSClassDefinitionEmpty;
2840 definition.className = "Class";
2841 definition.staticFunctions = Class_staticFunctions;
2842 Class_ = JSClassCreate(&definition);
2844 definition = kJSClassDefinitionEmpty;
2845 definition.className = "Internal";
2846 definition.staticFunctions = Internal_staticFunctions;
2847 definition.hasProperty = &Internal_hasProperty;
2848 definition.getProperty = &Internal_getProperty;
2849 definition.setProperty = &Internal_setProperty;
2850 definition.getPropertyNames = &Internal_getPropertyNames;
2851 definition.finalize = &CYFinalize;
2852 Internal_ = JSClassCreate(&definition);
2854 definition = kJSClassDefinitionEmpty;
2855 definition.className = "Message";
2856 definition.staticFunctions = cy::Functor::StaticFunctions;
2857 definition.staticValues = cy::Functor::StaticValues;
2858 definition.callAsFunction = &Message_callAsFunction;
2859 definition.finalize = &CYFinalize;
2860 Message_ = JSClassCreate(&definition);
2862 definition = kJSClassDefinitionEmpty;
2863 definition.className = "Messages";
2864 definition.hasProperty = &Messages_hasProperty;
2865 definition.getProperty = &Messages_getProperty;
2866 definition.setProperty = &Messages_setProperty;
2867 #if 0 && OBJC_API_VERSION < 2
2868 definition.deleteProperty = &Messages_deleteProperty;
2870 definition.getPropertyNames = &Messages_getPropertyNames;
2871 definition.finalize = &CYFinalize;
2872 Messages_ = JSClassCreate(&definition);
2874 definition = kJSClassDefinitionEmpty;
2875 definition.className = "Selector";
2876 definition.staticValues = Selector_staticValues;
2877 definition.staticFunctions = Selector_staticFunctions;
2878 definition.callAsFunction = &Selector_callAsFunction;
2879 definition.finalize = &CYFinalize;
2880 Selector_ = JSClassCreate(&definition);
2882 definition = kJSClassDefinitionEmpty;
2883 definition.className = "Super";
2884 definition.staticFunctions = Internal_staticFunctions;
2885 definition.finalize = &CYFinalize;
2886 Super_ = JSClassCreate(&definition);
2888 definition = kJSClassDefinitionEmpty;
2889 definition.className = "ObjectiveC::Classes";
2890 definition.getProperty = &ObjectiveC_Classes_getProperty;
2891 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2892 ObjectiveC_Classes_ = JSClassCreate(&definition);
2894 definition = kJSClassDefinitionEmpty;
2895 definition.className = "ObjectiveC::Constants";
2896 definition.getProperty = &ObjectiveC_Constants_getProperty;
2897 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2898 ObjectiveC_Constants_ = JSClassCreate(&definition);
2900 #if OBJC_API_VERSION >= 2
2901 definition = kJSClassDefinitionEmpty;
2902 definition.className = "ObjectiveC::Images";
2903 definition.getProperty = &ObjectiveC_Images_getProperty;
2904 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2905 ObjectiveC_Images_ = JSClassCreate(&definition);
2907 definition = kJSClassDefinitionEmpty;
2908 definition.className = "ObjectiveC::Image::Classes";
2909 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2910 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2911 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2914 definition = kJSClassDefinitionEmpty;
2915 definition.className = "ObjectiveC::Protocols";
2916 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2917 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2918 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2921 // XXX: this is horrible; there has to be a better way to do this
2923 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24");
2925 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2930 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2931 JSObjectRef global(CYGetGlobalObject(context));
2932 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2933 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2934 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2935 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2937 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2938 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2940 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2941 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2942 CYArrayPush(context, alls, protocols);
2944 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2945 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2946 CYArrayPush(context, alls, classes);
2948 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2949 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2950 CYArrayPush(context, alls, constants);
2952 #if OBJC_API_VERSION >= 2
2953 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2956 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2957 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2958 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2959 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2960 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2962 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2963 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2965 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2966 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2967 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2968 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2969 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2971 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2972 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2973 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2974 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2975 JSObjectSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2977 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2978 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2979 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2980 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2981 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2983 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2984 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2985 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2986 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2987 JSObjectSetPrototype(context, NumberInstance_prototype, Number_prototype);
2989 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2990 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2991 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2992 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2993 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2995 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2996 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2997 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2998 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2999 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
3001 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
3002 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
3003 JSObjectSetPrototype(context, Class_prototype, Instance_prototype);
3005 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3006 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3007 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3009 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3010 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3013 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3016 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3018 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3019 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3022 static CYHooks CYObjectiveCHooks = {
3023 &CYObjectiveC_ExecuteStart,
3024 &CYObjectiveC_ExecuteEnd,
3025 &CYObjectiveC_CallFunction,
3026 &CYObjectiveC_Initialize,
3027 &CYObjectiveC_SetupContext,
3028 &CYObjectiveC_PoolFFI,
3029 &CYObjectiveC_FromFFI,
3032 struct CYObjectiveC {
3034 hooks_ = &CYObjectiveCHooks;
3035 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
3036 _assert(hooks_ != NULL);
3040 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3041 CYSetupContext(context);
3042 } CYObjectiveCatch }
3044 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3047 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3048 utf8 = CYPoolCode(pool, utf8);
3050 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3051 size_t bytes(utf16.size * sizeof(uint16_t));
3052 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3053 memcpy(copy, utf16.data, bytes);
3057 } catch (const CYException &exception) {
3059 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];