1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2013 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
22 #include <Foundation/Foundation.h>
24 #include "ObjectiveC/Internal.hpp"
26 #include <objc/objc-api.h>
28 #include "cycript.hpp"
30 #include "ObjectiveC/Internal.hpp"
33 #include <CoreFoundation/CoreFoundation.h>
34 #include <JavaScriptCore/JSStringRefCF.h>
35 #include <objc/runtime.h>
39 #include <malloc/malloc.h>
40 #include <mach/mach.h>
44 #include "JavaScript.hpp"
46 #include "Execute.hpp"
54 #define CYObjectiveTry_ { \
56 #define CYObjectiveTry { \
57 JSContextRef context(context_); \
59 #define CYObjectiveCatch \
60 catch (const CYException &error) { \
61 @throw CYCastNSObject(NULL, context, error.CastJSValue(context)); \
67 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
69 #define CYPoolCatch(value) \
70 @catch (NSException *error) { \
71 _saved = [error retain]; \
72 throw CYJSError(context, CYCastJSValue(context, error)); \
77 [_saved autorelease]; \
83 #define CYSadCatch(value) \
84 @catch (NSException *error ) { \
85 throw CYJSError(context, CYCastJSValue(context, error)); \
90 #define class_getSuperclass GSObjCSuper
91 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
92 #define class_getName GSNameFromClass
94 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
96 #define ivar_getName(ivar) ((ivar)->ivar_name)
97 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
98 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
100 #define method_getName(method) ((method)->method_name)
101 #define method_getImplementation(method) ((method)->method_imp)
102 #define method_getTypeEncoding(method) ((method)->method_types)
103 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
106 #define objc_getClass GSClassFromName
108 #define objc_getProtocol GSProtocolFromName
110 #define object_getClass GSObjCClass
112 #define object_getInstanceVariable(object, name, value) ({ \
113 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
114 _assert(value != NULL); \
116 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
120 #define object_setIvar(object, ivar, value) ({ \
121 void *data = (value); \
122 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
125 #define protocol_getName(protocol) [(protocol) name]
128 static void (*$objc_setAssociatedObject)(id object, void *key, id value, objc_AssociationPolicy policy);
129 static id (*$objc_getAssociatedObject)(id object, void *key);
130 static void (*$objc_removeAssociatedObjects)(id object);
132 struct BlockLiteral {
136 void (*invoke)(void *, ...);
140 struct BlockDescriptor1 {
141 unsigned long int reserved;
142 unsigned long int size;
145 struct BlockDescriptor2 {
146 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
147 void (*dispose_helper)(BlockLiteral *src);
150 struct BlockDescriptor3 {
151 const char *signature;
156 BLOCK_DEALLOCATING = 0x0001,
157 BLOCK_REFCOUNT_MASK = 0xfffe,
158 BLOCK_NEEDS_FREE = 1 << 24,
159 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
160 BLOCK_HAS_CTOR = 1 << 26,
161 BLOCK_IS_GC = 1 << 27,
162 BLOCK_IS_GLOBAL = 1 << 28,
163 BLOCK_HAS_STRET = 1 << 29,
164 BLOCK_HAS_SIGNATURE = 1 << 30,
167 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
169 /* Objective-C Pool Release {{{ */
170 void CYPoolRelease_(void *data) {
171 id object(reinterpret_cast<id>(data));
175 id CYPoolRelease_(CYPool *pool, id object) {
178 else if (pool == NULL)
179 return [object autorelease];
181 pool->atexit(CYPoolRelease_);
186 template <typename Type_>
187 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
188 return (Type_) CYPoolRelease_(pool, (id) object);
191 /* Objective-C Strings {{{ */
192 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
193 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
194 char *string(new(pool) char[size]);
195 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
196 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
200 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
202 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
205 return CYCopyJSString(CYPoolCString(pool, context, value));
209 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
212 // XXX: this definition scares me; is anyone using this?!
213 NSString *string([value description]);
214 return CYCopyJSString(context, string);
217 NSString *CYCopyNSString(const CYUTF8String &value) {
219 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
221 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
225 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
227 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
230 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
234 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
235 return CYCopyNSString(context, CYJSString(context, value));
238 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
239 return CYPoolRelease(pool, CYCopyNSString(value));
242 NSString *CYCastNSString(CYPool *pool, SEL sel) {
243 const char *name(sel_getName(sel));
244 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
247 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
248 return CYPoolRelease(pool, CYCopyNSString(context, value));
251 CYUTF8String CYCastUTF8String(NSString *value) {
252 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
253 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
257 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
259 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
260 if (exception == NULL)
262 *exception = CYCastJSValue(context, error);
265 size_t CYGetIndex(NSString *value) {
266 return CYGetIndex(CYCastUTF8String(value));
269 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
270 return CYGetOffset(CYPoolCString(pool, context, value), index);
273 static JSClassRef Instance_;
275 static JSClassRef ArrayInstance_;
276 static JSClassRef FunctionInstance_;
277 static JSClassRef ObjectInstance_;
278 static JSClassRef StringInstance_;
280 static JSClassRef Class_;
281 static JSClassRef Internal_;
282 static JSClassRef Message_;
283 static JSClassRef Messages_;
284 static JSClassRef Selector_;
285 static JSClassRef Super_;
287 static JSClassRef ObjectiveC_Classes_;
288 static JSClassRef ObjectiveC_Constants_;
289 static JSClassRef ObjectiveC_Protocols_;
292 static JSClassRef ObjectiveC_Image_Classes_;
293 static JSClassRef ObjectiveC_Images_;
297 static Class NSCFBoolean_;
298 static Class NSCFType_;
299 static Class NSGenericDeallocHandler_;
300 static Class NSZombie_;
302 static std::set<Class> banned_;
304 static Class NSBoolNumber_;
307 static Class NSArray_;
308 static Class NSBlock_;
309 static Class NSDictionary_;
310 static Class NSString_;
311 static Class Object_;
313 static Type_privateData *Object_type;
314 static Type_privateData *Selector_type;
316 Type_privateData *Instance::GetType() const {
320 Type_privateData *Selector_privateData::GetType() const {
321 return Selector_type;
324 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
326 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
328 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
329 else if (meta && !class_isMetaClass(self))
330 return CYGetCachedObject(context, CYJSString("Class_prototype"));
332 JSObjectRef global(CYGetGlobalObject(context));
333 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
336 sprintf(label, "i%p", self);
337 CYJSString name(label);
339 JSValueRef value(CYGetProperty(context, cy, name));
340 if (!JSValueIsUndefined(context, value))
343 JSClassRef _class(NULL);
344 JSValueRef prototype;
346 if (self == NSArray_)
347 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
348 else if (self == NSBlock_)
349 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
350 else if (self == NSDictionary_)
351 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
352 else if (self == NSString_)
353 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
355 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
357 JSObjectRef object(JSObjectMake(context, _class, NULL));
358 JSObjectSetPrototype(context, object, prototype);
359 CYSetProperty(context, cy, name, object);
364 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
365 return CYGetClassPrototype(context, self, class_isMetaClass(self));
368 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
369 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
370 if (Class super = class_getSuperclass(_class))
371 JSObjectSetPrototype(context, value, Messages::Make(context, super));
375 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
376 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
380 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
381 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
385 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
386 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
387 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
391 Instance::~Instance() {
392 if ((flags_ & Transient) == 0)
393 // XXX: does this handle background threads correctly?
394 // XXX: this simply does not work on the console because I'm stupid
395 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
398 struct Message_privateData :
403 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
404 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
410 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
411 Instance::Flags flags;
414 flags = Instance::Transient;
416 flags = Instance::None;
417 object = [object retain];
420 return Instance::Make(context, object, flags);
423 @interface NSMethodSignature (Cycript)
424 - (NSString *) _typeString;
427 @interface NSObject (Cycript)
429 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
430 - (JSType) cy$JSType;
432 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
433 - (NSString *) cy$toCYON:(bool)objective;
435 - (bool) cy$hasProperty:(NSString *)name;
436 - (NSObject *) cy$getProperty:(NSString *)name;
437 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
438 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
439 - (bool) cy$deleteProperty:(NSString *)name;
440 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
442 + (bool) cy$hasImplicitProperties;
448 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
451 NSString *CYCastNSCYON(id value, bool objective) {
457 Class _class(object_getClass(value));
458 SEL sel(@selector(cy$toCYON:));
460 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
461 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
462 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
463 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
464 string = [value cy$toCYON:objective];
469 else if (value == NSZombie_)
470 string = @"_NSZombie_";
471 else if (_class == NSZombie_)
472 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
473 // XXX: frowny /in/ the pants
474 else if (banned_.find(value) != banned_.end())
478 string = [NSString stringWithFormat:@"%@", value];
483 string = @"undefined";
490 struct PropertyAttributes {
495 const char *variable;
508 PropertyAttributes(objc_property_t property) :
520 name = property_getName(property);
521 const char *attributes(property_getAttributes(property));
523 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
524 if ((next = strchr(token, ',')) != NULL)
527 case 'R': readonly = true; break;
528 case 'C': copy = true; break;
529 case '&': retain = true; break;
530 case 'N': nonatomic = true; break;
531 case 'G': getter_ = token + 1; break;
532 case 'S': setter_ = token + 1; break;
533 case 'V': variable = token + 1; break;
537 /*if (variable == NULL) {
538 variable = property_getName(property);
539 size_t size(strlen(variable));
540 char *name(new(pool_) char[size + 2]);
542 memcpy(name + 1, variable, size);
543 name[size + 1] = '\0';
548 const char *Getter() {
550 getter_ = pool_.strdup(name);
554 const char *Setter() {
555 if (setter_ == NULL && !readonly) {
556 size_t length(strlen(name));
558 char *temp(new(pool_) char[length + 5]);
564 temp[3] = toupper(name[0]);
565 memcpy(temp + 4, name + 1, length - 1);
568 temp[length + 3] = ':';
569 temp[length + 4] = '\0';
579 @interface CYWebUndefined : NSObject {
582 + (CYWebUndefined *) undefined;
586 @implementation CYWebUndefined
588 + (CYWebUndefined *) undefined {
589 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
595 #define WebUndefined CYWebUndefined
597 /* Bridge: CYJSObject {{{ */
598 @interface CYJSObject : NSMutableDictionary {
600 JSGlobalContextRef context_;
603 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
605 - (NSUInteger) count;
606 - (id) objectForKey:(id)key;
607 - (NSEnumerator *) keyEnumerator;
608 - (void) setObject:(id)object forKey:(id)key;
609 - (void) removeObjectForKey:(id)key;
613 /* Bridge: CYJSArray {{{ */
614 @interface CYJSArray : NSMutableArray {
616 JSGlobalContextRef context_;
619 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
621 - (NSUInteger) count;
622 - (id) objectAtIndex:(NSUInteger)index;
624 - (void) addObject:(id)anObject;
625 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
626 - (void) removeLastObject;
627 - (void) removeObjectAtIndex:(NSUInteger)index;
628 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
633 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
634 return JSValueIsObjectOfClass(context, value, Instance_);
637 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
638 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
641 NSObject *CYMakeBlock(void (*invoke)(), sig::Signature &signature) {
642 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
646 BlockDescriptor1 one_;
647 BlockDescriptor2 two_;
648 BlockDescriptor3 three_;
654 Descriptor *descriptor(new Descriptor);
655 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
657 literal->isa = objc_getClass("__NSGlobalBlock__");
658 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
659 literal->reserved = 0;
660 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(invoke);
661 literal->descriptor = descriptor;
663 descriptor->d_.one_.size = sizeof(descriptor->d_);
664 descriptor->d_.three_.signature = sig::Unparse(descriptor->pool_, &signature);
666 return reinterpret_cast<NSObject *>(literal);
669 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
670 if (CYJSValueIsNSObject(context, object)) {
671 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
672 return internal->GetValue();
675 if (JSValueIsObjectOfClass(context, object, Functor_)) {
676 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
677 return CYMakeBlock(internal->GetValue(), internal->signature_);
680 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
681 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
682 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
685 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
686 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
690 @interface NSBoolNumber : NSNumber {
695 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
699 switch (JSType type = JSValueGetType(context, value)) {
700 case kJSTypeUndefined:
701 object = [WebUndefined undefined];
711 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
714 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
720 object = CYCopyNSNumber(context, value);
725 object = CYCopyNSString(context, value);
730 // XXX: this might could be more efficient
731 object = CYCastNSObject(pool, context, (JSObjectRef) value);
736 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
743 return CYPoolRelease(pool, object);
745 return [object retain];
748 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
749 return CYNSObject(pool, context, value, true);
752 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
753 return CYNSObject(&pool, context, value, false);
756 /* Bridge: NSArray {{{ */
757 @implementation NSArray (Cycript)
760 return [[self mutableCopy] autorelease];
763 - (NSString *) cy$toCYON:(bool)objective {
764 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
765 [json appendString:@"@["];
769 for (id object in self) {
771 for (size_t index(0), count([self count]); index != count; ++index) {
772 id object([self objectAtIndex:index]);
775 [json appendString:@","];
778 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
779 [json appendString:CYCastNSCYON(object, true)];
781 [json appendString:@","];
786 [json appendString:@"]"];
790 - (bool) cy$hasProperty:(NSString *)name {
791 if ([name isEqualToString:@"length"])
794 size_t index(CYGetIndex(name));
795 if (index == _not(size_t) || index >= [self count])
796 return [super cy$hasProperty:name];
801 - (NSObject *) cy$getProperty:(NSString *)name {
802 size_t index(CYGetIndex(name));
803 if (index == _not(size_t) || index >= [self count])
804 return [super cy$getProperty:name];
806 return [self objectAtIndex:index];
809 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
811 if ([name isEqualToString:@"length"])
812 return CYCastJSValue(context, [self count]);
815 return [super cy$getProperty:name inContext:context];
818 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
819 [super cy$getPropertyNames:names inContext:context];
821 for (size_t index(0), count([self count]); index != count; ++index) {
822 id object([self objectAtIndex:index]);
823 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
825 sprintf(name, "%zu", index);
826 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
831 + (bool) cy$hasImplicitProperties {
837 /* Bridge: NSBlock {{{ */
844 /* Bridge: NSBoolNumber {{{ */
846 @implementation NSBoolNumber (Cycript)
848 - (JSType) cy$JSType {
849 return kJSTypeBoolean;
852 - (NSString *) cy$toCYON:(bool)objective {
853 NSString *value([self boolValue] ? @"true" : @"false");
854 return objective ? value : [NSString stringWithFormat:@"@%@", value];
857 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
858 return CYCastJSValue(context, (bool) [self boolValue]);
864 /* Bridge: NSDictionary {{{ */
865 @implementation NSDictionary (Cycript)
868 return [[self mutableCopy] autorelease];
871 - (NSString *) cy$toCYON:(bool)objective {
872 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
873 [json appendString:@"@{"];
877 for (NSObject *key in self) {
879 NSEnumerator *keys([self keyEnumerator]);
880 while (NSObject *key = [keys nextObject]) {
883 [json appendString:@","];
886 [json appendString:CYCastNSCYON(key, true)];
887 [json appendString:@":"];
888 NSObject *object([self objectForKey:key]);
889 [json appendString:CYCastNSCYON(object, true)];
892 [json appendString:@"}"];
896 - (bool) cy$hasProperty:(NSString *)name {
897 return [self objectForKey:name] != nil;
900 - (NSObject *) cy$getProperty:(NSString *)name {
901 return [self objectForKey:name];
904 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
905 [super cy$getPropertyNames:names inContext:context];
908 for (NSObject *key in self) {
910 NSEnumerator *keys([self keyEnumerator]);
911 while (NSObject *key = [keys nextObject]) {
913 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
917 + (bool) cy$hasImplicitProperties {
923 /* Bridge: NSMutableArray {{{ */
924 @implementation NSMutableArray (Cycript)
926 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
927 if ([name isEqualToString:@"length"]) {
928 // XXX: is this not intelligent?
929 NSNumber *number(reinterpret_cast<NSNumber *>(value));
931 NSUInteger size([number unsignedIntegerValue]);
933 NSUInteger size([number unsignedIntValue]);
935 NSUInteger count([self count]);
937 [self removeObjectsInRange:NSMakeRange(size, count - size)];
938 else if (size != count) {
939 WebUndefined *undefined([WebUndefined undefined]);
940 for (size_t i(count); i != size; ++i)
941 [self addObject:undefined];
946 size_t index(CYGetIndex(name));
947 if (index == _not(size_t))
948 return [super cy$setProperty:name to:value];
950 id object(value ?: [NSNull null]);
952 size_t count([self count]);
954 [self replaceObjectAtIndex:index withObject:object];
956 if (index != count) {
957 WebUndefined *undefined([WebUndefined undefined]);
958 for (size_t i(count); i != index; ++i)
959 [self addObject:undefined];
962 [self addObject:object];
968 - (bool) cy$deleteProperty:(NSString *)name {
969 size_t index(CYGetIndex(name));
970 if (index == _not(size_t) || index >= [self count])
971 return [super cy$deleteProperty:name];
972 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
978 /* Bridge: NSMutableDictionary {{{ */
979 @implementation NSMutableDictionary (Cycript)
981 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
982 [self setObject:(value ?: [NSNull null]) forKey:name];
986 - (bool) cy$deleteProperty:(NSString *)name {
987 if ([self objectForKey:name] == nil)
990 [self removeObjectForKey:name];
997 /* Bridge: NSNumber {{{ */
998 @implementation NSNumber (Cycript)
1000 - (JSType) cy$JSType {
1002 // XXX: this just seems stupid
1003 if ([self class] == NSCFBoolean_)
1004 return kJSTypeBoolean;
1006 return kJSTypeNumber;
1009 - (NSString *) cy$toCYON:(bool)objective {
1010 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1011 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1014 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1015 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1016 } CYObjectiveCatch }
1020 /* Bridge: NSNull {{{ */
1021 @implementation NSNull (Cycript)
1023 - (JSType) cy$JSType {
1027 - (NSString *) cy$toCYON:(bool)objective {
1028 NSString *value(@"null");
1029 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1032 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1033 return CYJSNull(context);
1034 } CYObjectiveCatch }
1038 /* Bridge: NSObject {{{ */
1039 @implementation NSObject (Cycript)
1045 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1046 return [self cy$valueOfInContext:context];
1049 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1051 } CYObjectiveCatch }
1053 - (JSType) cy$JSType {
1054 return kJSTypeObject;
1057 - (NSString *) cy$toCYON:(bool)objective {
1058 return [[self description] cy$toCYON:objective];
1061 - (bool) cy$hasProperty:(NSString *)name {
1065 - (NSObject *) cy$getProperty:(NSString *)name {
1069 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1070 if (NSObject *value = [self cy$getProperty:name])
1071 return CYCastJSValue(context, value);
1073 } CYObjectiveCatch }
1075 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1079 - (bool) cy$deleteProperty:(NSString *)name {
1083 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1086 + (bool) cy$hasImplicitProperties {
1092 /* Bridge: NSProxy {{{ */
1093 @implementation NSProxy (Cycript)
1095 - (NSString *) cy$toCYON:(bool)objective {
1096 return [[self description] cy$toCYON:objective];
1101 /* Bridge: NSString {{{ */
1102 @implementation NSString (Cycript)
1105 return [[self copy] autorelease];
1108 - (JSType) cy$JSType {
1109 return kJSTypeString;
1112 - (NSString *) cy$toCYON:(bool)objective {
1113 std::ostringstream str;
1116 CYUTF8String string(CYCastUTF8String(self));
1117 CYStringify(str, string.data, string.size);
1118 std::string value(str.str());
1119 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1122 - (bool) cy$hasProperty:(NSString *)name {
1123 size_t index(CYGetIndex(name));
1124 if (index == _not(size_t) || index >= [self length])
1125 return [super cy$hasProperty:name];
1130 - (NSObject *) cy$getProperty:(NSString *)name {
1131 size_t index(CYGetIndex(name));
1132 if (index == _not(size_t) || index >= [self length])
1133 return [super cy$getProperty:name];
1135 return [self substringWithRange:NSMakeRange(index, 1)];
1138 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1139 [super cy$getPropertyNames:names inContext:context];
1141 for (size_t index(0), length([self length]); index != length; ++index) {
1143 sprintf(name, "%zu", index);
1144 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1148 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1149 return CYCastJSValue(context, CYJSString(context, self));
1150 } CYObjectiveCatch }
1154 /* Bridge: WebUndefined {{{ */
1155 @implementation WebUndefined (Cycript)
1157 - (JSType) cy$JSType {
1158 return kJSTypeUndefined;
1161 - (NSString *) cy$toCYON:(bool)objective {
1162 NSString *value(@"undefined");
1163 return value; // XXX: maybe use the below code, adding @undefined?
1164 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1167 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1168 return CYJSUndefined(context);
1169 } CYObjectiveCatch }
1174 static bool CYIsClass(id self) {
1176 return class_isMetaClass(object_getClass(self));
1178 return GSObjCIsClass(self);
1182 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1183 id self(CYCastNSObject(&pool, context, value));
1184 if (CYIsClass(self))
1185 return (Class) self;
1186 throw CYJSError(context, "got something that is not a Class");
1190 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1192 size_t size(JSPropertyNameArrayGetCount(names));
1193 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1194 for (size_t index(0); index != size; ++index)
1195 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1199 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1201 return CYJSNull(context);
1203 return CYMakeInstance(context, value, false);
1204 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1206 @implementation CYJSObject
1208 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1209 if ((self = [super init]) != nil) {
1211 context_ = CYGetJSContext(context);
1212 JSGlobalContextRetain(context_);
1213 JSValueProtect(context_, object_);
1215 } CYObjectiveCatch }
1217 - (void) dealloc { CYObjectiveTry {
1218 JSValueUnprotect(context_, object_);
1219 JSGlobalContextRelease(context_);
1221 } CYObjectiveCatch }
1223 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1225 const char *cyon(CYPoolCCYON(pool, context, object_));
1227 return [super cy$toCYON:objective];
1229 return [NSString stringWithUTF8String:cyon];
1230 } CYObjectiveCatch }
1232 - (NSUInteger) count { CYObjectiveTry {
1233 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1234 size_t size(JSPropertyNameArrayGetCount(names));
1235 JSPropertyNameArrayRelease(names);
1237 } CYObjectiveCatch }
1239 - (id) objectForKey:(id)key { CYObjectiveTry {
1240 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1241 if (JSValueIsUndefined(context, value))
1243 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1244 } CYObjectiveCatch }
1246 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1247 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1248 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1249 JSPropertyNameArrayRelease(names);
1251 } CYObjectiveCatch }
1253 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1254 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1255 } CYObjectiveCatch }
1257 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1258 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1259 } CYObjectiveCatch }
1263 @implementation CYJSArray
1265 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1267 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_)];
1268 } CYObjectiveCatch }
1270 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1271 if ((self = [super init]) != nil) {
1273 context_ = CYGetJSContext(context);
1274 JSGlobalContextRetain(context_);
1275 JSValueProtect(context_, object_);
1277 } CYObjectiveCatch }
1279 - (void) dealloc { CYObjectiveTry {
1280 JSValueUnprotect(context_, object_);
1281 JSGlobalContextRelease(context_);
1283 } CYObjectiveCatch }
1285 - (NSUInteger) count { CYObjectiveTry {
1286 return CYArrayLength(context, object_);
1287 } CYObjectiveCatch }
1289 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1290 size_t bounds([self count]);
1291 if (index >= bounds)
1292 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1293 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1294 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1295 } CYObjectiveCatch }
1297 - (void) addObject:(id)object { CYObjectiveTry {
1298 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1299 } CYObjectiveCatch }
1301 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1302 size_t bounds([self count] + 1);
1303 if (index >= bounds)
1304 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1305 JSValueRef arguments[3];
1306 arguments[0] = CYCastJSValue(context, index);
1307 arguments[1] = CYCastJSValue(context, 0);
1308 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1309 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1310 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1311 } CYObjectiveCatch }
1313 - (void) removeLastObject { CYObjectiveTry {
1314 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1315 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1316 } CYObjectiveCatch }
1318 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1319 size_t bounds([self count]);
1320 if (index >= bounds)
1321 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1322 JSValueRef arguments[2];
1323 arguments[0] = CYCastJSValue(context, index);
1324 arguments[1] = CYCastJSValue(context, 1);
1325 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1326 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1327 } CYObjectiveCatch }
1329 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1330 size_t bounds([self count]);
1331 if (index >= bounds)
1332 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1333 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1334 } CYObjectiveCatch }
1338 // XXX: inherit from or replace with CYJSObject
1339 @interface CYInternal : NSObject {
1340 JSGlobalContextRef context_;
1341 JSObjectRef object_;
1346 @implementation CYInternal
1348 - (void) dealloc { CYObjectiveTry {
1349 JSValueUnprotect(context_, object_);
1350 JSGlobalContextRelease(context_);
1352 } CYObjectiveCatch }
1354 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1355 if ((self = [super init]) != nil) {
1356 context_ = CYGetJSContext(context);
1357 JSGlobalContextRetain(context_);
1359 } CYObjectiveCatch }
1361 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1362 if (object_ == NULL)
1365 return JSObjectHasProperty(context, object_, name);
1368 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1369 if (object_ == NULL)
1372 return CYGetProperty(context, object_, name);
1375 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1376 @synchronized (self) {
1377 if (object_ == NULL) {
1378 object_ = JSObjectMake(context, NULL, NULL);
1379 JSValueProtect(context, object_);
1383 CYSetProperty(context, object_, name, value);
1386 + (CYInternal *) get:(id)object {
1387 if ($objc_getAssociatedObject == NULL)
1390 @synchronized (object) {
1391 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1398 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1399 if ($objc_getAssociatedObject == NULL)
1402 @synchronized (object) {
1403 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1406 if ($objc_setAssociatedObject == NULL)
1409 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1410 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1419 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1420 Selector_privateData *internal(new Selector_privateData(sel));
1421 return JSObjectMake(context, Selector_, internal);
1424 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1425 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1426 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1427 return reinterpret_cast<SEL>(internal->value_);
1429 return CYCastPointer<SEL>(context, value);
1432 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1433 return (void *) [[NSAutoreleasePool alloc] init];
1434 } CYSadCatch(NULL) }
1436 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1437 return [(NSAutoreleasePool *) handle release];
1440 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1442 return Instance::Make(context, nil);
1443 if (Class _class = objc_getClass(name.data))
1444 return CYMakeInstance(context, _class, true);
1445 if (Protocol *protocol = objc_getProtocol(name.data))
1446 return CYMakeInstance(context, protocol, true);
1448 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1450 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1451 ffi_call(cif, function, value, values);
1454 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1455 switch (type->primitive) {
1456 // XXX: do something epic about blocks
1459 case sig::typename_P:
1460 // XXX: this works for return values, but not for properties and fields
1461 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1464 case sig::selector_P:
1465 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1473 } CYSadCatch(false) }
1475 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1476 switch (type->primitive) {
1477 // XXX: do something epic about blocks
1480 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1481 JSValueRef value(CYCastJSValue(context, object));
1487 case sig::typename_P:
1488 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1490 case sig::selector_P:
1491 if (SEL sel = *reinterpret_cast<SEL *>(data))
1492 return CYMakeSelector(context, sel);
1496 return CYJSNull(context);
1500 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1502 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1503 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1506 #if OBJC_API_VERSION >= 2
1508 method_getReturnType(method, type, sizeof(type));
1510 const char *type(method_getTypeEncoding(method));
1516 // XXX: possibly use a more "awesome" check?
1520 static const char *CYPoolTypeEncoding(CYPool &pool, JSContextRef context, SEL sel, objc_method *method) {
1522 return method_getTypeEncoding(method);
1524 const char *name(sel_getName(sel));
1525 size_t length(strlen(name));
1527 char keyed[length + 2];
1529 keyed[length + 1] = '\0';
1530 memcpy(keyed + 1, name, length);
1532 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1533 return entry->value_;
1538 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1539 JSObjectRef _this(CYCastJSObject(context, values[0]));
1540 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1543 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1544 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1547 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1548 Message_privateData *internal(new Message_privateData(sel, type, imp));
1549 return JSObjectMake(context, Message_, internal);
1552 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1553 JSObjectRef function(CYCastJSObject(context, value));
1555 sig::Signature signature;
1556 sig::Parse(pool, &signature, encoding, &Structor_);
1557 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageClosure_));
1558 // XXX: see notes in Library.cpp about needing to leak
1559 return reinterpret_cast<IMP>(internal->GetValue());
1562 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1563 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1564 Class _class(internal->GetValue());
1567 const char *name(CYPoolCString(pool, context, property));
1569 if (SEL sel = sel_getUid(name))
1570 if (class_getInstanceMethod(_class, sel) != NULL)
1576 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1577 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1578 Class _class(internal->GetValue());
1581 const char *name(CYPoolCString(pool, context, property));
1583 if (SEL sel = sel_getUid(name))
1584 if (objc_method *method = class_getInstanceMethod(_class, sel))
1585 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1590 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1591 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1592 Class _class(internal->GetValue());
1595 const char *name(CYPoolCString(pool, context, property));
1597 SEL sel(sel_registerName(name));
1599 objc_method *method(class_getInstanceMethod(_class, sel));
1604 if (JSValueIsObjectOfClass(context, value, Message_)) {
1605 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1606 type = sig::Unparse(pool, &message->signature_);
1607 imp = reinterpret_cast<IMP>(message->GetValue());
1609 type = CYPoolTypeEncoding(pool, context, sel, method);
1610 imp = CYMakeMessage(context, value, type);
1614 method_setImplementation(method, imp);
1617 GSMethodList list(GSAllocMethodList(1));
1618 GSAppendMethodToList(list, sel, type, imp, YES);
1619 GSAddMethodList(_class, list, YES);
1620 GSFlushMethodCacheForClass(_class);
1622 class_addMethod(_class, sel, imp, type);
1629 #if 0 && OBJC_API_VERSION < 2
1630 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1631 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1632 Class _class(internal->GetValue());
1635 const char *name(CYPoolCString(pool, context, property));
1637 if (SEL sel = sel_getUid(name))
1638 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1639 objc_method_list list = {NULL, 1, {method}};
1640 class_removeMethods(_class, &list);
1648 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1649 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1650 Class _class(internal->GetValue());
1652 #if OBJC_API_VERSION >= 2
1654 objc_method **data(class_copyMethodList(_class, &size));
1655 for (size_t i(0); i != size; ++i)
1656 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1659 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1660 for (int i(0); i != methods->method_count; ++i)
1661 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1665 static bool CYHasImplicitProperties(Class _class) {
1666 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1667 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1669 return [_class cy$hasImplicitProperties];
1672 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1673 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1674 id self(internal->GetValue());
1676 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1680 NSString *name(CYCastNSString(&pool, context, property));
1682 if (CYInternal *internal = [CYInternal get:self])
1683 if ([internal hasProperty:property inContext:context])
1686 Class _class(object_getClass(self));
1689 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1690 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1691 if ([self cy$hasProperty:name])
1693 } CYPoolCatch(false)
1695 const char *string(CYPoolCString(pool, context, name));
1698 if (class_getProperty(_class, string) != NULL)
1702 if (CYHasImplicitProperties(_class))
1703 if (SEL sel = sel_getUid(string))
1704 if (CYImplements(self, _class, sel, true))
1710 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1711 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1712 id self(internal->GetValue());
1714 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1715 return Internal::Make(context, self, object);
1718 NSString *name(CYCastNSString(&pool, context, property));
1720 if (CYInternal *internal = [CYInternal get:self])
1721 if (JSValueRef value = [internal getProperty:property inContext:context])
1725 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1729 const char *string(CYPoolCString(pool, context, name));
1730 Class _class(object_getClass(self));
1733 if (objc_property_t property = class_getProperty(_class, string)) {
1734 PropertyAttributes attributes(property);
1735 SEL sel(sel_registerName(attributes.Getter()));
1736 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1740 if (CYHasImplicitProperties(_class))
1741 if (SEL sel = sel_getUid(string))
1742 if (CYImplements(self, _class, sel, true))
1743 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1748 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1749 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1750 id self(internal->GetValue());
1754 NSString *name(CYCastNSString(&pool, context, property));
1755 NSObject *data(CYCastNSObject(&pool, context, value));
1758 if ([self cy$setProperty:name to:data])
1760 } CYPoolCatch(false)
1762 const char *string(CYPoolCString(pool, context, name));
1763 Class _class(object_getClass(self));
1766 if (objc_property_t property = class_getProperty(_class, string)) {
1767 PropertyAttributes attributes(property);
1768 if (const char *setter = attributes.Setter()) {
1769 SEL sel(sel_registerName(setter));
1770 JSValueRef arguments[1] = {value};
1771 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1777 size_t length(strlen(string));
1779 char set[length + 5];
1785 if (string[0] != '\0') {
1786 set[3] = toupper(string[0]);
1787 memcpy(set + 4, string + 1, length - 1);
1790 set[length + 3] = ':';
1791 set[length + 4] = '\0';
1793 if (SEL sel = sel_getUid(set))
1794 if (CYImplements(self, _class, sel)) {
1795 JSValueRef arguments[1] = {value};
1796 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1800 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1801 [internal setProperty:property toValue:value inContext:context];
1808 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1809 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1810 id self(internal->GetValue());
1813 NSString *name(CYCastNSString(NULL, context, property));
1814 return [self cy$deleteProperty:name];
1815 } CYPoolCatch(false)
1816 } CYCatch(false) return /*XXX*/ false; }
1818 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1819 const char *name(sel_getName(method_getName(method)));
1820 if (strchr(name, ':') != NULL)
1823 const char *type(method_getTypeEncoding(method));
1824 if (type == NULL || *type == '\0' || *type == 'v')
1827 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1830 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1831 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1832 id self(internal->GetValue());
1835 Class _class(object_getClass(self));
1840 objc_property_t *data(class_copyPropertyList(_class, &size));
1841 for (size_t i(0); i != size; ++i)
1842 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1847 if (CYHasImplicitProperties(_class))
1848 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1849 #if OBJC_API_VERSION >= 2
1851 objc_method **data(class_copyMethodList(current, &size));
1852 for (size_t i(0); i != size; ++i)
1853 Instance_getPropertyNames_message(names, data[i]);
1856 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1857 for (int i(0); i != methods->method_count; ++i)
1858 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1863 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1864 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1865 [self cy$getPropertyNames:names inContext:context];
1869 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1870 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1871 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1875 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1876 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1877 id self(internal->GetValue());
1879 if (![self isKindOfClass:NSBlock_])
1880 CYThrow("non-NSBlock object is not a function");
1881 // XXX: replace above logic with the following assertion
1882 //_assert([self isKindOfClass:NSBlock_]);
1883 // to do this, make it so FunctionInstance_ is the class of blocks
1884 // to do /that/, generalize the various "is exactly Instance_" checks
1885 // then, move Instance_callAsFunction to only be on FunctionInstance
1887 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1889 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1890 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1891 descriptor += sizeof(BlockDescriptor1);
1892 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1893 descriptor += sizeof(BlockDescriptor2);
1894 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1896 if (const char *type = descriptor3->signature) {
1902 sig::Signature signature;
1903 sig::Parse(pool, &signature, type, &Structor_);
1906 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1908 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1909 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1914 CYThrow("NSBlock without signature field passed arguments");
1918 } CYPoolCatch(NULL);
1923 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1924 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1925 Class _class(internal->GetValue());
1926 if (!CYIsClass(_class))
1929 if (CYJSValueIsNSObject(context, instance)) {
1930 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1931 // XXX: this isn't always safe
1932 return [linternal->GetValue() isKindOfClass:_class];
1938 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1940 throw CYJSError(context, "incorrect number of arguments to Instance");
1942 id value(CYCastNSObject(&pool, context, arguments[0]));
1944 value = [NSNull null];
1945 return CYCastJSValue(context, [value cy$box]);
1948 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1949 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1952 id self(internal->GetValue());
1953 const char *name(CYPoolCString(pool, context, property));
1955 if (object_getInstanceVariable(self, name, NULL) != NULL)
1961 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
1962 length = CYCastDouble(encoding + 1);
1966 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
1967 for (size_t i(0); i != size; ++i)
1968 if (ivars[i] == ivar)
1970 else if (ivar_getOffset(ivars[i]) == offset) {
1971 const char *encoding(ivar_getTypeEncoding(ivars[i]));
1972 _assert(encoding[0] == 'b');
1973 shift += CYCastDouble(encoding + 1);
1978 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1979 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1982 id self(internal->GetValue());
1983 const char *name(CYPoolCString(pool, context, property));
1986 if (strcmp(name, "isa") == 0)
1987 return CYCastJSValue(context, object_getClass(self));
1990 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1991 ptrdiff_t offset(ivar_getOffset(ivar));
1992 void *data(reinterpret_cast<uint8_t *>(self) + offset);
1994 const char *encoding(ivar_getTypeEncoding(ivar));
1995 if (encoding[0] == 'b') {
1996 unsigned length, shift;
1997 CYBitField(length, shift, self, ivar, encoding, offset);
1998 _assert(shift + length <= sizeof(uintptr_t) * 8);
1999 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2000 uintptr_t mask((1 << length) - 1);
2001 return CYCastJSValue(context, (field >> shift) & mask);
2003 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2004 return CYFromFFI(context, type.type_, type.GetFFI(), data);
2011 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2012 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2015 id self(internal->GetValue());
2016 const char *name(CYPoolCString(pool, context, property));
2018 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2019 ptrdiff_t offset(ivar_getOffset(ivar));
2020 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2022 const char *encoding(ivar_getTypeEncoding(ivar));
2023 if (encoding[0] == 'b') {
2024 unsigned length, shift;
2025 CYBitField(length, shift, self, ivar, encoding, offset);
2026 _assert(shift + length <= sizeof(uintptr_t) * 8);
2027 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2028 uintptr_t mask((1 << length) - 1);
2029 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2031 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2032 CYPoolFFI(&pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2040 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2041 if (Class super = class_getSuperclass(_class))
2042 Internal_getPropertyNames_(super, names);
2044 #if OBJC_API_VERSION >= 2
2046 objc_ivar **data(class_copyIvarList(_class, &size));
2047 for (size_t i(0); i != size; ++i)
2048 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2051 if (objc_ivar_list *ivars = _class->ivars)
2052 for (int i(0); i != ivars->ivar_count; ++i)
2053 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2057 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2058 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2061 id self(internal->GetValue());
2062 Class _class(object_getClass(self));
2064 Internal_getPropertyNames_(_class, names);
2067 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2068 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2069 return internal->GetOwner();
2072 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2074 NSString *name(CYCastNSString(&pool, context, property));
2075 if (Class _class = NSClassFromString(name))
2076 return CYMakeInstance(context, _class, true);
2081 static Class *CYCopyClassList(size_t &size) {
2082 size = objc_getClassList(NULL, 0);
2083 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2086 size_t writ(objc_getClassList(data, size));
2092 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2104 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2107 if (Class *data = CYCopyClassList(size)) {
2108 for (size_t i(0); i != size; ++i)
2109 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2114 while (Class _class = objc_next_class(&state))
2115 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2119 #if OBJC_API_VERSION >= 2
2120 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2121 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2124 const char *name(CYPoolCString(pool, context, property));
2126 const char **data(objc_copyClassNamesForImage(internal, &size));
2128 for (size_t i(0); i != size; ++i)
2129 if (strcmp(name, data[i]) == 0) {
2130 if (Class _class = objc_getClass(name)) {
2131 value = CYMakeInstance(context, _class, true);
2142 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2143 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2145 const char **data(objc_copyClassNamesForImage(internal, &size));
2146 for (size_t i(0); i != size; ++i)
2147 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2151 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2153 const char *name(CYPoolCString(pool, context, property));
2155 const char **data(objc_copyImageNames(&size));
2156 for (size_t i(0); i != size; ++i)
2157 if (strcmp(name, data[i]) == 0) {
2166 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2167 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2171 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2173 const char **data(objc_copyImageNames(&size));
2174 for (size_t i(0); i != size; ++i)
2175 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2180 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2182 const char *name(CYPoolCString(pool, context, property));
2183 if (Protocol *protocol = objc_getProtocol(name))
2184 return CYMakeInstance(context, protocol, true);
2188 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2189 #if OBJC_API_VERSION >= 2
2191 Protocol **data(objc_copyProtocolList(&size));
2192 for (size_t i(0); i != size; ++i)
2193 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2200 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2202 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2204 return Instance::Make(context, nil);
2208 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2209 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2213 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2214 *data = reinterpret_cast<void *>(address);
2215 return KERN_SUCCESS;
2219 std::set<Class> query_;
2220 JSContextRef context_;
2221 JSObjectRef results_;
2224 struct CYObjectStruct {
2228 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2229 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2230 JSContextRef context(choice->context_);
2232 for (unsigned i(0); i != count; ++i) {
2233 vm_range_t &range(ranges[i]);
2234 void *data(reinterpret_cast<void *>(range.address));
2235 size_t size(range.size);
2237 if (size < sizeof(CYObjectStruct))
2240 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2242 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2244 Class isa(reinterpret_cast<Class>(pointers[0]));
2247 std::set<Class>::const_iterator result(choice->query_.find(isa));
2248 if (result == choice->query_.end())
2251 // XXX: if (size < class_getInstanceSize(*result))
2252 if ((class_getInstanceSize(*result) + 15) / 16 * 16 != size)
2254 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2258 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2260 throw CYJSError(context, "choose() takes a class argument");
2263 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2265 vm_address_t *zones(NULL);
2267 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2268 _assert(error == KERN_SUCCESS);
2270 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2271 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2274 choice.context_ = context;
2275 choice.results_ = results;
2278 Class *classes(CYCopyClassList(number));
2279 _assert(classes != NULL);
2281 for (size_t i(0); i != number; ++i)
2282 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2283 if (current == _class) {
2284 choice.query_.insert(classes[i]);
2290 for (unsigned i(0); i != size; ++i) {
2291 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2292 if (zone == NULL || zone->introspect == NULL)
2295 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2303 #if defined(__i386__) || defined(__x86_64__)
2304 #define OBJC_MAX_STRUCT_BY_VALUE 8
2305 static int struct_forward_array[] = {
2306 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2307 #elif defined(__arm__)
2308 #define OBJC_MAX_STRUCT_BY_VALUE 1
2309 static int struct_forward_array[] = {
2311 #elif defined(__arm64__)
2314 #error missing objc-runtime-info
2318 static bool stret(ffi_type *ffi_type) {
2319 return ffi_type->type == FFI_TYPE_STRUCT && (
2320 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2321 struct_forward_array[ffi_type->size] != 0
2327 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2331 _class = object_getClass(self);
2335 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2336 imp = method_getImplementation(method);
2337 type = method_getTypeEncoding(method);
2342 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2344 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2345 type = CYPoolCString(pool, context, [method _typeString]);
2353 sig::Signature signature;
2354 sig::Parse(pool, &signature, type, &Structor_);
2356 size_t used(count + 3);
2357 if (used > signature.count) {
2358 sig::Element *elements(new (pool) sig::Element[used]);
2359 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2361 for (size_t index(signature.count); index != used; ++index) {
2362 sig::Element *element(&elements[index]);
2363 element->name = NULL;
2364 element->offset = _not(size_t);
2366 sig::Type *type(new (pool) sig::Type);
2367 memset(type, 0, sizeof(*type));
2368 type->primitive = sig::object_P;
2369 element->type = type;
2372 signature.elements = elements;
2373 signature.count = used;
2377 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2382 if (stret(cif.rtype))
2383 imp = class_getMethodImplementation_stret(_class, _cmd);
2386 imp = class_getMethodImplementation(_class, _cmd);
2388 objc_super super = {self, _class};
2389 imp = objc_msg_lookup_super(&super, _cmd);
2393 void (*function)() = reinterpret_cast<void (*)()>(imp);
2394 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2397 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2399 throw CYJSError(context, "too few arguments to objc_msgSend");
2409 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2410 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2411 self = internal->GetValue();
2412 _class = internal->class_;;
2413 uninitialized = false;
2414 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2415 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2416 self = internal->GetValue();
2418 uninitialized = internal->IsUninitialized();
2420 internal->value_ = nil;
2422 self = CYCastNSObject(&pool, context, arguments[0]);
2424 uninitialized = false;
2428 return CYJSNull(context);
2430 _cmd = CYCastSEL(context, arguments[1]);
2432 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2435 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2436 return $objc_msgSend(context, object, _this, count, arguments);
2439 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2440 JSValueRef setup[count + 2];
2443 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2444 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2447 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2449 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2451 // XXX: handle Instance::Uninitialized?
2452 id self(CYCastNSObject(&pool, context, _this));
2456 setup[1] = &internal->sel_;
2458 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2461 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2463 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2465 id self(CYCastNSObject(&pool, context, arguments[0]));
2466 Class _class(CYCastClass(pool, context, arguments[1]));
2467 return cy::Super::Make(context, self, _class);
2470 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2472 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2474 const char *name(CYPoolCString(pool, context, arguments[0]));
2475 return CYMakeSelector(context, sel_registerName(name));
2478 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2480 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2481 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2482 return CYMakeInstance(context, self, false);
2485 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2486 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2487 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2490 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2491 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2492 Type_privateData *typical(internal->GetType());
2497 if (typical == NULL) {
2501 type = typical->type_;
2502 ffi = typical->ffi_;
2505 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2508 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2509 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2510 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2513 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2514 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2515 id self(internal->GetValue());
2516 if (!CYIsClass(self))
2517 return CYJSUndefined(context);
2518 return CYGetClassPrototype(context, self);
2521 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2522 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2523 id self(internal->GetValue());
2524 if (!CYIsClass(self))
2525 return CYJSUndefined(context);
2526 return Messages::Make(context, (Class) self);
2529 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2530 if (!CYJSValueIsNSObject(context, _this))
2533 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2534 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2537 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2538 if (!CYJSValueIsNSObject(context, _this))
2541 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2542 id value(internal->GetValue());
2549 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2551 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2552 return CYJSUndefined(context);
2553 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2556 return CYCastJSValue(context, CYJSString(context, [value description]));
2558 } CYCatch(NULL) return /*XXX*/ NULL; }
2560 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2561 if (!CYJSValueIsNSObject(context, _this))
2564 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2565 id value(internal->GetValue());
2567 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2570 if (JSValueRef result = [value cy$valueOfInContext:context])
2574 } CYCatch(NULL) return /*XXX*/ NULL; }
2576 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2577 if (!CYJSValueIsNSObject(context, _this))
2580 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2581 // XXX: but... but... THIS ISN'T A POINTER! :(
2582 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2583 } CYCatch(NULL) return /*XXX*/ NULL; }
2585 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2586 if (!CYJSValueIsNSObject(context, _this))
2589 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2590 id value(internal->GetValue());
2593 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2594 return CYCastJSValue(context, CYJSString(context, [value description]));
2596 } CYCatch(NULL) return /*XXX*/ NULL; }
2598 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2599 if (!CYJSValueIsNSObject(context, _this))
2602 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2603 id value(internal->GetValue());
2605 if (!CYIsClass(value))
2606 CYThrow("non-Class object cannot be used as Type");
2608 // XXX: this is a very silly implementation
2610 std::ostringstream type;
2612 type << class_getName(value);
2616 return CYMakeType(context, type.str().c_str());
2618 } CYCatch(NULL) return /*XXX*/ NULL; }
2620 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2621 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2622 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2625 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2626 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2629 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2630 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2631 const char *name(sel_getName(internal->GetValue()));
2634 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2635 return CYCastJSValue(context, CYJSString(context, string));
2637 } CYCatch(NULL) return /*XXX*/ NULL; }
2639 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2641 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2644 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2645 SEL sel(internal->GetValue());
2647 objc_method *method;
2648 if (Class _class = CYCastClass(pool, context, arguments[0]))
2649 method = class_getInstanceMethod(_class, sel);
2653 const char *encoding(CYPoolTypeEncoding(pool, context, sel, method));
2654 if (encoding == NULL)
2655 return CYJSNull(context);
2657 sig::Signature signature;
2658 sig::Parse(pool, &signature, encoding, &Structor_);
2659 return CYMakeType(context, &signature);
2662 static JSStaticValue Selector_staticValues[2] = {
2663 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2664 {NULL, NULL, NULL, 0}
2667 static JSStaticValue Instance_staticValues[5] = {
2668 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2669 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2670 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2671 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2672 {NULL, NULL, NULL, 0}
2675 static JSStaticFunction Instance_staticFunctions[7] = {
2676 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2677 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2678 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2679 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2680 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2681 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2685 static JSStaticFunction Class_staticFunctions[2] = {
2686 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2690 static JSStaticFunction Internal_staticFunctions[2] = {
2691 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2695 static JSStaticFunction Selector_staticFunctions[5] = {
2696 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2697 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2698 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2699 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2704 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2705 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2706 } CYObjectiveCatch }
2709 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2710 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2711 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2712 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2714 CYPool &pool(CYGetGlobalPool());
2716 Object_type = new(pool) Type_privateData("@");
2717 Selector_type = new(pool) Type_privateData(":");
2719 NSArray_ = objc_getClass("NSArray");
2720 NSBlock_ = objc_getClass("NSBlock");
2721 NSDictionary_ = objc_getClass("NSDictionary");
2722 NSString_ = objc_getClass("NSString");
2723 Object_ = objc_getClass("Object");
2726 // XXX: apparently, iOS now has both of these
2727 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2728 if (NSCFBoolean_ == nil)
2729 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2731 NSCFType_ = objc_getClass("NSCFType");
2733 NSZombie_ = objc_getClass("_NSZombie_");
2735 banned_.insert(Object_);
2736 banned_.insert(objc_getClass("__NSAtom"));
2737 banned_.insert(objc_getClass("__NSGenericDeallocHandler"));
2738 banned_.insert(objc_getClass("NSMessageBuilder"));
2739 banned_.insert(objc_getClass("__NSMessageBuilder"));
2741 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2744 JSClassDefinition definition;
2746 definition = kJSClassDefinitionEmpty;
2747 definition.className = "Instance";
2748 definition.staticValues = Instance_staticValues;
2749 definition.staticFunctions = Instance_staticFunctions;
2750 definition.hasProperty = &Instance_hasProperty;
2751 definition.getProperty = &Instance_getProperty;
2752 definition.setProperty = &Instance_setProperty;
2753 definition.deleteProperty = &Instance_deleteProperty;
2754 definition.getPropertyNames = &Instance_getPropertyNames;
2755 definition.callAsConstructor = &Instance_callAsConstructor;
2756 definition.callAsFunction = &Instance_callAsFunction;
2757 definition.hasInstance = &Instance_hasInstance;
2758 definition.finalize = &CYFinalize;
2759 Instance_ = JSClassCreate(&definition);
2761 definition.className = "ArrayInstance";
2762 ArrayInstance_ = JSClassCreate(&definition);
2764 definition.className = "FunctionInstance";
2765 FunctionInstance_ = JSClassCreate(&definition);
2767 definition.className = "ObjectInstance";
2768 ObjectInstance_ = JSClassCreate(&definition);
2770 definition.className = "StringInstance";
2771 StringInstance_ = JSClassCreate(&definition);
2773 definition = kJSClassDefinitionEmpty;
2774 definition.className = "Class";
2775 definition.staticFunctions = Class_staticFunctions;
2776 Class_ = JSClassCreate(&definition);
2778 definition = kJSClassDefinitionEmpty;
2779 definition.className = "Internal";
2780 definition.staticFunctions = Internal_staticFunctions;
2781 definition.hasProperty = &Internal_hasProperty;
2782 definition.getProperty = &Internal_getProperty;
2783 definition.setProperty = &Internal_setProperty;
2784 definition.getPropertyNames = &Internal_getPropertyNames;
2785 definition.finalize = &CYFinalize;
2786 Internal_ = JSClassCreate(&definition);
2788 definition = kJSClassDefinitionEmpty;
2789 definition.className = "Message";
2790 definition.staticFunctions = cy::Functor::StaticFunctions;
2791 definition.callAsFunction = &Message_callAsFunction;
2792 definition.finalize = &CYFinalize;
2793 Message_ = JSClassCreate(&definition);
2795 definition = kJSClassDefinitionEmpty;
2796 definition.className = "Messages";
2797 definition.hasProperty = &Messages_hasProperty;
2798 definition.getProperty = &Messages_getProperty;
2799 definition.setProperty = &Messages_setProperty;
2800 #if 0 && OBJC_API_VERSION < 2
2801 definition.deleteProperty = &Messages_deleteProperty;
2803 definition.getPropertyNames = &Messages_getPropertyNames;
2804 definition.finalize = &CYFinalize;
2805 Messages_ = JSClassCreate(&definition);
2807 definition = kJSClassDefinitionEmpty;
2808 definition.className = "Selector";
2809 definition.staticValues = Selector_staticValues;
2810 definition.staticFunctions = Selector_staticFunctions;
2811 definition.callAsFunction = &Selector_callAsFunction;
2812 definition.finalize = &CYFinalize;
2813 Selector_ = JSClassCreate(&definition);
2815 definition = kJSClassDefinitionEmpty;
2816 definition.className = "Super";
2817 definition.staticFunctions = Internal_staticFunctions;
2818 definition.finalize = &CYFinalize;
2819 Super_ = JSClassCreate(&definition);
2821 definition = kJSClassDefinitionEmpty;
2822 definition.className = "ObjectiveC::Classes";
2823 definition.getProperty = &ObjectiveC_Classes_getProperty;
2824 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2825 ObjectiveC_Classes_ = JSClassCreate(&definition);
2827 definition = kJSClassDefinitionEmpty;
2828 definition.className = "ObjectiveC::Constants";
2829 definition.getProperty = &ObjectiveC_Constants_getProperty;
2830 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2831 ObjectiveC_Constants_ = JSClassCreate(&definition);
2833 #if OBJC_API_VERSION >= 2
2834 definition = kJSClassDefinitionEmpty;
2835 definition.className = "ObjectiveC::Images";
2836 definition.getProperty = &ObjectiveC_Images_getProperty;
2837 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2838 ObjectiveC_Images_ = JSClassCreate(&definition);
2840 definition = kJSClassDefinitionEmpty;
2841 definition.className = "ObjectiveC::Image::Classes";
2842 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2843 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2844 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2847 definition = kJSClassDefinitionEmpty;
2848 definition.className = "ObjectiveC::Protocols";
2849 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2850 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2851 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2854 // XXX: this is horrible; there has to be a better way to do this
2856 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24");
2858 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2863 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2864 JSObjectRef global(CYGetGlobalObject(context));
2865 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2866 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2867 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2868 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2870 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2871 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2873 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2874 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2875 CYArrayPush(context, alls, protocols);
2877 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2878 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2879 CYArrayPush(context, alls, classes);
2881 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2882 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2883 CYArrayPush(context, alls, constants);
2885 #if OBJC_API_VERSION >= 2
2886 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2889 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2890 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2891 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2892 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2893 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2895 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2896 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2898 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2899 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2900 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2901 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2902 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2904 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2905 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2906 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2907 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2908 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2910 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2911 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2912 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2913 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2914 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2916 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2917 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2918 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2919 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2920 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2922 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2923 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2924 JSObjectSetPrototype(context, Class_prototype, Instance_prototype);
2926 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2927 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2928 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2930 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2931 CYSetProperty(context, Instance, CYJSString("box"), box);
2934 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2937 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2939 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2940 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2943 static CYHooks CYObjectiveCHooks = {
2944 &CYObjectiveC_ExecuteStart,
2945 &CYObjectiveC_ExecuteEnd,
2946 &CYObjectiveC_CallFunction,
2947 &CYObjectiveC_Initialize,
2948 &CYObjectiveC_SetupContext,
2949 &CYObjectiveC_PoolFFI,
2950 &CYObjectiveC_FromFFI,
2953 struct CYObjectiveC {
2955 hooks_ = &CYObjectiveCHooks;
2956 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2957 _assert(hooks_ != NULL);