1 /* Cycript - The Truly Universal Scripting Language
2 * Copyright (C) 2009-2016 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "cycript.hpp"
32 #include <malloc/malloc.h>
33 #include <mach/mach.h>
36 #include <objc/message.h>
37 #include <objc/runtime.h>
40 #include <CoreFoundation/CoreFoundation.h>
41 #include <JavaScriptCore/JSStringRefCF.h>
44 #include <Foundation/Foundation.h>
49 #include "Functor.hpp"
50 #include "JavaScript.hpp"
52 #include "Execute.hpp"
54 #include "ObjectiveC/Internal.hpp"
55 #include "ObjectiveC/Syntax.hpp"
57 #define CYObjectiveTry_ { \
59 #define CYObjectiveTry { \
60 JSContextRef context(context_); \
62 #define CYObjectiveCatch \
63 catch (const CYException &error) { \
64 @throw CYCastNSObject(NULL, context, error.CastJSValue(context, "Error")); \
70 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
72 #define CYPoolCatch(value) \
73 @catch (NSException *error) { \
74 _saved = [error retain]; \
75 throw CYJSError(context, CYCastJSValue(context, error)); \
80 [_saved autorelease]; \
86 #define CYSadCatch(value) \
87 @catch (NSException *error ) { \
88 throw CYJSError(context, CYCastJSValue(context, error)); \
92 #define _oassert(test) \
94 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"_assert(" #test ")" userInfo:nil];
102 void (*invoke)(void *, ...);
106 struct BlockDescriptor1 {
107 unsigned long int reserved;
108 unsigned long int size;
111 struct BlockDescriptor2 {
112 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
113 void (*dispose_helper)(BlockLiteral *src);
116 struct BlockDescriptor3 {
117 const char *signature;
122 BLOCK_DEALLOCATING = 0x0001,
123 BLOCK_REFCOUNT_MASK = 0xfffe,
124 BLOCK_NEEDS_FREE = 1 << 24,
125 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
126 BLOCK_HAS_CTOR = 1 << 26,
127 BLOCK_IS_GC = 1 << 27,
128 BLOCK_IS_GLOBAL = 1 << 28,
129 BLOCK_HAS_STRET = 1 << 29,
130 BLOCK_HAS_SIGNATURE = 1 << 30,
133 static bool CYIsClass(id self) {
134 return class_isMetaClass(object_getClass(self));
137 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
139 /* Objective-C Pool Release {{{ */
140 void CYPoolRelease_(void *data) {
141 id object(reinterpret_cast<id>(data));
145 id CYPoolRelease_(CYPool *pool, id object) {
148 else if (pool == NULL)
149 return [object autorelease];
151 pool->atexit(CYPoolRelease_);
156 template <typename Type_>
157 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
158 return (Type_) CYPoolRelease_(pool, (id) object);
161 /* Objective-C Strings {{{ */
162 CYUTF8String CYPoolUTF8String(CYPool &pool, JSContextRef context, NSString *value) {
163 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
164 char *string(new(pool) char[size + 1]);
165 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
166 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
167 return CYUTF8String(string, [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
170 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
171 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
172 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
177 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
178 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
182 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
185 // XXX: this definition scares me; is anyone using this?!
186 NSString *string([value description]);
188 return CYCopyJSString(context, string);
191 return CYCopyJSString(CYPoolUTF8String(pool, context, string));
195 NSString *CYCopyNSString(const CYUTF8String &value) {
197 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
199 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
203 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
205 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
208 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
212 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
213 return CYCopyNSString(context, CYJSString(context, value));
216 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
217 return CYPoolRelease(pool, CYCopyNSString(value));
220 NSString *CYCastNSString(CYPool *pool, SEL sel) {
221 const char *name(sel_getName(sel));
222 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
225 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
226 return CYPoolRelease(pool, CYCopyNSString(context, value));
229 CYUTF8String CYCastUTF8String(NSString *value) {
230 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
231 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
235 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
237 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
238 if (exception == NULL)
240 *exception = CYCastJSValue(context, error);
243 size_t CYGetIndex(NSString *value) {
244 return CYGetIndex(CYCastUTF8String(value));
247 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
248 return CYGetOffset(CYPoolCString(pool, context, value), index);
251 static JSClassRef ArrayInstance_;
252 static JSClassRef BooleanInstance_;
253 static JSClassRef FunctionInstance_;
254 static JSClassRef NumberInstance_;
255 static JSClassRef ObjectInstance_;
256 static JSClassRef StringInstance_;
258 static JSClassRef ObjectiveC_Classes_;
259 static JSClassRef ObjectiveC_Constants_;
260 static JSClassRef ObjectiveC_Protocols_;
263 static JSClassRef ObjectiveC_Image_Classes_;
264 static JSClassRef ObjectiveC_Images_;
268 static Class __NSMallocBlock__;
269 static Class NSCFBoolean_;
270 static Class NSCFType_;
271 static Class NSGenericDeallocHandler_;
273 static Class NSBoolNumber_;
276 static Class NSArray_;
277 static Class NSBlock_;
278 static Class NSDictionary_;
279 static Class NSNumber_;
280 static Class NSObject_;
281 static Class NSString_;
282 static Class NSZombie_;
283 static Class Object_;
285 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
287 JSValueRef Prototype::GetPrototype(JSContextRef context) const {
289 if (value_ == NSCFBoolean_)
291 if (value_ == NSBoolNumber_)
293 return CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
294 if (value_ == NSArray_)
295 return CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
296 if (value_ == NSBlock_)
297 return CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
298 if (value_ == NSNumber_)
299 return CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
300 if (value_ == NSDictionary_)
301 return CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
302 if (value_ == NSString_)
303 return CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
305 if (Class super = class_getSuperclass(value_))
306 return CYPrivate<Prototype>::Cache(context, super);
307 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
310 JSValueRef Constructor::GetPrototype(JSContextRef context) const {
311 if (Class super = class_getSuperclass(value_))
312 return CYPrivate<Constructor>::Cache(context, super);
313 return CYGetCachedObject(context, CYJSString("Constructor_prototype"));
316 bool CYIsKindOfClass(id object, Class _class) {
317 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
323 JSValueRef Instance::GetPrototype(JSContextRef context) const {
324 return CYPrivate<Prototype>::Cache(context, object_getClass(value_));
327 JSClassRef Instance::GetClass(id object, Flags flags) {
328 return CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance::Class_;
331 Instance::Instance(id value, Flags flags) :
336 /*else if ([value retainCount] == NSUInteger(-1))
337 flags_ |= Instance::Permanent;*/
339 value_ = [value_ retain];
342 Instance::~Instance() {
347 struct Message_privateData :
350 static JSClassRef Class_;
354 Message_privateData(SEL sel, const char *type, IMP value) :
355 cy::Functor(reinterpret_cast<void (*)()>(value), type),
360 static JSObjectRef Make(JSContextRef context, SEL sel, const char *type, IMP value);
363 JSClassRef Message_privateData::Class_;
365 JSObjectRef CYMakeInstance(JSContextRef context, id object, Instance::Flags flags = Instance::None) {
366 _assert(object != nil);
369 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
371 if (weak != NULL && &JSWeakObjectMapGet != NULL)
372 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
376 JSObjectRef instance;
377 if (CYIsClass(object) && !class_isMetaClass(object))
378 instance = CYPrivate<Constructor>::Cache(context, object);
380 instance = Instance::Make(context, object, flags);
383 if (weak != NULL && &JSWeakObjectMapSet != NULL)
384 JSWeakObjectMapSet(context, weak, object, instance);
390 @interface NSMethodSignature (Cycript)
391 - (NSString *) _typeString;
394 @interface NSObject (Cycript)
396 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
397 - (JSType) cy$JSType;
399 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
400 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
402 - (bool) cy$hasProperty:(NSString *)name;
403 - (NSObject *) cy$getProperty:(NSString *)name;
404 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
405 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
406 - (bool) cy$deleteProperty:(NSString *)name;
407 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
409 + (bool) cy$hasImplicitProperties;
415 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
418 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
419 _assert(value != nil);
421 Class _class(object_getClass(value));
423 if (class_isMetaClass(_class)) {
424 const char *name(class_getName(value));
425 if (class_isMetaClass(value))
426 return [NSString stringWithFormat:@"object_getClass(%s)", name];
428 return [NSString stringWithUTF8String:name];
431 if (_class == NSZombie_)
432 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
434 SEL sel(@selector(cy$toCYON:inSet:));
436 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
437 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
438 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
439 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
440 return [value cy$toCYON:objective inSet:objects];
442 return [NSString stringWithFormat:@"%@", value];
445 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
447 return CYCastNSCYON(value, objective, *objects);
449 std::set<void *> objects;
450 return CYCastNSCYON(value, objective, objects);
454 struct PropertyAttributes {
459 const char *variable;
472 PropertyAttributes(objc_property_t property) :
484 name = property_getName(property);
485 const char *attributes(property_getAttributes(property));
487 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
488 if ((next = strchr(token, ',')) != NULL)
491 case 'R': readonly = true; break;
492 case 'C': copy = true; break;
493 case '&': retain = true; break;
494 case 'N': nonatomic = true; break;
495 case 'G': getter_ = token + 1; break;
496 case 'S': setter_ = token + 1; break;
497 case 'V': variable = token + 1; break;
501 /*if (variable == NULL) {
502 variable = property_getName(property);
503 size_t size(strlen(variable));
504 char *name(new(pool_) char[size + 2]);
506 memcpy(name + 1, variable, size);
507 name[size + 1] = '\0';
512 const char *Getter() {
514 getter_ = pool_.strdup(name);
518 const char *Setter() {
519 if (setter_ == NULL && !readonly) {
520 size_t length(strlen(name));
522 char *temp(new(pool_) char[length + 5]);
528 temp[3] = toupper(name[0]);
529 memcpy(temp + 4, name + 1, length - 1);
532 temp[length + 3] = ':';
533 temp[length + 4] = '\0';
542 @interface CYWebUndefined : NSObject {
545 + (CYWebUndefined *) undefined;
549 @implementation CYWebUndefined
551 + (CYWebUndefined *) undefined {
552 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
558 #define WebUndefined CYWebUndefined
560 /* Bridge: CYJSObject {{{ */
561 @interface CYJSObject : NSMutableDictionary {
563 JSGlobalContextRef context_;
566 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
568 - (NSUInteger) count;
569 - (id) objectForKey:(id)key;
570 - (NSEnumerator *) keyEnumerator;
571 - (void) setObject:(id)object forKey:(id)key;
572 - (void) removeObjectForKey:(id)key;
576 /* Bridge: CYJSArray {{{ */
577 @interface CYJSArray : NSMutableArray {
579 JSGlobalContextRef context_;
582 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
584 - (NSUInteger) count;
585 - (id) objectAtIndex:(NSUInteger)index;
587 - (void) addObject:(id)anObject;
588 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
589 - (void) removeLastObject;
590 - (void) removeObjectAtIndex:(NSUInteger)index;
591 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
596 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
597 return JSValueIsObjectOfClass(context, value, Instance::Class_) || JSValueIsObjectOfClass(context, value, FunctionInstance_) || JSValueIsObjectOfClass(context, value, CYPrivate<Constructor>::Class_);
600 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
601 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
605 struct CYBlockDescriptor {
607 BlockDescriptor1 one_;
608 BlockDescriptor2 two_;
609 BlockDescriptor3 three_;
612 Closure_privateData *internal_;
615 void CYDisposeBlock(BlockLiteral *literal) {
616 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
619 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
620 JSObjectRef _this(CYCastJSObject(context, values[0]));
621 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
624 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
625 _assert(__NSMallocBlock__ != Nil);
626 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
628 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
629 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
631 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockAdapter_);
632 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->value_);
634 literal->isa = __NSMallocBlock__;
635 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
636 literal->reserved = 0;
637 literal->descriptor = descriptor;
639 descriptor->d_.one_.size = sizeof(descriptor->d_);
640 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
641 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
643 return reinterpret_cast<NSBlock *>(literal);
647 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
648 if (CYJSValueIsNSObject(context, object)) {
649 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
650 return internal->value_;
653 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
654 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
655 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
658 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
659 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
663 @interface NSBoolNumber : NSNumber {
668 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
672 switch (JSType type = JSValueGetType(context, value)) {
673 case kJSTypeUndefined:
674 object = [WebUndefined undefined];
684 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
687 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
693 object = CYCopyNSNumber(context, value);
698 object = CYCopyNSString(context, value);
703 // XXX: this might could be more efficient
704 object = CYCastNSObject(pool, context, (JSObjectRef) value);
709 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
716 return CYPoolRelease(pool, object);
718 return [object retain];
721 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
722 return CYNSObject(pool, context, value, true);
725 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
726 return CYNSObject(&pool, context, value, false);
729 /* Bridge: NSArray {{{ */
730 @implementation NSArray (Cycript)
733 return [[self mutableCopy] autorelease];
736 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
737 _oassert(objects.insert(self).second);
739 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
740 [json appendString:@"@["];
744 for (id object in self) {
746 for (size_t index(0), count([self count]); index != count; ++index) {
747 id object([self objectAtIndex:index]);
750 [json appendString:@","];
753 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
754 [json appendString:CYCastNSCYON(object, true, objects)];
756 [json appendString:@","];
761 [json appendString:@"]"];
765 - (bool) cy$hasProperty:(NSString *)name {
766 if ([name isEqualToString:@"length"])
769 size_t index(CYGetIndex(name));
770 if (index == _not(size_t) || index >= [self count])
771 return [super cy$hasProperty:name];
776 - (NSObject *) cy$getProperty:(NSString *)name {
777 size_t index(CYGetIndex(name));
778 if (index == _not(size_t) || index >= [self count])
779 return [super cy$getProperty:name];
781 return [self objectAtIndex:index];
784 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
786 if ([name isEqualToString:@"length"])
787 return CYCastJSValue(context, [self count]);
790 return [super cy$getProperty:name inContext:context];
793 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
794 [super cy$getPropertyNames:names inContext:context];
796 for (size_t index(0), count([self count]); index != count; ++index) {
797 id object([self objectAtIndex:index]);
798 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
800 sprintf(name, "%zu", index);
801 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
806 + (bool) cy$hasImplicitProperties {
812 /* Bridge: NSBlock {{{ */
814 @interface NSBlock : NSObject
818 static const char *CYBlockEncoding(NSBlock *self);
819 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature);
821 @implementation NSBlock (Cycript)
823 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
827 if (!CYBlockSignature(pool, self, type.signature))
828 return [super cy$toCYON:objective inSet:objects];
829 _oassert(objects.insert(self).second);
831 CYType *typed((new(pool) CYTypeExpression(CYDecodeType(pool, &type)))->typed_);
832 CYTypeModifier *&modifier(CYGetLast(typed->modifier_));
833 CYTypeBlockWith *with(dynamic_cast<CYTypeBlockWith *>(modifier));
834 _assert(with != NULL);
835 CYObjCBlock *block(new(pool) CYObjCBlock(typed, with->parameters_, NULL));
838 std::ostringstream str;
840 CYOutput out(*str.rdbuf(), options);
841 block->Output(out, CYNoFlags);
843 std::string value(str.str());
844 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
850 /* Bridge: NSBoolNumber {{{ */
852 @implementation NSBoolNumber (Cycript)
854 - (JSType) cy$JSType {
855 return kJSTypeBoolean;
858 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
859 NSString *value([self boolValue] ? @"true" : @"false");
860 return objective ? value : [NSString stringWithFormat:@"@%@", value];
863 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
864 return CYCastJSValue(context, (bool) [self boolValue]);
870 /* Bridge: NSDictionary {{{ */
871 @implementation NSDictionary (Cycript)
874 return [[self mutableCopy] autorelease];
877 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
878 _oassert(objects.insert(self).second);
880 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
881 [json appendString:@"@{"];
885 for (NSObject *key in self) {
887 NSEnumerator *keys([self keyEnumerator]);
888 while (NSObject *key = [keys nextObject]) {
891 [json appendString:@","];
894 [json appendString:CYCastNSCYON(key, true, objects)];
895 [json appendString:@":"];
896 NSObject *object([self objectForKey:key]);
897 [json appendString:CYCastNSCYON(object, true, objects)];
900 [json appendString:@"}"];
904 - (bool) cy$hasProperty:(NSString *)name {
905 return [self objectForKey:name] != nil;
908 - (NSObject *) cy$getProperty:(NSString *)name {
909 return [self objectForKey:name];
912 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
913 [super cy$getPropertyNames:names inContext:context];
916 for (NSObject *key in self) {
918 NSEnumerator *keys([self keyEnumerator]);
919 while (NSObject *key = [keys nextObject]) {
921 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
925 + (bool) cy$hasImplicitProperties {
931 /* Bridge: NSMutableArray {{{ */
932 @implementation NSMutableArray (Cycript)
934 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
935 if ([name isEqualToString:@"length"]) {
936 // XXX: is this not intelligent?
937 NSNumber *number(reinterpret_cast<NSNumber *>(value));
938 NSUInteger size([number unsignedIntegerValue]);
939 NSUInteger count([self count]);
941 [self removeObjectsInRange:NSMakeRange(size, count - size)];
942 else if (size != count) {
943 WebUndefined *undefined([WebUndefined undefined]);
944 for (size_t i(count); i != size; ++i)
945 [self addObject:undefined];
950 size_t index(CYGetIndex(name));
951 if (index == _not(size_t))
952 return [super cy$setProperty:name to:value];
954 id object(value ?: [NSNull null]);
956 size_t count([self count]);
958 [self replaceObjectAtIndex:index withObject:object];
960 if (index != count) {
961 WebUndefined *undefined([WebUndefined undefined]);
962 for (size_t i(count); i != index; ++i)
963 [self addObject:undefined];
966 [self addObject:object];
972 - (bool) cy$deleteProperty:(NSString *)name {
973 size_t index(CYGetIndex(name));
974 if (index == _not(size_t) || index >= [self count])
975 return [super cy$deleteProperty:name];
976 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
982 /* Bridge: NSMutableDictionary {{{ */
983 @implementation NSMutableDictionary (Cycript)
985 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
986 [self setObject:(value ?: [NSNull null]) forKey:name];
990 - (bool) cy$deleteProperty:(NSString *)name {
991 if ([self objectForKey:name] == nil)
994 [self removeObjectForKey:name];
1001 /* Bridge: NSNumber {{{ */
1002 @implementation NSNumber (Cycript)
1004 - (JSType) cy$JSType {
1006 // XXX: this just seems stupid
1007 if ([self class] == NSCFBoolean_)
1008 return kJSTypeBoolean;
1010 return kJSTypeNumber;
1013 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1014 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1015 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1018 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1019 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1020 } CYObjectiveCatch }
1024 /* Bridge: NSNull {{{ */
1025 @implementation NSNull (Cycript)
1027 - (JSType) cy$JSType {
1031 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1032 NSString *value(@"null");
1033 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1036 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1037 return CYJSNull(context);
1038 } CYObjectiveCatch }
1042 /* Bridge: NSObject {{{ */
1043 @implementation NSObject (Cycript)
1049 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1050 return [self cy$valueOfInContext:context];
1053 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1055 } CYObjectiveCatch }
1057 - (JSType) cy$JSType {
1058 return kJSTypeObject;
1061 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1062 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1065 - (bool) cy$hasProperty:(NSString *)name {
1069 - (NSObject *) cy$getProperty:(NSString *)name {
1073 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1074 if (NSObject *value = [self cy$getProperty:name])
1075 return CYCastJSValue(context, value);
1077 } CYObjectiveCatch }
1079 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1083 - (bool) cy$deleteProperty:(NSString *)name {
1087 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1090 + (bool) cy$hasImplicitProperties {
1096 /* Bridge: NSOrderedSet {{{ */
1098 @implementation NSOrderedSet (Cycript)
1100 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1101 _oassert(objects.insert(self).second);
1103 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1104 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1105 [json appendString:CYCastNSCYON([self array], true, objects)];
1106 [json appendString:@"]]"];
1113 /* Bridge: NSProxy {{{ */
1114 @implementation NSProxy (Cycript)
1116 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1117 return [[self description] cy$toCYON:objective inSet:objects];
1122 /* Bridge: NSSet {{{ */
1123 @implementation NSSet (Cycript)
1125 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1126 _oassert(objects.insert(self).second);
1128 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1129 [json appendString:@"[NSSet setWithArray:"];
1130 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1131 [json appendString:@"]]"];
1137 /* Bridge: NSString {{{ */
1138 @implementation NSString (Cycript)
1141 return [[self copy] autorelease];
1144 - (JSType) cy$JSType {
1145 return kJSTypeString;
1148 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1149 std::ostringstream str;
1152 CYUTF8String string(CYCastUTF8String(self));
1153 CYStringify(str, string.data, string.size, CYStringifyModeNative);
1154 std::string value(str.str());
1155 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1158 - (bool) cy$hasProperty:(NSString *)name {
1159 size_t index(CYGetIndex(name));
1160 if (index == _not(size_t) || index >= [self length])
1161 return [super cy$hasProperty:name];
1166 - (NSObject *) cy$getProperty:(NSString *)name {
1167 size_t index(CYGetIndex(name));
1168 if (index == _not(size_t) || index >= [self length])
1169 return [super cy$getProperty:name];
1171 return [self substringWithRange:NSMakeRange(index, 1)];
1174 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1175 [super cy$getPropertyNames:names inContext:context];
1177 for (size_t index(0), length([self length]); index != length; ++index) {
1179 sprintf(name, "%zu", index);
1180 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1184 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1185 return CYCastJSValue(context, CYJSString(context, self));
1186 } CYObjectiveCatch }
1190 /* Bridge: WebUndefined {{{ */
1191 @implementation WebUndefined (Cycript)
1193 - (JSType) cy$JSType {
1194 return kJSTypeUndefined;
1197 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1198 NSString *value(@"undefined");
1199 return value; // XXX: maybe use the below code, adding @undefined?
1200 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1203 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1204 return CYJSUndefined(context);
1205 } CYObjectiveCatch }
1210 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1211 id self(CYCastNSObject(&pool, context, value));
1212 if (CYIsClass(self))
1213 return (Class) self;
1214 throw CYJSError(context, "got something that is not a Class");
1218 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1220 size_t size(JSPropertyNameArrayGetCount(names));
1221 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1222 for (size_t index(0); index != size; ++index)
1223 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1227 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) {
1229 return CYJSNull(context);
1230 return CYMakeInstance(context, value);
1233 @implementation CYJSObject
1235 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1236 if ((self = [super init]) != nil) {
1238 context_ = CYGetJSContext(context);
1239 JSGlobalContextRetain(context_);
1240 JSValueProtect(context_, object_);
1242 } CYObjectiveCatch }
1244 - (void) dealloc { CYObjectiveTry {
1245 JSValueUnprotect(context_, object_);
1246 JSGlobalContextRelease(context_);
1248 } CYObjectiveCatch }
1250 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1252 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1254 return [super cy$toCYON:objective inSet:objects];
1256 return [NSString stringWithUTF8String:cyon];
1257 } CYObjectiveCatch }
1259 - (NSUInteger) count { CYObjectiveTry {
1260 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1261 size_t size(JSPropertyNameArrayGetCount(names));
1262 JSPropertyNameArrayRelease(names);
1264 } CYObjectiveCatch }
1266 - (id) objectForKey:(id)key { CYObjectiveTry {
1267 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1268 if (JSValueIsUndefined(context, value))
1270 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1271 } CYObjectiveCatch }
1273 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1274 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1275 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1276 JSPropertyNameArrayRelease(names);
1278 } CYObjectiveCatch }
1280 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1281 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1282 } CYObjectiveCatch }
1284 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1285 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1286 } CYObjectiveCatch }
1290 @implementation CYJSArray
1292 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1294 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1295 } CYObjectiveCatch }
1297 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1298 if ((self = [super init]) != nil) {
1300 context_ = CYGetJSContext(context);
1301 JSGlobalContextRetain(context_);
1302 JSValueProtect(context_, object_);
1304 } CYObjectiveCatch }
1306 - (void) dealloc { CYObjectiveTry {
1307 JSValueUnprotect(context_, object_);
1308 JSGlobalContextRelease(context_);
1310 } CYObjectiveCatch }
1312 - (NSUInteger) count { CYObjectiveTry {
1313 return CYArrayLength(context, object_);
1314 } CYObjectiveCatch }
1316 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1317 size_t bounds([self count]);
1318 if (index >= bounds)
1319 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1320 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1321 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1322 } CYObjectiveCatch }
1324 - (void) addObject:(id)object { CYObjectiveTry {
1325 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1326 } CYObjectiveCatch }
1328 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1329 size_t bounds([self count] + 1);
1330 if (index >= bounds)
1331 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1332 JSValueRef arguments[3];
1333 arguments[0] = CYCastJSValue(context, index);
1334 arguments[1] = CYCastJSValue(context, 0);
1335 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1336 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1337 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1338 } CYObjectiveCatch }
1340 - (void) removeLastObject { CYObjectiveTry {
1341 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1342 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1343 } CYObjectiveCatch }
1345 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1346 size_t bounds([self count]);
1347 if (index >= bounds)
1348 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1349 JSValueRef arguments[2];
1350 arguments[0] = CYCastJSValue(context, index);
1351 arguments[1] = CYCastJSValue(context, 1);
1352 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1353 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1354 } CYObjectiveCatch }
1356 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1357 size_t bounds([self count]);
1358 if (index >= bounds)
1359 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1360 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1361 } CYObjectiveCatch }
1365 // XXX: inherit from or replace with CYJSObject
1366 @interface CYInternal : NSObject {
1367 JSGlobalContextRef context_;
1368 JSObjectRef object_;
1373 @implementation CYInternal
1375 - (void) dealloc { CYObjectiveTry {
1376 JSValueUnprotect(context_, object_);
1377 JSGlobalContextRelease(context_);
1379 } CYObjectiveCatch }
1381 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1382 if ((self = [super init]) != nil) {
1383 context_ = CYGetJSContext(context);
1384 JSGlobalContextRetain(context_);
1386 } CYObjectiveCatch }
1388 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1389 if (object_ == NULL)
1392 return JSObjectHasProperty(context, object_, name);
1395 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1396 if (object_ == NULL)
1399 return CYGetProperty(context, object_, name);
1402 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1403 @synchronized (self) {
1404 if (object_ == NULL) {
1405 object_ = JSObjectMake(context, NULL, NULL);
1406 JSValueProtect(context, object_);
1410 CYSetProperty(context, object_, name, value);
1413 + (CYInternal *) get:(id)object {
1415 if (&objc_getAssociatedObject == NULL)
1418 @synchronized (object) {
1419 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1427 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1429 if (&objc_getAssociatedObject == NULL)
1432 @synchronized (object) {
1433 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1436 if (&objc_setAssociatedObject == NULL)
1439 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1440 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1450 static JSValueRef CYCastJSValue(JSContextRef context, SEL sel) {
1452 return CYJSNull(context);
1453 return CYPrivate<Selector_privateData>::Make(context, sel);
1456 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1457 if (JSValueIsObjectOfClass(context, value, CYPrivate<Selector_privateData>::Class_)) {
1458 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1459 return reinterpret_cast<SEL>(internal->value_);
1462 return sel_registerName(CYPoolCString(pool, context, value));
1466 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1467 return (void *) [[NSAutoreleasePool alloc] init];
1468 } CYSadCatch(NULL) }
1470 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1471 return [(NSAutoreleasePool *) handle release];
1474 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1475 CYCallFunction(pool, context, cif, function, value, values);
1478 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, const sig::Signature *signature) {
1480 if (JSValueIsNull(context, value))
1482 JSObjectRef object(CYCastJSObject(context, value));
1484 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1485 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_;
1487 if (JSValueIsObjectOfClass(context, object, Instance::Class_)) {
1488 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_ == nil);
1492 _assert(JSObjectIsFunction(context, object));
1494 _assert(signature != NULL);
1495 _assert(signature->count != 0);
1497 sig::Signature modified;
1498 modified.count = signature->count + 1;
1499 modified.elements = new(pool) sig::Element[modified.count];
1501 modified.elements[0] = signature->elements[0];
1502 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1504 modified.elements[1].name = NULL;
1505 modified.elements[1].type = new(pool) sig::Object();
1506 modified.elements[1].offset = _not(size_t);
1508 return CYMakeBlock(context, object, modified);
1516 void Block::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1517 // XXX: this function actually needs to handle null pools as it is an autorelease
1518 _assert(pool != NULL);
1519 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &signature);
1522 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1523 void Object::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1524 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1527 void Meta::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1528 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1531 void Selector::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1532 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1535 JSValueRef Object::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1536 NSObject *value(*reinterpret_cast<NSObject **>(data));
1538 return CYJSNull(context);
1539 JSObjectRef object(CYMakeInstance(context, value));
1542 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1544 if (internal->IsUninitialized()) {
1545 internal->flags_ &= ~Instance::Uninitialized;
1546 if (internal->value_ == nil)
1547 internal->value_ = value;
1549 _assert(internal->value_ == value);
1558 JSValueRef Meta::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1559 if (Class value = *reinterpret_cast<Class *>(data))
1560 return CYMakeInstance(context, value, Instance::Permanent);
1561 return CYJSNull(context);
1564 JSValueRef Selector::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1565 return CYCastJSValue(context, *reinterpret_cast<SEL *>(data));
1568 JSValueRef Block::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1569 return CYCastJSValue(context, *reinterpret_cast<NSObject **>(data));
1574 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1575 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1579 method_getReturnType(method, type, sizeof(type));
1584 // XXX: possibly use a more "awesome" check?
1588 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1589 JSObjectRef _this(CYCastJSObject(context, values[0]));
1590 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1593 JSObjectRef Message_privateData::Make(JSContextRef context, SEL sel, const char *type, IMP value) {
1594 Message_privateData *internal(new Message_privateData(sel, type, value));
1595 return JSObjectMake(context, Message_privateData::Class_, internal);
1598 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1599 JSObjectRef function(CYCastJSObject(context, value));
1601 sig::Signature signature;
1602 sig::Parse(pool, &signature, encoding, &Structor_);
1603 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1604 // XXX: see notes in Library.cpp about needing to leak
1605 return reinterpret_cast<IMP>(internal->value_);
1608 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1609 auto internal(CYPrivate<Messages>::Get(context, object));
1610 Class _class(internal->GetClass());
1613 const char *name(CYPoolCString(pool, context, property));
1615 if (SEL sel = sel_getUid(name))
1616 if (class_getInstanceMethod(_class, sel) != NULL)
1622 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1623 auto internal(CYPrivate<Messages>::Get(context, object));
1624 Class _class(internal->GetClass());
1627 const char *name(CYPoolCString(pool, context, property));
1629 if (SEL sel = sel_getUid(name))
1630 if (objc_method *method = class_getInstanceMethod(_class, sel))
1631 return Message_privateData::Make(context, sel, method_getTypeEncoding(method), method_getImplementation(method));
1636 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1637 auto internal(CYPrivate<Messages>::Get(context, object));
1638 Class _class(internal->GetClass());
1641 const char *name(CYPoolCString(pool, context, property));
1642 SEL sel(sel_registerName(name));
1647 if (JSValueIsObjectOfClass(context, value, Message_privateData::Class_)) {
1648 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1649 type = sig::Unparse(pool, &message->signature_);
1650 imp = reinterpret_cast<IMP>(message->value_);
1651 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1652 type = method_getTypeEncoding(method);
1653 imp = CYMakeMessage(context, value, type);
1654 } else return false;
1656 objc_method *method(NULL);
1658 objc_method **methods(class_copyMethodList(_class, &size));
1659 pool.atexit(free, methods);
1661 for (size_t i(0); i != size; ++i)
1662 if (sel_isEqual(method_getName(methods[i]), sel)) {
1663 method = methods[i];
1668 method_setImplementation(method, imp);
1670 class_addMethod(_class, sel, imp, type);
1675 static JSValueRef Messages_complete_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1677 if (!CYCastBool(context, arguments[1]))
1678 return CYObjectMakeArray(context, 0, NULL);
1682 _assert(count == 1);
1684 CYUTF8String prefix(CYPoolUTF8String(pool, context, CYJSString(context, arguments[0])));
1686 auto internal(CYPrivate<Messages>::Get(context, _this));
1687 Class _class(internal->GetClass());
1690 objc_method **data(class_copyMethodList(_class, &size));
1691 pool.atexit(free, data);
1693 JSObjectRef array(NULL); {
1694 CYArrayBuilder<1024> values(context, array);
1696 for (size_t i(0); i != size; ++i) {
1697 CYUTF8String name(sel_getName(method_getName(data[i])));
1698 if (CYStartsWith(name, prefix))
1699 values(CYCastJSValue(context, CYJSString(name)));
1704 static bool CYHasImplicitProperties(JSContextRef context, Class _class) {
1705 if (!CYCastBool(context, CYGetCachedValue(context, CYJSString("cydget"))))
1706 if (class_getProperty(NSObject_, "description") != NULL)
1708 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1709 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1711 return [_class cy$hasImplicitProperties];
1714 static objc_property_t CYFindProperty(CYPool &pool, Class _class, const char *name) {
1717 if (objc_property_t property = class_getProperty(_class, name))
1721 /* // XXX: I don't think any of this is required
1723 Protocol **protocols(class_copyProtocolList(_class, &count));
1724 // XXX: just implement a scope guard already :/
1725 pool.atexit(free, protocols);
1727 for (unsigned int i(0); i != count; ++i)
1728 if (objc_property_t property = protocol_getProperty(protocols[i], name, true, true))
1731 return CYFindProperty(pool, class_getSuperclass(_class), name); */
1734 static JSValueRef Constructor_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1735 auto internal(CYPrivate<Constructor>::Get(context, object));
1736 return CYPrivate<Interior>::Make(context, internal->value_, context, object);
1739 static bool Constructor_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1740 auto internal(CYPrivate<Constructor>::Get(context, object));
1741 Class _class(object_getClass(internal->value_));
1742 if (!CYHasImplicitProperties(context, _class))
1745 if (SEL sel = sel_getUid(CYPoolCString(pool, context, property)))
1746 if (CYImplements(internal->value_, _class, sel, true))
1751 static JSValueRef Constructor_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1752 auto internal(CYPrivate<Constructor>::Get(context, object));
1753 Class _class(object_getClass(internal->value_));
1754 if (!CYHasImplicitProperties(context, _class))
1757 if (SEL sel = sel_getUid(CYPoolCString(pool, context, property)))
1758 if (CYImplements(internal->value_, _class, sel, true))
1759 return CYSendMessage(pool, context, internal->value_, NULL, sel, 0, NULL, false);
1763 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1764 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1765 id self(internal->value_);
1767 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1771 NSString *name(CYCastNSString(&pool, context, property));
1773 if (CYInternal *internal = [CYInternal get:self])
1774 if ([internal hasProperty:property inContext:context])
1777 Class _class(object_getClass(self));
1780 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1781 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1782 if ([self cy$hasProperty:name])
1784 } CYPoolCatch(false)
1786 const char *string(CYPoolCString(pool, context, name));
1788 if (CYFindProperty(pool, _class, string) != NULL)
1791 if (CYHasImplicitProperties(context, _class))
1792 if (SEL sel = sel_getUid(string))
1793 if (CYImplements(self, _class, sel, true))
1799 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1800 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1801 id self(internal->value_);
1803 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1804 return CYPrivate<Interior>::Make(context, self, context, object);
1807 NSString *name(CYCastNSString(&pool, context, property));
1809 if (CYInternal *internal = [CYInternal get:self])
1810 if (JSValueRef value = [internal getProperty:property inContext:context])
1814 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1818 const char *string(CYPoolCString(pool, context, name));
1819 Class _class(object_getClass(self));
1821 if (objc_property_t property = CYFindProperty(pool, _class, string)) {
1822 PropertyAttributes attributes(property);
1823 SEL sel(sel_registerName(attributes.Getter()));
1824 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1827 if (CYHasImplicitProperties(context, _class))
1828 if (SEL sel = sel_getUid(string))
1829 if (CYImplements(self, _class, sel, true))
1830 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1835 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1836 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1837 id self(internal->value_);
1841 NSString *name(CYCastNSString(&pool, context, property));
1842 NSObject *data(CYCastNSObject(&pool, context, value));
1845 if ([self cy$setProperty:name to:data])
1847 } CYPoolCatch(false)
1849 const char *string(CYPoolCString(pool, context, name));
1850 Class _class(object_getClass(self));
1852 if (objc_property_t property = CYFindProperty(pool, _class, string)) {
1853 PropertyAttributes attributes(property);
1854 if (const char *setter = attributes.Setter()) {
1855 SEL sel(sel_registerName(setter));
1856 JSValueRef arguments[1] = {value};
1857 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1862 size_t length(strlen(string));
1864 char set[length + 5];
1870 if (string[0] != '\0') {
1871 set[3] = toupper(string[0]);
1872 memcpy(set + 4, string + 1, length - 1);
1875 set[length + 3] = ':';
1876 set[length + 4] = '\0';
1878 if (SEL sel = sel_getUid(set))
1879 if (CYImplements(self, _class, sel)) {
1880 JSValueRef arguments[1] = {value};
1881 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1885 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1886 [internal setProperty:property toValue:value inContext:context];
1893 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1894 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1895 id self(internal->value_);
1898 NSString *name(CYCastNSString(NULL, context, property));
1899 return [self cy$deleteProperty:name];
1900 } CYPoolCatch(false)
1901 } CYCatch(false) return /*XXX*/ false; }
1903 static void CYForEachProperty(CYPool &pool, Class _class, const Functor<void (objc_method *, const char *)> &code) {
1904 for (; _class != Nil; _class = class_getSuperclass(_class)) {
1906 objc_method **data(class_copyMethodList(_class, &size));
1907 pool.atexit(free, data);
1909 for (size_t i(0); i != size; ++i) {
1910 objc_method *method(data[i]);
1912 const char *name(sel_getName(method_getName(method)));
1913 if (strchr(name, ':') != NULL)
1921 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1922 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1923 id self(internal->value_);
1926 Class _class(object_getClass(self));
1928 for (Class current(_class); current != Nil; current = class_getSuperclass(current)) {
1930 objc_property_t *data(class_copyPropertyList(current, &size));
1931 pool.atexit(free, data);
1933 for (size_t i(0); i != size; ++i)
1934 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1937 if (CYHasImplicitProperties(context, _class))
1938 CYForEachProperty(pool, _class, fun([&](objc_method *method, const char *name) {
1939 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1943 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1944 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1945 [self cy$getPropertyNames:names inContext:context];
1949 static JSValueRef Instance_complete_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1950 if (!CYJSValueIsNSObject(context, _this))
1951 return CYObjectMakeArray(context, 0, NULL);
1953 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
1954 id self(internal->value_);
1956 _assert(count == 1 || count == 2);
1958 Class _class(object_getClass(self));
1960 CYUTF8String prefix(CYPoolUTF8String(pool, context, CYJSString(context, arguments[0])));
1962 JSObjectRef array(NULL); {
1963 CYArrayBuilder<1024> values(context, array);
1965 CYForEachProperty(pool, _class, fun([&](objc_method *method, const char *name) {
1966 if (!CYStartsWith(name, prefix))
1968 const char *type(method_getTypeEncoding(method));
1969 if (type == NULL || *type == '\0' || *type == 'v')
1971 if (class_getProperty(_class, name) != NULL)
1973 values(CYCastJSValue(context, CYJSString(pool.strcat(name, "()", NULL))));
1978 static JSObjectRef Constructor_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1979 auto internal(CYPrivate<Constructor>::Get(context, object));
1980 JSObjectRef value(CYMakeInstance(context, [internal->value_ alloc], Instance::Uninitialized));
1984 static const char *CYBlockEncoding(NSBlock *self) {
1985 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1986 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1988 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1989 descriptor += sizeof(BlockDescriptor1);
1990 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1991 descriptor += sizeof(BlockDescriptor2);
1992 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1993 return descriptor3->signature;
1996 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature) {
1997 const char *encoding(CYBlockEncoding(self));
1998 if (encoding == NULL)
2001 sig::Parse(pool, &signature, encoding, &Structor_);
2002 _assert(signature.count >= 2);
2004 _assert(dynamic_cast<sig::Object *>(signature.elements[1].type) != NULL);
2005 signature.elements[1] = signature.elements[0];
2007 ++signature.elements;
2013 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2014 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2015 id self(internal->value_);
2017 if (const char *encoding = CYBlockEncoding(self)) {
2023 sig::Signature signature;
2024 sig::Parse(pool, &signature, encoding, &Structor_);
2027 sig::sig_ffi_cif(pool, 0, signature, &cif);
2029 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
2030 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
2031 return CYCallFunction(pool, context, 1, setup, count, arguments, false, false, signature, &cif, function);
2035 CYThrow("NSBlock without signature field passed arguments");
2039 } CYPoolCatch(NULL);
2044 static bool Constructor_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
2045 auto internal(CYPrivate<Constructor>::Get(context, constructor));
2046 Class _class(internal->value_);
2048 if (CYJSValueIsNSObject(context, instance)) {
2049 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2050 // XXX: this isn't always safe
2051 return [linternal->value_ isKindOfClass:_class];
2057 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2059 throw CYJSError(context, "incorrect number of arguments to Instance");
2061 id value(CYCastNSObject(&pool, context, arguments[0]));
2063 value = [NSNull null];
2064 return CYCastJSValue(context, [value cy$box]);
2067 static bool Interior_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2068 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2071 id self(internal->value_);
2072 const char *name(CYPoolCString(pool, context, property));
2074 if (object_getInstanceVariable(self, name, NULL) != NULL)
2080 static void CYBitField(CYPool &pool, unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2081 length = CYCastDouble(encoding + 1);
2085 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2086 pool.atexit(free, ivars);
2088 for (size_t i(0); i != size; ++i)
2089 if (ivars[i] == ivar)
2091 else if (ivar_getOffset(ivars[i]) == offset) {
2092 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2093 _assert(encoding != NULL);
2094 _assert(encoding[0] == 'b');
2095 shift += CYCastDouble(encoding + 1);
2099 static JSValueRef Interior_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2100 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2103 id self(internal->value_);
2104 const char *name(CYPoolCString(pool, context, property));
2106 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2107 ptrdiff_t offset(ivar_getOffset(ivar));
2108 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2110 const char *encoding(ivar_getTypeEncoding(ivar));
2111 _assert(encoding != NULL);
2112 _assert(encoding[0] != '\0');
2113 if (encoding[0] == 'b') {
2114 unsigned length, shift;
2115 CYBitField(pool, length, shift, self, ivar, encoding, offset);
2116 _assert(shift + length <= sizeof(uintptr_t) * 8);
2117 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2118 uintptr_t mask((1 << length) - 1);
2119 return CYCastJSValue(context, (field >> shift) & mask);
2121 #if defined(__APPLE__) && defined(__LP64__)
2122 // XXX: maybe do even more verifications here
2123 if (strcmp(name, "isa") == 0)
2124 return CYCastJSValue(context, object_getClass(self));
2127 auto type(new(pool) Type_privateData(encoding));
2128 return type->type_->FromFFI(context, type->GetFFI(), data);
2135 static bool Interior_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2136 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2139 id self(internal->value_);
2140 const char *name(CYPoolCString(pool, context, property));
2142 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2143 ptrdiff_t offset(ivar_getOffset(ivar));
2144 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2146 const char *encoding(ivar_getTypeEncoding(ivar));
2147 _assert(encoding != NULL);
2148 if (encoding[0] == 'b') {
2149 unsigned length, shift;
2150 CYBitField(pool, length, shift, self, ivar, encoding, offset);
2151 _assert(shift + length <= sizeof(uintptr_t) * 8);
2152 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2153 uintptr_t mask((1 << length) - 1);
2154 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2156 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2157 type->type_->PoolFFI(&pool, context, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2165 static void Interior_getPropertyNames_(CYPool &pool, Class _class, JSPropertyNameAccumulatorRef names) {
2166 if (Class super = class_getSuperclass(_class))
2167 Interior_getPropertyNames_(pool, super, names);
2170 objc_ivar **data(class_copyIvarList(_class, &size));
2171 pool.atexit(free, data);
2173 for (size_t i(0); i != size; ++i)
2174 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2177 static void Interior_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2178 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2181 id self(internal->value_);
2182 Class _class(object_getClass(self));
2184 Interior_getPropertyNames_(pool, _class, names);
2187 static JSValueRef Interior_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2188 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2189 return internal->owner_;
2192 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2194 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2197 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2199 NSString *name(CYCastNSString(&pool, context, property));
2200 if (Class _class = NSClassFromString(name))
2201 return CYMakeInstance(context, _class, Instance::Permanent);
2205 static Class *CYCopyClassList(size_t &size) {
2206 size = objc_getClassList(NULL, 0);
2207 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2210 size_t writ(objc_getClassList(data, size));
2216 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2227 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2231 if (Class *data = CYCopyClassList(size)) {
2232 pool.atexit(free, data);
2233 for (size_t i(0); i != size; ++i)
2234 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2239 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2240 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2243 const char *name(CYPoolCString(pool, context, property));
2246 const char **data(objc_copyClassNamesForImage(internal, &size));
2247 pool.atexit(free, data);
2250 for (size_t i(0); i != size; ++i)
2251 if (strcmp(name, data[i]) == 0) {
2252 if (Class _class = objc_getClass(name))
2253 return CYMakeInstance(context, _class, Instance::Permanent);
2261 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2262 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2266 const char **data(objc_copyClassNamesForImage(internal, &size));
2267 pool.atexit(free, data);
2269 for (size_t i(0); i != size; ++i)
2270 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2273 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2275 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2278 const char **data(objc_copyImageNames(&size));
2279 pool.atexit(free, data);
2281 for (size_t i(0); i != size; ++i)
2282 if (name == data[i]) {
2283 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2284 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2291 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2295 const char **data(objc_copyImageNames(&size));
2296 pool.atexit(free, data);
2298 for (size_t i(0); i != size; ++i)
2299 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2303 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2305 const char *name(CYPoolCString(pool, context, property));
2306 if (Protocol *protocol = objc_getProtocol(name))
2307 return CYMakeInstance(context, protocol, Instance::Permanent);
2311 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2315 Protocol **data(objc_copyProtocolList(&size));
2316 pool.atexit(free, data);
2318 for (size_t i(0); i != size; ++i)
2319 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2322 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2324 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2326 return CYJSNull(context);
2330 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2331 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2335 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2336 *data = reinterpret_cast<void *>(address);
2337 return KERN_SUCCESS;
2341 std::set<Class> query_;
2342 JSContextRef context_;
2343 JSObjectRef results_;
2346 struct CYObjectStruct {
2350 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2351 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2352 JSContextRef context(choice->context_);
2354 for (unsigned i(0); i != count; ++i) {
2355 vm_range_t &range(ranges[i]);
2356 void *data(reinterpret_cast<void *>(range.address));
2357 size_t size(range.size);
2359 if (size < sizeof(CYObjectStruct))
2362 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2363 #if defined(__APPLE__) && defined(__LP64__)
2364 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2366 Class isa(reinterpret_cast<Class>(pointers[0]));
2369 std::set<Class>::const_iterator result(choice->query_.find(isa));
2370 if (result == choice->query_.end())
2373 size_t needed(class_getInstanceSize(*result));
2374 // XXX: if (size < needed)
2376 size_t boundary(496);
2380 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2382 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2386 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2388 throw CYJSError(context, "choose() takes a class argument");
2390 CYGarbageCollect(context);
2393 id _class(CYCastNSObject(&pool, context, arguments[0]));
2395 vm_address_t *zones(NULL);
2397 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2398 _assert(error == KERN_SUCCESS);
2400 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2401 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2404 choice.context_ = context;
2405 choice.results_ = results;
2408 Class *classes(CYCopyClassList(number));
2409 _assert(classes != NULL);
2410 pool.atexit(free, classes);
2412 for (size_t i(0); i != number; ++i)
2413 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2414 if (current == _class) {
2415 choice.query_.insert(classes[i]);
2419 for (unsigned i(0); i != size; ++i) {
2420 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2421 if (zone == NULL || zone->introspect == NULL)
2424 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2432 #if defined(__i386__) || defined(__x86_64__)
2433 #define OBJC_MAX_STRUCT_BY_VALUE 8
2434 static int struct_forward_array[] = {
2435 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2436 #elif defined(__arm__)
2437 #define OBJC_MAX_STRUCT_BY_VALUE 1
2438 static int struct_forward_array[] = {
2440 #elif defined(__arm64__)
2443 #error missing objc-runtime-info
2447 static bool stret(ffi_type *ffi_type) {
2448 return ffi_type->type == FFI_TYPE_STRUCT && (
2449 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2450 struct_forward_array[ffi_type->size] != 0
2458 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2462 _class = object_getClass(self);
2466 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2467 imp = method_getImplementation(method);
2468 type = method_getTypeEncoding(method);
2473 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2474 type = CYPoolCString(pool, context, [method _typeString]);
2480 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2487 sig::Signature signature;
2488 sig::Parse(pool, &signature, type, &Structor_);
2491 sig::sig_ffi_cif(pool, 0, signature, &cif);
2495 if (stret(cif.rtype))
2496 imp = class_getMethodImplementation_stret(_class, _cmd);
2499 imp = class_getMethodImplementation(_class, _cmd);
2502 void (*function)() = reinterpret_cast<void (*)()>(imp);
2503 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, true, signature, &cif, function);
2506 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2508 throw CYJSError(context, "too few arguments to objc_msgSend");
2518 if (JSValueIsObjectOfClass(context, arguments[0], CYPrivate<cy::Super>::Class_)) {
2519 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2520 self = internal->value_;
2521 _class = internal->class_;;
2522 uninitialized = false;
2523 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2524 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2525 self = internal->value_;
2527 uninitialized = internal->IsUninitialized();
2528 if (uninitialized && [internal->value_ retainCount] != NSUInteger(-1))
2529 internal->value_ = nil;
2531 self = CYCastNSObject(&pool, context, arguments[0]);
2533 uninitialized = false;
2537 return CYJSNull(context);
2539 _cmd = CYCastSEL(context, arguments[1]);
2541 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2544 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2545 return $objc_msgSend(context, object, _this, count, arguments);
2548 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2549 JSValueRef setup[count + 2];
2552 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2553 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2556 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2558 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2560 // XXX: handle Instance::Uninitialized?
2561 id self(CYCastNSObject(&pool, context, _this));
2565 setup[1] = &internal->sel_;
2567 return CYCallFunction(pool, context, 2, setup, count, arguments, false, true, internal->signature_, &internal->cif_, internal->value_);
2570 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2572 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2574 id self(CYCastNSObject(&pool, context, arguments[0]));
2575 Class _class(CYCastClass(pool, context, arguments[1]));
2576 return CYPrivate<cy::Super>::Make(context, self, _class);
2579 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2581 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2583 const char *name(CYPoolCString(pool, context, arguments[0]));
2584 return CYPrivate<Selector_privateData>::Make(context, sel_registerName(name));
2587 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2589 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2590 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2593 static JSValueRef Selector_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2594 return CYMakeType(context, sig::Selector());
2597 static JSValueRef Instance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2598 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2599 id self(internal->value_);
2600 return CYMakeType(context, sig::Object(class_getName(object_getClass(self))));
2603 static JSValueRef FunctionInstance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2604 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2607 if (!CYBlockSignature(pool, internal->value_, type.signature))
2608 return CYJSNull(context);
2609 return CYMakeType(context, type);
2612 static JSValueRef Constructor_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2613 return CYMakeType(context, sig::Meta());
2616 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2617 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2618 return CYMakeInstance(context, object_getClass(internal->value_), Instance::Permanent);
2621 static JSValueRef Constructor_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2622 auto internal(CYPrivate<Constructor>::Get(context, object));
2623 return CYMakeInstance(context, object_getClass(internal->value_), Instance::Permanent);
2626 static JSValueRef Constructor_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2627 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2628 id self(internal->value_);
2629 return CYPrivate<Prototype>::Cache(context, self);
2632 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2633 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2635 if (!CYJSValueIsNSObject(context, _this))
2638 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2639 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->value_, false, objects)));
2642 static JSValueRef Constructor_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2643 auto internal(CYPrivate<Constructor>::Get(context, _this));
2644 return CYCastJSValue(context, CYJSString(class_getName(internal->value_)));
2647 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2648 if (!CYJSValueIsNSObject(context, _this))
2651 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2652 id value(internal->value_);
2659 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2661 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2662 return CYJSUndefined(context);
2663 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2666 return CYCastJSValue(context, CYJSString(context, [value description]));
2668 } CYCatch(NULL) return /*XXX*/ NULL; }
2670 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2671 if (!CYJSValueIsNSObject(context, _this))
2674 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2675 id value(internal->value_);
2676 _assert(value != nil);
2678 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2681 if (JSValueRef result = [value cy$valueOfInContext:context])
2685 } CYCatch(NULL) return /*XXX*/ NULL; }
2687 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2688 if (!CYJSValueIsNSObject(context, _this))
2690 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2691 // XXX: return CYMakePointer(context, internal->value_, sig::Object(class_getName(object_getClass(internal->value_))), NULL, object);
2692 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2693 } CYCatch(NULL) return /*XXX*/ NULL; }
2695 static JSValueRef Constructor_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2696 auto internal(CYPrivate<Constructor>::Get(context, object));
2697 // XXX: return CYMakePointer(context, internal->value_, sig::Meta(), NULL, object);
2698 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2699 } CYCatch(NULL) return /*XXX*/ NULL; }
2701 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2702 if (!CYJSValueIsNSObject(context, _this))
2705 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2706 id value(internal->value_);
2709 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2710 return CYCastJSValue(context, CYJSString(context, [value description]));
2712 } CYCatch(NULL) return /*XXX*/ NULL; }
2714 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2715 if (!CYJSValueIsNSObject(context, _this))
2718 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2719 id value(internal->value_);
2721 if (!CYIsClass(value))
2722 CYThrow("non-Class object cannot be used as Type");
2724 sig::Object type(class_getName(value));
2725 return CYMakeType(context, type);
2726 } CYCatch(NULL) return /*XXX*/ NULL; }
2728 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2729 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2730 return CYCastJSValue(context, sel_getName(internal->value_));
2733 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2734 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2737 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2738 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2739 const char *name(sel_getName(internal->value_));
2742 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2743 return CYCastJSValue(context, CYJSString(context, string));
2745 } CYCatch(NULL) return /*XXX*/ NULL; }
2747 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2749 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2752 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2753 SEL sel(internal->value_);
2755 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2756 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2757 const char *encoding(method_getTypeEncoding(method));
2759 sig::Function type(false);
2760 sig::Parse(pool, &type.signature, encoding, &Structor_);
2761 return CYMakeType(context, type);
2764 static JSStaticValue Selector_staticValues[2] = {
2765 {"$cyt", &Selector_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2766 {NULL, NULL, NULL, 0}
2769 static JSStaticValue Instance_staticValues[3] = {
2770 {"$cyt", &Instance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2771 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2772 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2773 {NULL, NULL, NULL, 0}
2776 static JSStaticValue FunctionInstance_staticValues[3] = {
2777 {"$cyt", &FunctionInstance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2778 // XXX: this is sadly a duplicate of Instance_staticValues
2779 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2780 {NULL, NULL, NULL, 0}
2783 static JSStaticFunction Instance_staticFunctions[7] = {
2784 {"cy$complete", &Instance_complete_callAsFunction, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2785 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2786 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2787 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2788 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2789 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2793 static JSStaticFunction Messages_staticFunctions[2] = {
2794 {"cy$complete", &Messages_complete_callAsFunction, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2798 static JSStaticValue Constructor_staticValues[5] = {
2799 {"$cyi", &Constructor_getProperty_$cyi, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2800 {"$cyt", &Constructor_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2801 {"constructor", &Constructor_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2802 {"prototype", &Constructor_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2803 {NULL, NULL, NULL, 0}
2806 static JSStaticFunction Constructor_staticFunctions[5] = {
2807 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2808 {"toCYON", &Constructor_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2809 {"toPointer", &Constructor_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2813 static JSStaticFunction Interior_staticFunctions[2] = {
2814 {"$cya", &Interior_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2818 static JSStaticFunction Selector_staticFunctions[5] = {
2819 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2820 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2821 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2822 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2827 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2828 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2829 } CYObjectiveCatch }
2832 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2833 NSArray_ = objc_getClass("NSArray");
2834 NSBlock_ = objc_getClass("NSBlock");
2835 NSDictionary_ = objc_getClass("NSDictionary");
2836 NSNumber_ = objc_getClass("NSNumber");
2837 NSObject_ = objc_getClass("NSObject");
2838 NSString_ = objc_getClass("NSString");
2839 Object_ = objc_getClass("Object");
2842 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2844 // XXX: apparently, iOS now has both of these
2845 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2846 if (NSCFBoolean_ == nil)
2847 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2849 NSCFType_ = objc_getClass("NSCFType");
2851 NSZombie_ = objc_getClass("_NSZombie_");
2853 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2854 NSZombie_ = objc_getClass("NSZombie");
2857 JSClassDefinition definition;
2859 definition = kJSClassDefinitionEmpty;
2860 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2861 definition.className = "Messages";
2862 definition.staticFunctions = Messages_staticFunctions;
2863 definition.hasProperty = &Messages_hasProperty;
2864 definition.getProperty = &Messages_getProperty;
2865 definition.setProperty = &Messages_setProperty;
2866 CYPrivate<Messages>::Class_ = JSClassCreate(&definition);
2868 definition = kJSClassDefinitionEmpty;
2869 definition.className = "Constructor";
2870 definition.parentClass = CYPrivate<Messages>::Class_;
2871 definition.staticValues = Constructor_staticValues;
2872 definition.staticFunctions = Constructor_staticFunctions;
2873 definition.hasInstance = &Constructor_hasInstance;
2874 definition.hasProperty = &Constructor_hasProperty;
2875 definition.getProperty = &Constructor_getProperty;
2876 definition.callAsConstructor = &Constructor_callAsConstructor;
2877 definition.finalize = &CYFinalize;
2878 CYPrivate<Constructor>::Class_ = JSClassCreate(&definition);
2880 definition = kJSClassDefinitionEmpty;
2881 definition.className = "Instance";
2882 definition.staticValues = Instance_staticValues;
2883 definition.staticFunctions = Instance_staticFunctions;
2884 definition.hasProperty = &Instance_hasProperty;
2885 definition.getProperty = &Instance_getProperty;
2886 definition.setProperty = &Instance_setProperty;
2887 definition.deleteProperty = &Instance_deleteProperty;
2888 definition.getPropertyNames = &Instance_getPropertyNames;
2889 definition.finalize = &CYFinalize;
2890 Instance::Class_ = JSClassCreate(&definition);
2892 definition.className = "ArrayInstance";
2893 ArrayInstance_ = JSClassCreate(&definition);
2895 definition.className = "BooleanInstance";
2896 BooleanInstance_ = JSClassCreate(&definition);
2898 definition.className = "NumberInstance";
2899 NumberInstance_ = JSClassCreate(&definition);
2901 definition.className = "ObjectInstance";
2902 ObjectInstance_ = JSClassCreate(&definition);
2904 definition.className = "StringInstance";
2905 StringInstance_ = JSClassCreate(&definition);
2907 definition.className = "FunctionInstance";
2908 definition.staticValues = FunctionInstance_staticValues;
2909 definition.callAsFunction = &FunctionInstance_callAsFunction;
2910 FunctionInstance_ = JSClassCreate(&definition);
2912 definition = kJSClassDefinitionEmpty;
2913 definition.className = "Interior";
2914 definition.staticFunctions = Interior_staticFunctions;
2915 definition.hasProperty = &Interior_hasProperty;
2916 definition.getProperty = &Interior_getProperty;
2917 definition.setProperty = &Interior_setProperty;
2918 definition.getPropertyNames = &Interior_getPropertyNames;
2919 definition.finalize = &CYFinalize;
2920 CYPrivate<Interior>::Class_ = JSClassCreate(&definition);
2922 definition = kJSClassDefinitionEmpty;
2923 definition.className = "Message";
2924 definition.staticFunctions = cy::Functor::StaticFunctions;
2925 definition.staticValues = cy::Functor::StaticValues;
2926 definition.callAsFunction = &Message_callAsFunction;
2927 definition.finalize = &CYFinalize;
2928 Message_privateData::Class_ = JSClassCreate(&definition);
2930 definition = kJSClassDefinitionEmpty;
2931 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2932 definition.className = "Prototype";
2933 definition.parentClass = CYPrivate<Messages>::Class_;
2934 definition.finalize = &CYFinalize;
2935 CYPrivate<Prototype>::Class_ = JSClassCreate(&definition);
2937 definition = kJSClassDefinitionEmpty;
2938 definition.className = "Selector";
2939 definition.staticValues = Selector_staticValues;
2940 definition.staticFunctions = Selector_staticFunctions;
2941 definition.callAsFunction = &Selector_callAsFunction;
2942 definition.finalize = &CYFinalize;
2943 CYPrivate<Selector_privateData>::Class_ = JSClassCreate(&definition);
2945 definition = kJSClassDefinitionEmpty;
2946 definition.className = "Super";
2947 definition.finalize = &CYFinalize;
2948 CYPrivate<cy::Super>::Class_ = JSClassCreate(&definition);
2950 definition = kJSClassDefinitionEmpty;
2951 definition.className = "ObjectiveC::Classes";
2952 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2953 definition.getProperty = &ObjectiveC_Classes_getProperty;
2954 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2955 ObjectiveC_Classes_ = JSClassCreate(&definition);
2957 definition = kJSClassDefinitionEmpty;
2958 definition.className = "ObjectiveC::Constants";
2959 definition.getProperty = &ObjectiveC_Constants_getProperty;
2960 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2961 ObjectiveC_Constants_ = JSClassCreate(&definition);
2964 definition = kJSClassDefinitionEmpty;
2965 definition.className = "ObjectiveC::Images";
2966 definition.getProperty = &ObjectiveC_Images_getProperty;
2967 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2968 ObjectiveC_Images_ = JSClassCreate(&definition);
2970 definition = kJSClassDefinitionEmpty;
2971 definition.className = "ObjectiveC::Image::Classes";
2972 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2973 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2974 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2977 definition = kJSClassDefinitionEmpty;
2978 definition.className = "ObjectiveC::Protocols";
2979 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2980 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2981 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2984 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2985 // XXX: this is horrible; there has to be a better way to do this
2987 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2989 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2995 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2996 JSObjectRef global(CYGetGlobalObject(context));
2997 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2998 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2999 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
3000 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
3002 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
3003 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
3005 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3006 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
3007 CYArrayPush(context, alls, protocols);
3009 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
3010 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
3011 CYArrayPush(context, alls, classes);
3013 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
3014 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
3015 CYArrayPush(context, alls, constants);
3018 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3021 JSObjectRef Message(JSObjectMakeConstructor(context, Message_privateData::Class_, NULL));
3022 JSObjectRef Selector(JSObjectMakeConstructor(context, CYPrivate<Selector_privateData>::Class_, &Selector_new));
3023 JSObjectRef Super(JSObjectMakeConstructor(context, CYPrivate<cy::Super>::Class_, &Super_new));
3025 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance::Class_, &Instance_new));
3026 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
3027 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3029 JSObjectRef Constructor(JSObjectMakeConstructor(context, CYPrivate<::Constructor>::Class_, NULL));
3030 JSObjectRef Constructor_prototype(CYCastJSObject(context, CYGetProperty(context, Constructor, prototype_s)));
3031 CYSetProperty(context, cy, CYJSString("Constructor_prototype"), Constructor_prototype);
3033 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
3034 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
3035 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
3036 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
3037 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
3039 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
3040 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
3041 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
3042 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
3043 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
3045 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
3046 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
3047 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
3048 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
3049 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
3051 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
3052 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
3053 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
3054 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
3055 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
3057 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3058 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3059 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3060 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3061 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3063 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3064 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3065 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3066 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3067 CYSetPrototype(context, StringInstance_prototype, String_prototype);
3069 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3070 CYSetProperty(context, cycript, CYJSString("Message"), Message);
3071 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3072 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3074 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3075 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3078 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3081 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3083 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3084 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3086 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
3087 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
3088 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
3089 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::Object()), kJSPropertyAttributeDontEnum);
3090 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::Meta()), kJSPropertyAttributeDontEnum);
3091 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::Selector()), kJSPropertyAttributeDontEnum);
3093 CYSetProperty(context, cy, CYJSString("cydget"), CYCastJSValue(context, false));
3096 static void *CYObjectiveC_CastSymbol(const char *name) {
3098 #ifdef __GNU_LIBOBJC__
3099 else if (strcmp(name, "object_getClass") == 0)
3100 return reinterpret_cast<void *>(&object_getClass);
3105 static CYHook CYObjectiveCHook = {
3106 &CYObjectiveC_ExecuteStart,
3107 &CYObjectiveC_ExecuteEnd,
3108 &CYObjectiveC_CallFunction,
3109 &CYObjectiveC_Initialize,
3110 &CYObjectiveC_SetupContext,
3111 &CYObjectiveC_CastSymbol,
3114 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3116 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3117 CYSetupContext(context);
3118 JSObjectRef global(CYGetGlobalObject(context));
3119 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
3120 CYSetProperty(context, cy, CYJSString("cydget"), CYCastJSValue(context, true));
3121 } CYObjectiveCatch }
3123 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3126 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3127 utf8 = CYPoolCode(pool, utf8);
3129 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3130 size_t bytes(utf16.size * sizeof(uint16_t));
3131 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3132 memcpy(copy, utf16.data, bytes);
3136 } catch (const CYException &exception) {
3138 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];