1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2013 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
22 #include <Foundation/Foundation.h>
24 #include "ObjectiveC/Internal.hpp"
26 #include <objc/objc-api.h>
28 #include "cycript.hpp"
30 #include "ObjectiveC/Internal.hpp"
33 #include <CoreFoundation/CoreFoundation.h>
34 #include <JavaScriptCore/JSStringRefCF.h>
35 #include <objc/runtime.h>
39 #include <malloc/malloc.h>
40 #include <mach/mach.h>
45 #include "JavaScript.hpp"
47 #include "Execute.hpp"
55 #define CYObjectiveTry_ { \
57 #define CYObjectiveTry { \
58 JSContextRef context(context_); \
60 #define CYObjectiveCatch \
61 catch (const CYException &error) { \
62 @throw CYCastNSObject(NULL, context, error.CastJSValue(context)); \
68 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
70 #define CYPoolCatch(value) \
71 @catch (NSException *error) { \
72 _saved = [error retain]; \
73 throw CYJSError(context, CYCastJSValue(context, error)); \
78 [_saved autorelease]; \
84 #define CYSadCatch(value) \
85 @catch (NSException *error ) { \
86 throw CYJSError(context, CYCastJSValue(context, error)); \
90 #define _oassert(test) \
92 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"_assert(" #test ")" userInfo:nil];
95 #define class_getSuperclass GSObjCSuper
96 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
97 #define class_getName GSNameFromClass
99 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
101 #define ivar_getName(ivar) ((ivar)->ivar_name)
102 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
103 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
105 #define method_getName(method) ((method)->method_name)
106 #define method_getImplementation(method) ((method)->method_imp)
107 #define method_getTypeEncoding(method) ((method)->method_types)
108 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
111 #define objc_getClass GSClassFromName
113 #define objc_getProtocol GSProtocolFromName
115 #define object_getClass GSObjCClass
117 #define object_getInstanceVariable(object, name, value) ({ \
118 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
119 _assert(value != NULL); \
121 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
125 #define object_setIvar(object, ivar, value) ({ \
126 void *data = (value); \
127 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
130 #define protocol_getName(protocol) [(protocol) name]
133 static void (*$objc_setAssociatedObject)(id object, void *key, id value, objc_AssociationPolicy policy);
134 static id (*$objc_getAssociatedObject)(id object, void *key);
135 static void (*$objc_removeAssociatedObjects)(id object);
139 struct BlockLiteral {
143 void (*invoke)(void *, ...);
147 struct BlockDescriptor1 {
148 unsigned long int reserved;
149 unsigned long int size;
152 struct BlockDescriptor2 {
153 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
154 void (*dispose_helper)(BlockLiteral *src);
157 struct BlockDescriptor3 {
158 const char *signature;
163 BLOCK_DEALLOCATING = 0x0001,
164 BLOCK_REFCOUNT_MASK = 0xfffe,
165 BLOCK_NEEDS_FREE = 1 << 24,
166 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
167 BLOCK_HAS_CTOR = 1 << 26,
168 BLOCK_IS_GC = 1 << 27,
169 BLOCK_IS_GLOBAL = 1 << 28,
170 BLOCK_HAS_STRET = 1 << 29,
171 BLOCK_HAS_SIGNATURE = 1 << 30,
174 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
176 /* Objective-C Pool Release {{{ */
177 void CYPoolRelease_(void *data) {
178 id object(reinterpret_cast<id>(data));
182 id CYPoolRelease_(CYPool *pool, id object) {
185 else if (pool == NULL)
186 return [object autorelease];
188 pool->atexit(CYPoolRelease_);
193 template <typename Type_>
194 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
195 return (Type_) CYPoolRelease_(pool, (id) object);
198 /* Objective-C Strings {{{ */
199 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
200 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
201 char *string(new(pool) char[size]);
202 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
203 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
207 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
209 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
212 return CYCopyJSString(CYPoolCString(pool, context, value));
216 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
219 // XXX: this definition scares me; is anyone using this?!
220 NSString *string([value description]);
221 return CYCopyJSString(context, string);
224 NSString *CYCopyNSString(const CYUTF8String &value) {
226 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
228 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
232 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
234 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
237 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
241 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
242 return CYCopyNSString(context, CYJSString(context, value));
245 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
246 return CYPoolRelease(pool, CYCopyNSString(value));
249 NSString *CYCastNSString(CYPool *pool, SEL sel) {
250 const char *name(sel_getName(sel));
251 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
254 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
255 return CYPoolRelease(pool, CYCopyNSString(context, value));
258 CYUTF8String CYCastUTF8String(NSString *value) {
259 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
260 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
264 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
266 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
267 if (exception == NULL)
269 *exception = CYCastJSValue(context, error);
272 size_t CYGetIndex(NSString *value) {
273 return CYGetIndex(CYCastUTF8String(value));
276 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
277 return CYGetOffset(CYPoolCString(pool, context, value), index);
280 static JSClassRef Instance_;
282 static JSClassRef ArrayInstance_;
283 static JSClassRef BooleanInstance_;
284 static JSClassRef FunctionInstance_;
285 static JSClassRef NumberInstance_;
286 static JSClassRef ObjectInstance_;
287 static JSClassRef StringInstance_;
289 static JSClassRef Class_;
290 static JSClassRef Internal_;
291 static JSClassRef Message_;
292 static JSClassRef Messages_;
293 static JSClassRef Selector_;
294 static JSClassRef Super_;
296 static JSClassRef ObjectiveC_Classes_;
297 static JSClassRef ObjectiveC_Constants_;
298 static JSClassRef ObjectiveC_Protocols_;
301 static JSClassRef ObjectiveC_Image_Classes_;
302 static JSClassRef ObjectiveC_Images_;
306 static Class __NSMallocBlock__;
307 static Class NSCFBoolean_;
308 static Class NSCFType_;
309 static Class NSGenericDeallocHandler_;
310 static Class NSZombie_;
312 static Class NSBoolNumber_;
315 static Class NSArray_;
316 static Class NSBlock_;
317 static Class NSDictionary_;
318 static Class NSNumber_;
319 static Class NSString_;
320 static Class Object_;
322 static Type_privateData *Object_type;
323 static Type_privateData *Selector_type;
325 Type_privateData *Instance::GetType() const {
329 Type_privateData *Selector_privateData::GetType() const {
330 return Selector_type;
333 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
335 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
337 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
338 else if (meta && !class_isMetaClass(self))
339 return CYGetCachedObject(context, CYJSString("Class_prototype"));
341 JSObjectRef global(CYGetGlobalObject(context));
342 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
345 sprintf(label, "i%p", self);
346 CYJSString name(label);
348 JSValueRef value(CYGetProperty(context, cy, name));
349 if (!JSValueIsUndefined(context, value))
352 JSClassRef _class(NULL);
353 JSValueRef prototype;
356 if (self == NSCFBoolean_)
358 if (self == NSBoolNumber_)
360 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
361 else if (self == NSArray_)
362 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
363 else if (self == NSBlock_)
364 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
365 else if (self == NSNumber_)
366 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
367 else if (self == NSDictionary_)
368 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
369 else if (self == NSString_)
370 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
372 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
374 JSObjectRef object(JSObjectMake(context, _class, NULL));
375 CYSetPrototype(context, object, prototype);
376 CYSetProperty(context, cy, name, object);
381 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
382 return CYGetClassPrototype(context, self, class_isMetaClass(self));
385 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
386 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
387 if (Class super = class_getSuperclass(_class))
388 CYSetPrototype(context, value, Messages::Make(context, super));
392 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
393 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
397 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
398 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
402 bool CYIsKindOfClass(id object, Class _class) {
403 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
409 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
410 JSObjectRef value(JSObjectMake(context, CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance_, new Instance(object, flags)));
411 CYSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
415 Instance::~Instance() {
416 if ((flags_ & Transient) == 0)
417 [GetValue() release];
420 struct Message_privateData :
425 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
426 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
432 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
433 Instance::Flags flags;
436 flags = Instance::Transient;
438 flags = Instance::None;
439 object = [object retain];
442 return Instance::Make(context, object, flags);
445 @interface NSMethodSignature (Cycript)
446 - (NSString *) _typeString;
449 @interface NSObject (Cycript)
451 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
452 - (JSType) cy$JSType;
454 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
455 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
457 - (bool) cy$hasProperty:(NSString *)name;
458 - (NSObject *) cy$getProperty:(NSString *)name;
459 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
460 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
461 - (bool) cy$deleteProperty:(NSString *)name;
462 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
464 + (bool) cy$hasImplicitProperties;
470 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
473 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
479 Class _class(object_getClass(value));
480 SEL sel(@selector(cy$toCYON:inSet:));
482 if (class_isMetaClass(_class)) {
483 const char *name(class_getName(value));
484 if (class_isMetaClass(value))
485 string = [NSString stringWithFormat:@"object_getClass(%s)", name];
487 string = [NSString stringWithUTF8String:name];
488 } else if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
489 string = reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
490 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
491 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
492 string = [value cy$toCYON:objective inSet:objects];
497 else if (_class == NSZombie_)
498 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
501 string = [NSString stringWithFormat:@"%@", value];
506 string = @"undefined";
512 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
514 return CYCastNSCYON(value, objective, *objects);
516 std::set<void *> objects;
517 return CYCastNSCYON(value, objective, objects);
522 struct PropertyAttributes {
527 const char *variable;
540 PropertyAttributes(objc_property_t property) :
552 name = property_getName(property);
553 const char *attributes(property_getAttributes(property));
555 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
556 if ((next = strchr(token, ',')) != NULL)
559 case 'R': readonly = true; break;
560 case 'C': copy = true; break;
561 case '&': retain = true; break;
562 case 'N': nonatomic = true; break;
563 case 'G': getter_ = token + 1; break;
564 case 'S': setter_ = token + 1; break;
565 case 'V': variable = token + 1; break;
569 /*if (variable == NULL) {
570 variable = property_getName(property);
571 size_t size(strlen(variable));
572 char *name(new(pool_) char[size + 2]);
574 memcpy(name + 1, variable, size);
575 name[size + 1] = '\0';
580 const char *Getter() {
582 getter_ = pool_.strdup(name);
586 const char *Setter() {
587 if (setter_ == NULL && !readonly) {
588 size_t length(strlen(name));
590 char *temp(new(pool_) char[length + 5]);
596 temp[3] = toupper(name[0]);
597 memcpy(temp + 4, name + 1, length - 1);
600 temp[length + 3] = ':';
601 temp[length + 4] = '\0';
611 @interface CYWebUndefined : NSObject {
614 + (CYWebUndefined *) undefined;
618 @implementation CYWebUndefined
620 + (CYWebUndefined *) undefined {
621 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
627 #define WebUndefined CYWebUndefined
629 /* Bridge: CYJSObject {{{ */
630 @interface CYJSObject : NSMutableDictionary {
632 JSGlobalContextRef context_;
635 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
637 - (NSUInteger) count;
638 - (id) objectForKey:(id)key;
639 - (NSEnumerator *) keyEnumerator;
640 - (void) setObject:(id)object forKey:(id)key;
641 - (void) removeObjectForKey:(id)key;
645 /* Bridge: CYJSArray {{{ */
646 @interface CYJSArray : NSMutableArray {
648 JSGlobalContextRef context_;
651 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
653 - (NSUInteger) count;
654 - (id) objectAtIndex:(NSUInteger)index;
656 - (void) addObject:(id)anObject;
657 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
658 - (void) removeLastObject;
659 - (void) removeObjectAtIndex:(NSUInteger)index;
660 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
665 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
666 return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
669 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
670 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
673 struct CYBlockDescriptor {
675 BlockDescriptor1 one_;
676 BlockDescriptor2 two_;
677 BlockDescriptor3 three_;
680 Closure_privateData *internal_;
683 void CYDisposeBlock(BlockLiteral *literal) {
684 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
687 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
688 JSObjectRef _this(CYCastJSObject(context, values[0]));
689 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
692 static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
693 CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
696 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
697 _assert(__NSMallocBlock__ != Nil);
698 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
700 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
701 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
703 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
704 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
706 literal->isa = __NSMallocBlock__;
707 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
708 literal->reserved = 0;
709 literal->descriptor = descriptor;
711 descriptor->d_.one_.size = sizeof(descriptor->d_);
712 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
713 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
715 return reinterpret_cast<NSBlock *>(literal);
718 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
719 if (CYJSValueIsNSObject(context, object)) {
720 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
721 return internal->GetValue();
724 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
725 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
726 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
729 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
730 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
734 @interface NSBoolNumber : NSNumber {
739 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
743 switch (JSType type = JSValueGetType(context, value)) {
744 case kJSTypeUndefined:
745 object = [WebUndefined undefined];
755 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
758 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
764 object = CYCopyNSNumber(context, value);
769 object = CYCopyNSString(context, value);
774 // XXX: this might could be more efficient
775 object = CYCastNSObject(pool, context, (JSObjectRef) value);
780 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
787 return CYPoolRelease(pool, object);
789 return [object retain];
792 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
793 return CYNSObject(pool, context, value, true);
796 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
797 return CYNSObject(&pool, context, value, false);
800 /* Bridge: NSArray {{{ */
801 @implementation NSArray (Cycript)
804 return [[self mutableCopy] autorelease];
807 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
808 _oassert(objects.insert(self).second);
810 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
811 [json appendString:@"@["];
815 for (id object in self) {
817 for (size_t index(0), count([self count]); index != count; ++index) {
818 id object([self objectAtIndex:index]);
821 [json appendString:@","];
824 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
825 [json appendString:CYCastNSCYON(object, true, objects)];
827 [json appendString:@","];
832 [json appendString:@"]"];
836 - (bool) cy$hasProperty:(NSString *)name {
837 if ([name isEqualToString:@"length"])
840 size_t index(CYGetIndex(name));
841 if (index == _not(size_t) || index >= [self count])
842 return [super cy$hasProperty:name];
847 - (NSObject *) cy$getProperty:(NSString *)name {
848 size_t index(CYGetIndex(name));
849 if (index == _not(size_t) || index >= [self count])
850 return [super cy$getProperty:name];
852 return [self objectAtIndex:index];
855 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
857 if ([name isEqualToString:@"length"])
858 return CYCastJSValue(context, [self count]);
861 return [super cy$getProperty:name inContext:context];
864 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
865 [super cy$getPropertyNames:names inContext:context];
867 for (size_t index(0), count([self count]); index != count; ++index) {
868 id object([self objectAtIndex:index]);
869 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
871 sprintf(name, "%zu", index);
872 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
877 + (bool) cy$hasImplicitProperties {
883 /* Bridge: NSBlock {{{ */
890 /* Bridge: NSBoolNumber {{{ */
892 @implementation NSBoolNumber (Cycript)
894 - (JSType) cy$JSType {
895 return kJSTypeBoolean;
898 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
899 NSString *value([self boolValue] ? @"true" : @"false");
900 return objective ? value : [NSString stringWithFormat:@"@%@", value];
903 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
904 return CYCastJSValue(context, (bool) [self boolValue]);
910 /* Bridge: NSDictionary {{{ */
911 @implementation NSDictionary (Cycript)
914 return [[self mutableCopy] autorelease];
917 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
918 _oassert(objects.insert(self).second);
920 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
921 [json appendString:@"@{"];
925 for (NSObject *key in self) {
927 NSEnumerator *keys([self keyEnumerator]);
928 while (NSObject *key = [keys nextObject]) {
931 [json appendString:@","];
934 [json appendString:CYCastNSCYON(key, true, objects)];
935 [json appendString:@":"];
936 NSObject *object([self objectForKey:key]);
937 [json appendString:CYCastNSCYON(object, true, objects)];
940 [json appendString:@"}"];
944 - (bool) cy$hasProperty:(NSString *)name {
945 return [self objectForKey:name] != nil;
948 - (NSObject *) cy$getProperty:(NSString *)name {
949 return [self objectForKey:name];
952 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
953 [super cy$getPropertyNames:names inContext:context];
956 for (NSObject *key in self) {
958 NSEnumerator *keys([self keyEnumerator]);
959 while (NSObject *key = [keys nextObject]) {
961 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
965 + (bool) cy$hasImplicitProperties {
971 /* Bridge: NSMutableArray {{{ */
972 @implementation NSMutableArray (Cycript)
974 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
975 if ([name isEqualToString:@"length"]) {
976 // XXX: is this not intelligent?
977 NSNumber *number(reinterpret_cast<NSNumber *>(value));
979 NSUInteger size([number unsignedIntegerValue]);
981 NSUInteger size([number unsignedIntValue]);
983 NSUInteger count([self count]);
985 [self removeObjectsInRange:NSMakeRange(size, count - size)];
986 else if (size != count) {
987 WebUndefined *undefined([WebUndefined undefined]);
988 for (size_t i(count); i != size; ++i)
989 [self addObject:undefined];
994 size_t index(CYGetIndex(name));
995 if (index == _not(size_t))
996 return [super cy$setProperty:name to:value];
998 id object(value ?: [NSNull null]);
1000 size_t count([self count]);
1002 [self replaceObjectAtIndex:index withObject:object];
1004 if (index != count) {
1005 WebUndefined *undefined([WebUndefined undefined]);
1006 for (size_t i(count); i != index; ++i)
1007 [self addObject:undefined];
1010 [self addObject:object];
1016 - (bool) cy$deleteProperty:(NSString *)name {
1017 size_t index(CYGetIndex(name));
1018 if (index == _not(size_t) || index >= [self count])
1019 return [super cy$deleteProperty:name];
1020 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1026 /* Bridge: NSMutableDictionary {{{ */
1027 @implementation NSMutableDictionary (Cycript)
1029 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1030 [self setObject:(value ?: [NSNull null]) forKey:name];
1034 - (bool) cy$deleteProperty:(NSString *)name {
1035 if ([self objectForKey:name] == nil)
1038 [self removeObjectForKey:name];
1045 /* Bridge: NSNumber {{{ */
1046 @implementation NSNumber (Cycript)
1048 - (JSType) cy$JSType {
1050 // XXX: this just seems stupid
1051 if ([self class] == NSCFBoolean_)
1052 return kJSTypeBoolean;
1054 return kJSTypeNumber;
1057 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1058 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1059 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1062 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1063 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1064 } CYObjectiveCatch }
1068 /* Bridge: NSNull {{{ */
1069 @implementation NSNull (Cycript)
1071 - (JSType) cy$JSType {
1075 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1076 NSString *value(@"null");
1077 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1080 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1081 return CYJSNull(context);
1082 } CYObjectiveCatch }
1086 /* Bridge: NSObject {{{ */
1087 @implementation NSObject (Cycript)
1093 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1094 return [self cy$valueOfInContext:context];
1097 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1099 } CYObjectiveCatch }
1101 - (JSType) cy$JSType {
1102 return kJSTypeObject;
1105 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1106 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1109 - (bool) cy$hasProperty:(NSString *)name {
1113 - (NSObject *) cy$getProperty:(NSString *)name {
1117 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1118 if (NSObject *value = [self cy$getProperty:name])
1119 return CYCastJSValue(context, value);
1121 } CYObjectiveCatch }
1123 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1127 - (bool) cy$deleteProperty:(NSString *)name {
1131 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1134 + (bool) cy$hasImplicitProperties {
1140 /* Bridge: NSProxy {{{ */
1141 @implementation NSProxy (Cycript)
1143 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1144 return [[self description] cy$toCYON:objective inSet:objects];
1149 /* Bridge: NSSet {{{ */
1150 @implementation NSSet (Cycript)
1152 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1153 _oassert(objects.insert(self).second);
1155 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1156 [json appendString:@"[NSSet setWithArray:"];
1157 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1158 [json appendString:@"]]"];
1164 /* Bridge: NSString {{{ */
1165 @implementation NSString (Cycript)
1168 return [[self copy] autorelease];
1171 - (JSType) cy$JSType {
1172 return kJSTypeString;
1175 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1176 std::ostringstream str;
1179 CYUTF8String string(CYCastUTF8String(self));
1180 CYStringify(str, string.data, string.size);
1181 std::string value(str.str());
1182 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1185 - (bool) cy$hasProperty:(NSString *)name {
1186 size_t index(CYGetIndex(name));
1187 if (index == _not(size_t) || index >= [self length])
1188 return [super cy$hasProperty:name];
1193 - (NSObject *) cy$getProperty:(NSString *)name {
1194 size_t index(CYGetIndex(name));
1195 if (index == _not(size_t) || index >= [self length])
1196 return [super cy$getProperty:name];
1198 return [self substringWithRange:NSMakeRange(index, 1)];
1201 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1202 [super cy$getPropertyNames:names inContext:context];
1204 for (size_t index(0), length([self length]); index != length; ++index) {
1206 sprintf(name, "%zu", index);
1207 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1211 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1212 return CYCastJSValue(context, CYJSString(context, self));
1213 } CYObjectiveCatch }
1217 /* Bridge: WebUndefined {{{ */
1218 @implementation WebUndefined (Cycript)
1220 - (JSType) cy$JSType {
1221 return kJSTypeUndefined;
1224 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1225 NSString *value(@"undefined");
1226 return value; // XXX: maybe use the below code, adding @undefined?
1227 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1230 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1231 return CYJSUndefined(context);
1232 } CYObjectiveCatch }
1237 static bool CYIsClass(id self) {
1239 return class_isMetaClass(object_getClass(self));
1241 return GSObjCIsClass(self);
1245 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1246 id self(CYCastNSObject(&pool, context, value));
1247 if (CYIsClass(self))
1248 return (Class) self;
1249 throw CYJSError(context, "got something that is not a Class");
1253 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1255 size_t size(JSPropertyNameArrayGetCount(names));
1256 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1257 for (size_t index(0); index != size; ++index)
1258 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1262 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1264 return CYJSNull(context);
1266 return CYMakeInstance(context, value, false);
1267 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1269 @implementation CYJSObject
1271 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1272 if ((self = [super init]) != nil) {
1274 context_ = CYGetJSContext(context);
1275 JSGlobalContextRetain(context_);
1276 JSValueProtect(context_, object_);
1278 } CYObjectiveCatch }
1280 - (void) dealloc { CYObjectiveTry {
1281 JSValueUnprotect(context_, object_);
1282 JSGlobalContextRelease(context_);
1284 } CYObjectiveCatch }
1286 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1288 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1290 return [super cy$toCYON:objective inSet:objects];
1292 return [NSString stringWithUTF8String:cyon];
1293 } CYObjectiveCatch }
1295 - (NSUInteger) count { CYObjectiveTry {
1296 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1297 size_t size(JSPropertyNameArrayGetCount(names));
1298 JSPropertyNameArrayRelease(names);
1300 } CYObjectiveCatch }
1302 - (id) objectForKey:(id)key { CYObjectiveTry {
1303 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1304 if (JSValueIsUndefined(context, value))
1306 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1307 } CYObjectiveCatch }
1309 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1310 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1311 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1312 JSPropertyNameArrayRelease(names);
1314 } CYObjectiveCatch }
1316 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1317 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1318 } CYObjectiveCatch }
1320 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1321 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1322 } CYObjectiveCatch }
1326 @implementation CYJSArray
1328 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1330 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1331 } CYObjectiveCatch }
1333 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1334 if ((self = [super init]) != nil) {
1336 context_ = CYGetJSContext(context);
1337 JSGlobalContextRetain(context_);
1338 JSValueProtect(context_, object_);
1340 } CYObjectiveCatch }
1342 - (void) dealloc { CYObjectiveTry {
1343 JSValueUnprotect(context_, object_);
1344 JSGlobalContextRelease(context_);
1346 } CYObjectiveCatch }
1348 - (NSUInteger) count { CYObjectiveTry {
1349 return CYArrayLength(context, object_);
1350 } CYObjectiveCatch }
1352 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1353 size_t bounds([self count]);
1354 if (index >= bounds)
1355 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1356 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1357 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1358 } CYObjectiveCatch }
1360 - (void) addObject:(id)object { CYObjectiveTry {
1361 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1362 } CYObjectiveCatch }
1364 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1365 size_t bounds([self count] + 1);
1366 if (index >= bounds)
1367 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1368 JSValueRef arguments[3];
1369 arguments[0] = CYCastJSValue(context, index);
1370 arguments[1] = CYCastJSValue(context, 0);
1371 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1372 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1373 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1374 } CYObjectiveCatch }
1376 - (void) removeLastObject { CYObjectiveTry {
1377 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1378 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1379 } CYObjectiveCatch }
1381 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1382 size_t bounds([self count]);
1383 if (index >= bounds)
1384 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1385 JSValueRef arguments[2];
1386 arguments[0] = CYCastJSValue(context, index);
1387 arguments[1] = CYCastJSValue(context, 1);
1388 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1389 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1390 } CYObjectiveCatch }
1392 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1393 size_t bounds([self count]);
1394 if (index >= bounds)
1395 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1396 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1397 } CYObjectiveCatch }
1401 // XXX: inherit from or replace with CYJSObject
1402 @interface CYInternal : NSObject {
1403 JSGlobalContextRef context_;
1404 JSObjectRef object_;
1409 @implementation CYInternal
1411 - (void) dealloc { CYObjectiveTry {
1412 JSValueUnprotect(context_, object_);
1413 JSGlobalContextRelease(context_);
1415 } CYObjectiveCatch }
1417 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1418 if ((self = [super init]) != nil) {
1419 context_ = CYGetJSContext(context);
1420 JSGlobalContextRetain(context_);
1422 } CYObjectiveCatch }
1424 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1425 if (object_ == NULL)
1428 return JSObjectHasProperty(context, object_, name);
1431 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1432 if (object_ == NULL)
1435 return CYGetProperty(context, object_, name);
1438 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1439 @synchronized (self) {
1440 if (object_ == NULL) {
1441 object_ = JSObjectMake(context, NULL, NULL);
1442 JSValueProtect(context, object_);
1446 CYSetProperty(context, object_, name, value);
1449 + (CYInternal *) get:(id)object {
1450 if ($objc_getAssociatedObject == NULL)
1453 @synchronized (object) {
1454 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1461 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1462 if ($objc_getAssociatedObject == NULL)
1465 @synchronized (object) {
1466 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1469 if ($objc_setAssociatedObject == NULL)
1472 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1473 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1482 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1483 Selector_privateData *internal(new Selector_privateData(sel));
1484 return JSObjectMake(context, Selector_, internal);
1487 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1488 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1489 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1490 return reinterpret_cast<SEL>(internal->value_);
1493 return sel_registerName(CYPoolCString(pool, context, value));
1497 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1498 return (void *) [[NSAutoreleasePool alloc] init];
1499 } CYSadCatch(NULL) }
1501 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1502 return [(NSAutoreleasePool *) handle release];
1505 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1507 return Instance::Make(context, nil);
1508 if (Class _class = objc_getClass(name.data))
1509 return CYMakeInstance(context, _class, true);
1510 if (Protocol *protocol = objc_getProtocol(name.data))
1511 return CYMakeInstance(context, protocol, true);
1513 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1515 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1516 ffi_call(cif, function, value, values);
1519 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, sig::Signature *signature) {
1520 if (JSValueIsNull(context, value))
1522 JSObjectRef object(CYCastJSObject(context, value));
1524 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1525 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1527 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1528 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1532 _assert(JSObjectIsFunction(context, object));
1534 _assert(signature != NULL);
1535 _assert(signature->count != 0);
1537 sig::Signature modified;
1538 modified.count = signature->count + 1;
1539 modified.elements = new(pool) sig::Element[modified.count];
1541 modified.elements[0] = signature->elements[0];
1542 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1544 modified.elements[1].name = NULL;
1545 modified.elements[1].type = new(pool) sig::Type();
1546 modified.elements[1].offset = _not(size_t);
1548 memset(modified.elements[1].type, 0, sizeof(sig::Type));
1549 modified.elements[1].type->primitive = sig::object_P;
1551 return CYMakeBlock(context, object, modified);
1554 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1555 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1557 switch (type->primitive) {
1559 // XXX: this function might not handle the idea of a null pool
1560 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &type->data.signature);
1564 case sig::typename_P:
1565 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1568 case sig::selector_P:
1569 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1577 } CYSadCatch(false) }
1579 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1580 switch (type->primitive) {
1581 // XXX: do something epic about blocks
1584 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1585 JSValueRef value(CYCastJSValue(context, object));
1591 case sig::typename_P:
1592 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1594 case sig::selector_P:
1595 if (SEL sel = *reinterpret_cast<SEL *>(data))
1596 return CYMakeSelector(context, sel);
1600 return CYJSNull(context);
1604 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1606 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1607 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1610 #if OBJC_API_VERSION >= 2
1612 method_getReturnType(method, type, sizeof(type));
1614 const char *type(method_getTypeEncoding(method));
1620 // XXX: possibly use a more "awesome" check?
1624 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1625 JSObjectRef _this(CYCastJSObject(context, values[0]));
1626 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1629 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1630 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1633 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1634 Message_privateData *internal(new Message_privateData(sel, type, imp));
1635 return JSObjectMake(context, Message_, internal);
1638 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1639 JSObjectRef function(CYCastJSObject(context, value));
1641 sig::Signature signature;
1642 sig::Parse(pool, &signature, encoding, &Structor_);
1643 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageClosure_));
1644 // XXX: see notes in Library.cpp about needing to leak
1645 return reinterpret_cast<IMP>(internal->GetValue());
1648 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1649 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1650 Class _class(internal->GetValue());
1653 const char *name(CYPoolCString(pool, context, property));
1655 if (SEL sel = sel_getUid(name))
1656 if (class_getInstanceMethod(_class, sel) != NULL)
1662 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1663 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1664 Class _class(internal->GetValue());
1667 const char *name(CYPoolCString(pool, context, property));
1669 if (SEL sel = sel_getUid(name))
1670 if (objc_method *method = class_getInstanceMethod(_class, sel))
1671 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1676 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1677 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1678 Class _class(internal->GetValue());
1681 const char *name(CYPoolCString(pool, context, property));
1682 SEL sel(sel_registerName(name));
1687 if (JSValueIsObjectOfClass(context, value, Message_)) {
1688 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1689 type = sig::Unparse(pool, &message->signature_);
1690 imp = reinterpret_cast<IMP>(message->GetValue());
1691 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1692 type = method_getTypeEncoding(method);
1693 imp = CYMakeMessage(context, value, type);
1694 } else _assert(false);
1696 objc_method *method(NULL);
1697 #if OBJC_API_VERSION >= 2
1699 objc_method **methods(class_copyMethodList(_class, &size));
1700 for (size_t i(0); i != size; ++i)
1701 if (sel_isEqual(method_getName(methods[i]), sel)) {
1702 method = methods[i];
1707 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1708 for (int i(0); i != methods->method_count; ++i)
1709 if (sel_isEqual(method_getName(&methods->method_list[i]), sel)) {
1710 method = &methods->method_list[i];
1716 method_setImplementation(method, imp);
1719 GSMethodList list(GSAllocMethodList(1));
1720 GSAppendMethodToList(list, sel, type, imp, YES);
1721 GSAddMethodList(_class, list, YES);
1722 GSFlushMethodCacheForClass(_class);
1724 class_addMethod(_class, sel, imp, type);
1731 #if 0 && OBJC_API_VERSION < 2
1732 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1733 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1734 Class _class(internal->GetValue());
1737 const char *name(CYPoolCString(pool, context, property));
1739 if (SEL sel = sel_getUid(name))
1740 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1741 objc_method_list list = {NULL, 1, {method}};
1742 class_removeMethods(_class, &list);
1750 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1751 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1752 Class _class(internal->GetValue());
1754 #if OBJC_API_VERSION >= 2
1756 objc_method **data(class_copyMethodList(_class, &size));
1757 for (size_t i(0); i != size; ++i)
1758 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1761 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1762 for (int i(0); i != methods->method_count; ++i)
1763 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1767 static bool CYHasImplicitProperties(Class _class) {
1768 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1769 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1771 return [_class cy$hasImplicitProperties];
1774 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1775 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1776 id self(internal->GetValue());
1778 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1782 NSString *name(CYCastNSString(&pool, context, property));
1784 if (CYInternal *internal = [CYInternal get:self])
1785 if ([internal hasProperty:property inContext:context])
1788 Class _class(object_getClass(self));
1791 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1792 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1793 if ([self cy$hasProperty:name])
1795 } CYPoolCatch(false)
1797 const char *string(CYPoolCString(pool, context, name));
1800 if (class_getProperty(_class, string) != NULL)
1804 if (CYHasImplicitProperties(_class))
1805 if (SEL sel = sel_getUid(string))
1806 if (CYImplements(self, _class, sel, true))
1812 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1813 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1814 id self(internal->GetValue());
1816 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1817 return Internal::Make(context, self, object);
1820 NSString *name(CYCastNSString(&pool, context, property));
1822 if (CYInternal *internal = [CYInternal get:self])
1823 if (JSValueRef value = [internal getProperty:property inContext:context])
1827 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1831 const char *string(CYPoolCString(pool, context, name));
1832 Class _class(object_getClass(self));
1835 if (objc_property_t property = class_getProperty(_class, string)) {
1836 PropertyAttributes attributes(property);
1837 SEL sel(sel_registerName(attributes.Getter()));
1838 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1842 if (CYHasImplicitProperties(_class))
1843 if (SEL sel = sel_getUid(string))
1844 if (CYImplements(self, _class, sel, true))
1845 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1850 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1851 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1852 id self(internal->GetValue());
1856 NSString *name(CYCastNSString(&pool, context, property));
1857 NSObject *data(CYCastNSObject(&pool, context, value));
1860 if ([self cy$setProperty:name to:data])
1862 } CYPoolCatch(false)
1864 const char *string(CYPoolCString(pool, context, name));
1865 Class _class(object_getClass(self));
1868 if (objc_property_t property = class_getProperty(_class, string)) {
1869 PropertyAttributes attributes(property);
1870 if (const char *setter = attributes.Setter()) {
1871 SEL sel(sel_registerName(setter));
1872 JSValueRef arguments[1] = {value};
1873 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1879 size_t length(strlen(string));
1881 char set[length + 5];
1887 if (string[0] != '\0') {
1888 set[3] = toupper(string[0]);
1889 memcpy(set + 4, string + 1, length - 1);
1892 set[length + 3] = ':';
1893 set[length + 4] = '\0';
1895 if (SEL sel = sel_getUid(set))
1896 if (CYImplements(self, _class, sel)) {
1897 JSValueRef arguments[1] = {value};
1898 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1902 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1903 [internal setProperty:property toValue:value inContext:context];
1910 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1911 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1912 id self(internal->GetValue());
1915 NSString *name(CYCastNSString(NULL, context, property));
1916 return [self cy$deleteProperty:name];
1917 } CYPoolCatch(false)
1918 } CYCatch(false) return /*XXX*/ false; }
1920 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1921 const char *name(sel_getName(method_getName(method)));
1922 if (strchr(name, ':') != NULL)
1925 const char *type(method_getTypeEncoding(method));
1926 if (type == NULL || *type == '\0' || *type == 'v')
1929 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1932 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1933 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1934 id self(internal->GetValue());
1937 Class _class(object_getClass(self));
1942 objc_property_t *data(class_copyPropertyList(_class, &size));
1943 for (size_t i(0); i != size; ++i)
1944 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1949 if (CYHasImplicitProperties(_class))
1950 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1951 #if OBJC_API_VERSION >= 2
1953 objc_method **data(class_copyMethodList(current, &size));
1954 for (size_t i(0); i != size; ++i)
1955 Instance_getPropertyNames_message(names, data[i]);
1958 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1959 for (int i(0); i != methods->method_count; ++i)
1960 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1965 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1966 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1967 [self cy$getPropertyNames:names inContext:context];
1971 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1972 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1973 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1977 static const char *CYBlockEncoding(NSBlock *self) {
1978 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1979 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1981 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1982 descriptor += sizeof(BlockDescriptor1);
1983 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1984 descriptor += sizeof(BlockDescriptor2);
1985 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1986 return descriptor3->signature;
1989 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1990 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1991 id self(internal->GetValue());
1993 if (const char *encoding = CYBlockEncoding(self)) {
1999 sig::Signature signature;
2000 sig::Parse(pool, &signature, encoding, &Structor_);
2003 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2005 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
2006 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
2007 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
2011 CYThrow("NSBlock without signature field passed arguments");
2015 } CYPoolCatch(NULL);
2020 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
2021 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2022 Class _class(internal->GetValue());
2023 if (!CYIsClass(_class))
2026 if (CYJSValueIsNSObject(context, instance)) {
2027 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2028 // XXX: this isn't always safe
2029 return [linternal->GetValue() isKindOfClass:_class];
2035 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2037 throw CYJSError(context, "incorrect number of arguments to Instance");
2039 id value(CYCastNSObject(&pool, context, arguments[0]));
2041 value = [NSNull null];
2042 return CYCastJSValue(context, [value cy$box]);
2045 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2046 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2049 id self(internal->GetValue());
2050 const char *name(CYPoolCString(pool, context, property));
2052 if (object_getInstanceVariable(self, name, NULL) != NULL)
2058 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2059 length = CYCastDouble(encoding + 1);
2063 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2064 for (size_t i(0); i != size; ++i)
2065 if (ivars[i] == ivar)
2067 else if (ivar_getOffset(ivars[i]) == offset) {
2068 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2069 _assert(encoding != NULL);
2070 _assert(encoding[0] == 'b');
2071 shift += CYCastDouble(encoding + 1);
2076 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2077 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2080 id self(internal->GetValue());
2081 const char *name(CYPoolCString(pool, context, property));
2084 if (strcmp(name, "isa") == 0)
2085 return CYCastJSValue(context, object_getClass(self));
2088 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2089 ptrdiff_t offset(ivar_getOffset(ivar));
2090 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2092 const char *encoding(ivar_getTypeEncoding(ivar));
2093 _assert(encoding != NULL);
2094 if (encoding[0] == 'b') {
2095 unsigned length, shift;
2096 CYBitField(length, shift, self, ivar, encoding, offset);
2097 _assert(shift + length <= sizeof(uintptr_t) * 8);
2098 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2099 uintptr_t mask((1 << length) - 1);
2100 return CYCastJSValue(context, (field >> shift) & mask);
2102 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2103 return CYFromFFI(context, type.type_, type.GetFFI(), data);
2110 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2111 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2114 id self(internal->GetValue());
2115 const char *name(CYPoolCString(pool, context, property));
2117 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2118 ptrdiff_t offset(ivar_getOffset(ivar));
2119 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2121 const char *encoding(ivar_getTypeEncoding(ivar));
2122 _assert(encoding != NULL);
2123 if (encoding[0] == 'b') {
2124 unsigned length, shift;
2125 CYBitField(length, shift, self, ivar, encoding, offset);
2126 _assert(shift + length <= sizeof(uintptr_t) * 8);
2127 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2128 uintptr_t mask((1 << length) - 1);
2129 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2131 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2132 CYPoolFFI(&pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2140 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2141 if (Class super = class_getSuperclass(_class))
2142 Internal_getPropertyNames_(super, names);
2144 #if OBJC_API_VERSION >= 2
2146 objc_ivar **data(class_copyIvarList(_class, &size));
2147 for (size_t i(0); i != size; ++i)
2148 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2151 if (objc_ivar_list *ivars = _class->ivars)
2152 for (int i(0); i != ivars->ivar_count; ++i)
2153 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2157 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2158 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2161 id self(internal->GetValue());
2162 Class _class(object_getClass(self));
2164 Internal_getPropertyNames_(_class, names);
2167 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2168 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2169 return internal->GetOwner();
2172 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2174 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2177 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2179 NSString *name(CYCastNSString(&pool, context, property));
2180 if (Class _class = NSClassFromString(name))
2181 return CYMakeInstance(context, _class, true);
2186 static Class *CYCopyClassList(size_t &size) {
2187 size = objc_getClassList(NULL, 0);
2188 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2191 size_t writ(objc_getClassList(data, size));
2197 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2209 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2212 if (Class *data = CYCopyClassList(size)) {
2213 for (size_t i(0); i != size; ++i)
2214 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2219 while (Class _class = objc_next_class(&state))
2220 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2224 #if OBJC_API_VERSION >= 2
2225 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2226 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2229 const char *name(CYPoolCString(pool, context, property));
2231 const char **data(objc_copyClassNamesForImage(internal, &size));
2233 for (size_t i(0); i != size; ++i)
2234 if (strcmp(name, data[i]) == 0) {
2235 if (Class _class = objc_getClass(name)) {
2236 value = CYMakeInstance(context, _class, true);
2247 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2248 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2250 const char **data(objc_copyClassNamesForImage(internal, &size));
2251 for (size_t i(0); i != size; ++i)
2252 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2256 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2258 const char *name(CYPoolCString(pool, context, property));
2260 const char **data(objc_copyImageNames(&size));
2261 for (size_t i(0); i != size; ++i)
2262 if (strcmp(name, data[i]) == 0) {
2271 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2272 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2276 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2278 const char **data(objc_copyImageNames(&size));
2279 for (size_t i(0); i != size; ++i)
2280 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2285 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2287 const char *name(CYPoolCString(pool, context, property));
2288 if (Protocol *protocol = objc_getProtocol(name))
2289 return CYMakeInstance(context, protocol, true);
2293 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2294 #if OBJC_API_VERSION >= 2
2296 Protocol **data(objc_copyProtocolList(&size));
2297 for (size_t i(0); i != size; ++i)
2298 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2305 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2307 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2309 return Instance::Make(context, nil);
2313 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2314 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2318 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2319 *data = reinterpret_cast<void *>(address);
2320 return KERN_SUCCESS;
2324 std::set<Class> query_;
2325 JSContextRef context_;
2326 JSObjectRef results_;
2329 struct CYObjectStruct {
2333 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2334 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2335 JSContextRef context(choice->context_);
2337 for (unsigned i(0); i != count; ++i) {
2338 vm_range_t &range(ranges[i]);
2339 void *data(reinterpret_cast<void *>(range.address));
2340 size_t size(range.size);
2342 if (size < sizeof(CYObjectStruct))
2345 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2347 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2349 Class isa(reinterpret_cast<Class>(pointers[0]));
2352 std::set<Class>::const_iterator result(choice->query_.find(isa));
2353 if (result == choice->query_.end())
2356 size_t needed(class_getInstanceSize(*result));
2357 // XXX: if (size < needed)
2359 size_t boundary(496);
2363 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2365 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2369 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2371 throw CYJSError(context, "choose() takes a class argument");
2373 CYGarbageCollect(context);
2376 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2378 vm_address_t *zones(NULL);
2380 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2381 _assert(error == KERN_SUCCESS);
2383 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2384 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2387 choice.context_ = context;
2388 choice.results_ = results;
2391 Class *classes(CYCopyClassList(number));
2392 _assert(classes != NULL);
2394 for (size_t i(0); i != number; ++i)
2395 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2396 if (current == _class) {
2397 choice.query_.insert(classes[i]);
2403 for (unsigned i(0); i != size; ++i) {
2404 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2405 if (zone == NULL || zone->introspect == NULL)
2408 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2416 #if defined(__i386__) || defined(__x86_64__)
2417 #define OBJC_MAX_STRUCT_BY_VALUE 8
2418 static int struct_forward_array[] = {
2419 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2420 #elif defined(__arm__)
2421 #define OBJC_MAX_STRUCT_BY_VALUE 1
2422 static int struct_forward_array[] = {
2424 #elif defined(__arm64__)
2427 #error missing objc-runtime-info
2431 static bool stret(ffi_type *ffi_type) {
2432 return ffi_type->type == FFI_TYPE_STRUCT && (
2433 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2434 struct_forward_array[ffi_type->size] != 0
2440 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2444 _class = object_getClass(self);
2448 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2449 imp = method_getImplementation(method);
2450 type = method_getTypeEncoding(method);
2455 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2457 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2458 type = CYPoolCString(pool, context, [method _typeString]);
2466 sig::Signature signature;
2467 sig::Parse(pool, &signature, type, &Structor_);
2469 size_t used(count + 3);
2470 if (used > signature.count) {
2471 sig::Element *elements(new (pool) sig::Element[used]);
2472 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2474 for (size_t index(signature.count); index != used; ++index) {
2475 sig::Element *element(&elements[index]);
2476 element->name = NULL;
2477 element->offset = _not(size_t);
2479 sig::Type *type(new (pool) sig::Type);
2480 memset(type, 0, sizeof(*type));
2481 type->primitive = sig::object_P;
2482 element->type = type;
2485 signature.elements = elements;
2486 signature.count = used;
2490 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2495 if (stret(cif.rtype))
2496 imp = class_getMethodImplementation_stret(_class, _cmd);
2499 imp = class_getMethodImplementation(_class, _cmd);
2501 objc_super super = {self, _class};
2502 imp = objc_msg_lookup_super(&super, _cmd);
2506 void (*function)() = reinterpret_cast<void (*)()>(imp);
2507 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2510 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2512 throw CYJSError(context, "too few arguments to objc_msgSend");
2522 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2523 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2524 self = internal->GetValue();
2525 _class = internal->class_;;
2526 uninitialized = false;
2527 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2528 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2529 self = internal->GetValue();
2531 uninitialized = internal->IsUninitialized();
2533 internal->value_ = nil;
2535 self = CYCastNSObject(&pool, context, arguments[0]);
2537 uninitialized = false;
2541 return CYJSNull(context);
2543 _cmd = CYCastSEL(context, arguments[1]);
2545 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2548 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2549 return $objc_msgSend(context, object, _this, count, arguments);
2552 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2553 JSValueRef setup[count + 2];
2556 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2557 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2560 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2562 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2564 // XXX: handle Instance::Uninitialized?
2565 id self(CYCastNSObject(&pool, context, _this));
2569 setup[1] = &internal->sel_;
2571 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2574 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2576 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2578 id self(CYCastNSObject(&pool, context, arguments[0]));
2579 Class _class(CYCastClass(pool, context, arguments[1]));
2580 return cy::Super::Make(context, self, _class);
2583 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2585 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2587 const char *name(CYPoolCString(pool, context, arguments[0]));
2588 return CYMakeSelector(context, sel_registerName(name));
2591 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2593 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2594 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2595 return CYMakeInstance(context, self, false);
2598 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2599 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2600 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2603 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2604 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2605 Type_privateData *typical(internal->GetType());
2610 if (typical == NULL) {
2614 type = typical->type_;
2615 ffi = typical->ffi_;
2618 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2621 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2622 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2623 const char *encoding(CYBlockEncoding(internal->GetValue()));
2624 if (encoding == NULL)
2625 return CYJSNull(context);
2626 // XXX: this should be stored on a FunctionInstance private value subclass
2628 sig::Signature signature;
2629 sig::Parse(pool, &signature, encoding, &Structor_);
2630 return CYMakeType(context, &signature);
2633 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2634 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2635 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2638 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2639 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2640 id self(internal->GetValue());
2641 if (!CYIsClass(self))
2642 return CYJSUndefined(context);
2643 return CYGetClassPrototype(context, self);
2646 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2647 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2648 id self(internal->GetValue());
2649 if (!CYIsClass(self))
2650 return CYJSUndefined(context);
2651 return Messages::Make(context, (Class) self);
2654 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2655 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2657 if (!CYJSValueIsNSObject(context, _this))
2660 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2661 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2664 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2665 if (!CYJSValueIsNSObject(context, _this))
2668 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2669 id value(internal->GetValue());
2676 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2678 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2679 return CYJSUndefined(context);
2680 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2683 return CYCastJSValue(context, CYJSString(context, [value description]));
2685 } CYCatch(NULL) return /*XXX*/ NULL; }
2687 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2688 if (!CYJSValueIsNSObject(context, _this))
2691 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2692 id value(internal->GetValue());
2694 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2697 if (JSValueRef result = [value cy$valueOfInContext:context])
2701 } CYCatch(NULL) return /*XXX*/ NULL; }
2703 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2704 if (!CYJSValueIsNSObject(context, _this))
2707 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2708 // XXX: but... but... THIS ISN'T A POINTER! :(
2709 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2710 } CYCatch(NULL) return /*XXX*/ NULL; }
2712 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2713 if (!CYJSValueIsNSObject(context, _this))
2716 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2717 id value(internal->GetValue());
2720 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2721 return CYCastJSValue(context, CYJSString(context, [value description]));
2723 } CYCatch(NULL) return /*XXX*/ NULL; }
2725 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2726 if (!CYJSValueIsNSObject(context, _this))
2729 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2730 id value(internal->GetValue());
2732 if (!CYIsClass(value))
2733 CYThrow("non-Class object cannot be used as Type");
2735 // XXX: this is a very silly implementation
2737 std::ostringstream type;
2739 type << class_getName(value);
2743 return CYMakeType(context, type.str().c_str());
2745 } CYCatch(NULL) return /*XXX*/ NULL; }
2747 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2748 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2749 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2752 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2753 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2756 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2757 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2758 const char *name(sel_getName(internal->GetValue()));
2761 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2762 return CYCastJSValue(context, CYJSString(context, string));
2764 } CYCatch(NULL) return /*XXX*/ NULL; }
2766 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2768 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2771 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2772 SEL sel(internal->GetValue());
2774 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2775 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2776 const char *encoding(method_getTypeEncoding(method));
2778 sig::Signature signature;
2779 sig::Parse(pool, &signature, encoding, &Structor_);
2780 return CYMakeType(context, &signature);
2783 static JSStaticValue Selector_staticValues[2] = {
2784 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2785 {NULL, NULL, NULL, 0}
2788 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2789 static JSStaticValue Instance_staticValues[5] = {
2790 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2791 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2792 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2793 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2794 {NULL, NULL, NULL, 0}
2797 static JSStaticValue FunctionInstance_staticValues[6] = {
2798 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2799 // XXX: this is sadly a duplicate of Instance_staticValues
2800 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2801 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2802 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2803 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2804 {NULL, NULL, NULL, 0}
2807 static JSStaticFunction Instance_staticFunctions[7] = {
2808 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2809 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2810 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2811 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2812 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2813 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2817 static JSStaticFunction Class_staticFunctions[2] = {
2818 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2822 static JSStaticFunction Internal_staticFunctions[2] = {
2823 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2827 static JSStaticFunction Selector_staticFunctions[5] = {
2828 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2829 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2830 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2831 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2836 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2837 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2838 } CYObjectiveCatch }
2841 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2842 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2843 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2844 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2846 CYPool &pool(CYGetGlobalPool());
2848 Object_type = new(pool) Type_privateData("@");
2849 Selector_type = new(pool) Type_privateData(":");
2851 NSArray_ = objc_getClass("NSArray");
2852 NSBlock_ = objc_getClass("NSBlock");
2853 NSDictionary_ = objc_getClass("NSDictionary");
2854 NSNumber_ = objc_getClass("NSNumber");
2855 NSString_ = objc_getClass("NSString");
2856 Object_ = objc_getClass("Object");
2859 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2861 // XXX: apparently, iOS now has both of these
2862 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2863 if (NSCFBoolean_ == nil)
2864 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2866 NSCFType_ = objc_getClass("NSCFType");
2868 NSZombie_ = objc_getClass("_NSZombie_");
2870 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2873 JSClassDefinition definition;
2875 definition = kJSClassDefinitionEmpty;
2876 definition.className = "Instance";
2877 definition.staticValues = Instance_staticValues;
2878 definition.staticFunctions = Instance_staticFunctions;
2879 definition.hasProperty = &Instance_hasProperty;
2880 definition.getProperty = &Instance_getProperty;
2881 definition.setProperty = &Instance_setProperty;
2882 definition.deleteProperty = &Instance_deleteProperty;
2883 definition.getPropertyNames = &Instance_getPropertyNames;
2884 definition.callAsConstructor = &Instance_callAsConstructor;
2885 definition.hasInstance = &Instance_hasInstance;
2886 definition.finalize = &CYFinalize;
2887 Instance_ = JSClassCreate(&definition);
2889 definition.className = "ArrayInstance";
2890 ArrayInstance_ = JSClassCreate(&definition);
2892 definition.className = "BooleanInstance";
2893 BooleanInstance_ = JSClassCreate(&definition);
2895 definition.className = "NumberInstance";
2896 NumberInstance_ = JSClassCreate(&definition);
2898 definition.className = "ObjectInstance";
2899 ObjectInstance_ = JSClassCreate(&definition);
2901 definition.className = "StringInstance";
2902 StringInstance_ = JSClassCreate(&definition);
2904 definition.className = "FunctionInstance";
2905 definition.staticValues = FunctionInstance_staticValues;
2906 definition.callAsFunction = &FunctionInstance_callAsFunction;
2907 FunctionInstance_ = JSClassCreate(&definition);
2909 definition = kJSClassDefinitionEmpty;
2910 definition.className = "Class";
2911 definition.staticFunctions = Class_staticFunctions;
2912 Class_ = JSClassCreate(&definition);
2914 definition = kJSClassDefinitionEmpty;
2915 definition.className = "Internal";
2916 definition.staticFunctions = Internal_staticFunctions;
2917 definition.hasProperty = &Internal_hasProperty;
2918 definition.getProperty = &Internal_getProperty;
2919 definition.setProperty = &Internal_setProperty;
2920 definition.getPropertyNames = &Internal_getPropertyNames;
2921 definition.finalize = &CYFinalize;
2922 Internal_ = JSClassCreate(&definition);
2924 definition = kJSClassDefinitionEmpty;
2925 definition.className = "Message";
2926 definition.staticFunctions = cy::Functor::StaticFunctions;
2927 definition.staticValues = cy::Functor::StaticValues;
2928 definition.callAsFunction = &Message_callAsFunction;
2929 definition.finalize = &CYFinalize;
2930 Message_ = JSClassCreate(&definition);
2932 definition = kJSClassDefinitionEmpty;
2933 definition.className = "Messages";
2934 definition.hasProperty = &Messages_hasProperty;
2935 definition.getProperty = &Messages_getProperty;
2936 definition.setProperty = &Messages_setProperty;
2937 #if 0 && OBJC_API_VERSION < 2
2938 definition.deleteProperty = &Messages_deleteProperty;
2940 definition.getPropertyNames = &Messages_getPropertyNames;
2941 definition.finalize = &CYFinalize;
2942 Messages_ = JSClassCreate(&definition);
2944 definition = kJSClassDefinitionEmpty;
2945 definition.className = "Selector";
2946 definition.staticValues = Selector_staticValues;
2947 definition.staticFunctions = Selector_staticFunctions;
2948 definition.callAsFunction = &Selector_callAsFunction;
2949 definition.finalize = &CYFinalize;
2950 Selector_ = JSClassCreate(&definition);
2952 definition = kJSClassDefinitionEmpty;
2953 definition.className = "Super";
2954 definition.staticFunctions = Internal_staticFunctions;
2955 definition.finalize = &CYFinalize;
2956 Super_ = JSClassCreate(&definition);
2958 definition = kJSClassDefinitionEmpty;
2959 definition.className = "ObjectiveC::Classes";
2960 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2961 definition.getProperty = &ObjectiveC_Classes_getProperty;
2962 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2963 ObjectiveC_Classes_ = JSClassCreate(&definition);
2965 definition = kJSClassDefinitionEmpty;
2966 definition.className = "ObjectiveC::Constants";
2967 definition.getProperty = &ObjectiveC_Constants_getProperty;
2968 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2969 ObjectiveC_Constants_ = JSClassCreate(&definition);
2971 #if OBJC_API_VERSION >= 2
2972 definition = kJSClassDefinitionEmpty;
2973 definition.className = "ObjectiveC::Images";
2974 definition.getProperty = &ObjectiveC_Images_getProperty;
2975 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2976 ObjectiveC_Images_ = JSClassCreate(&definition);
2978 definition = kJSClassDefinitionEmpty;
2979 definition.className = "ObjectiveC::Image::Classes";
2980 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2981 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2982 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2985 definition = kJSClassDefinitionEmpty;
2986 definition.className = "ObjectiveC::Protocols";
2987 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2988 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2989 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2992 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2993 // XXX: this is horrible; there has to be a better way to do this
2995 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2997 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
3003 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
3004 JSObjectRef global(CYGetGlobalObject(context));
3005 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
3006 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
3007 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
3008 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
3010 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
3011 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
3013 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3014 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
3015 CYArrayPush(context, alls, protocols);
3017 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
3018 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
3019 CYArrayPush(context, alls, classes);
3021 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
3022 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
3023 CYArrayPush(context, alls, constants);
3025 #if OBJC_API_VERSION >= 2
3026 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3029 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
3030 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3031 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3032 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3033 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
3035 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
3036 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3038 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
3039 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
3040 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
3041 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
3042 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
3044 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
3045 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
3046 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
3047 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
3048 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
3050 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
3051 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
3052 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
3053 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
3054 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
3056 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
3057 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
3058 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
3059 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
3060 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
3062 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3063 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3064 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3065 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3066 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3068 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3069 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3070 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3071 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3072 CYSetPrototype(context, StringInstance_prototype, String_prototype);
3074 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
3075 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
3076 CYSetPrototype(context, Class_prototype, Instance_prototype);
3078 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3079 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3080 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3082 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3083 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3086 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3089 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3091 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3092 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3095 static CYHooks CYObjectiveCHooks = {
3096 &CYObjectiveC_ExecuteStart,
3097 &CYObjectiveC_ExecuteEnd,
3098 &CYObjectiveC_CallFunction,
3099 &CYObjectiveC_Initialize,
3100 &CYObjectiveC_SetupContext,
3101 &CYObjectiveC_PoolFFI,
3102 &CYObjectiveC_FromFFI,
3105 struct CYObjectiveC {
3107 hooks_ = &CYObjectiveCHooks;
3108 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
3109 _assert(hooks_ != NULL);
3113 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3114 CYSetupContext(context);
3115 } CYObjectiveCatch }
3117 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3120 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3121 CYStream stream(utf8.data, utf8.data + utf8.size);
3122 utf8 = CYPoolCode(pool, stream);
3124 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3125 size_t bytes(utf16.size * sizeof(uint16_t));
3126 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3127 memcpy(copy, utf16.data, bytes);
3131 } catch (const CYException &exception) {
3133 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];