1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2015 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 "JavaScript.hpp"
51 #include "Execute.hpp"
53 #include "ObjectiveC/Internal.hpp"
54 #include "ObjectiveC/Syntax.hpp"
56 #define CYObjectiveTry_ { \
58 #define CYObjectiveTry { \
59 JSContextRef context(context_); \
61 #define CYObjectiveCatch \
62 catch (const CYException &error) { \
63 @throw CYCastNSObject(NULL, context, error.CastJSValue(context, "Error")); \
69 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
71 #define CYPoolCatch(value) \
72 @catch (NSException *error) { \
73 _saved = [error retain]; \
74 throw CYJSError(context, CYCastJSValue(context, error)); \
79 [_saved autorelease]; \
85 #define CYSadCatch(value) \
86 @catch (NSException *error ) { \
87 throw CYJSError(context, CYCastJSValue(context, error)); \
91 #define _oassert(test) \
93 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"_assert(" #test ")" userInfo:nil];
101 void (*invoke)(void *, ...);
105 struct BlockDescriptor1 {
106 unsigned long int reserved;
107 unsigned long int size;
110 struct BlockDescriptor2 {
111 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
112 void (*dispose_helper)(BlockLiteral *src);
115 struct BlockDescriptor3 {
116 const char *signature;
121 BLOCK_DEALLOCATING = 0x0001,
122 BLOCK_REFCOUNT_MASK = 0xfffe,
123 BLOCK_NEEDS_FREE = 1 << 24,
124 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
125 BLOCK_HAS_CTOR = 1 << 26,
126 BLOCK_IS_GC = 1 << 27,
127 BLOCK_IS_GLOBAL = 1 << 28,
128 BLOCK_HAS_STRET = 1 << 29,
129 BLOCK_HAS_SIGNATURE = 1 << 30,
132 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
134 /* Objective-C Pool Release {{{ */
135 void CYPoolRelease_(void *data) {
136 id object(reinterpret_cast<id>(data));
140 id CYPoolRelease_(CYPool *pool, id object) {
143 else if (pool == NULL)
144 return [object autorelease];
146 pool->atexit(CYPoolRelease_);
151 template <typename Type_>
152 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
153 return (Type_) CYPoolRelease_(pool, (id) object);
156 /* Objective-C Strings {{{ */
157 CYUTF8String CYPoolUTF8String(CYPool &pool, JSContextRef context, NSString *value) {
158 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
159 char *string(new(pool) char[size + 1]);
160 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
161 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
162 return CYUTF8String(string, [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
165 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
166 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
167 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
172 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
173 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
177 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
180 // XXX: this definition scares me; is anyone using this?!
181 NSString *string([value description]);
183 return CYCopyJSString(context, string);
186 return CYCopyJSString(CYPoolUTF8String(pool, context, string));
190 NSString *CYCopyNSString(const CYUTF8String &value) {
192 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
194 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
198 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
200 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
203 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
207 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
208 return CYCopyNSString(context, CYJSString(context, value));
211 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
212 return CYPoolRelease(pool, CYCopyNSString(value));
215 NSString *CYCastNSString(CYPool *pool, SEL sel) {
216 const char *name(sel_getName(sel));
217 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
220 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
221 return CYPoolRelease(pool, CYCopyNSString(context, value));
224 CYUTF8String CYCastUTF8String(NSString *value) {
225 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
226 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
230 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
232 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
233 if (exception == NULL)
235 *exception = CYCastJSValue(context, error);
238 size_t CYGetIndex(NSString *value) {
239 return CYGetIndex(CYCastUTF8String(value));
242 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
243 return CYGetOffset(CYPoolCString(pool, context, value), index);
246 static JSClassRef ArrayInstance_;
247 static JSClassRef BooleanInstance_;
248 static JSClassRef ClassInstance_;
249 static JSClassRef FunctionInstance_;
250 static JSClassRef NumberInstance_;
251 static JSClassRef ObjectInstance_;
252 static JSClassRef StringInstance_;
254 static JSClassRef ObjectiveC_Classes_;
255 static JSClassRef ObjectiveC_Constants_;
256 static JSClassRef ObjectiveC_Protocols_;
259 static JSClassRef ObjectiveC_Image_Classes_;
260 static JSClassRef ObjectiveC_Images_;
264 static Class __NSMallocBlock__;
265 static Class NSCFBoolean_;
266 static Class NSCFType_;
267 static Class NSGenericDeallocHandler_;
269 static Class NSBoolNumber_;
272 static Class NSArray_;
273 static Class NSBlock_;
274 static Class NSDictionary_;
275 static Class NSNumber_;
276 static Class NSString_;
277 static Class NSZombie_;
278 static Class Object_;
280 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
282 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
284 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
285 else if (meta && !class_isMetaClass(self))
286 return CYGetCachedObject(context, CYJSString("ClassInstance_prototype"));
288 JSObjectRef global(CYGetGlobalObject(context));
289 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
292 sprintf(label, "i%p", self);
293 CYJSString name(label);
295 JSValueRef value(CYGetProperty(context, cy, name));
296 if (!JSValueIsUndefined(context, value))
299 JSValueRef prototype;
302 if (self == NSCFBoolean_)
304 if (self == NSBoolNumber_)
306 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
307 else if (self == NSArray_)
308 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
309 else if (self == NSBlock_)
310 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
311 else if (self == NSNumber_)
312 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
313 else if (self == NSDictionary_)
314 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
315 else if (self == NSString_)
316 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
318 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
320 JSObjectRef object(JSObjectMake(context, NULL, NULL));
321 CYSetPrototype(context, object, prototype);
322 CYSetProperty(context, cy, name, object);
327 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
328 return CYGetClassPrototype(context, self, class_isMetaClass(self));
331 JSValueRef Messages::GetPrototype(JSContextRef context) const {
332 if (Class super = class_getSuperclass(value_))
333 return Messages::Make(context, super);
337 bool CYIsKindOfClass(id object, Class _class) {
338 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
344 JSValueRef Instance::GetPrototype(JSContextRef context) const {
345 return CYGetClassPrototype(context, object_getClass(value_));
348 JSClassRef Instance::GetClass(id object, Flags flags) {
349 return CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance::Class_;
352 Instance::Instance(id value, Flags flags) :
356 if ((flags & Instance::Permanent) == 0)
357 value_ = [value_ retain];
360 Instance::~Instance() {
361 if ((flags_ & Permanent) == 0)
365 struct Message_privateData :
368 static JSClassRef Class_;
372 Message_privateData(SEL sel, const char *type, IMP value) :
373 cy::Functor(reinterpret_cast<void (*)()>(value), type),
378 static JSObjectRef Make(JSContextRef context, SEL sel, const char *type, IMP value);
381 JSClassRef Message_privateData::Class_;
383 JSObjectRef CYMakeInstance(JSContextRef context, id object, Instance::Flags flags = Instance::None) {
384 _assert(object != nil);
387 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
389 if (weak != NULL && &JSWeakObjectMapGet != NULL)
390 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
394 JSObjectRef instance(Instance::Make(context, object, flags));
397 if (weak != NULL && &JSWeakObjectMapSet != NULL)
398 JSWeakObjectMapSet(context, weak, object, instance);
404 @interface NSMethodSignature (Cycript)
405 - (NSString *) _typeString;
408 @interface NSObject (Cycript)
410 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
411 - (JSType) cy$JSType;
413 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
414 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
416 - (bool) cy$hasProperty:(NSString *)name;
417 - (NSObject *) cy$getProperty:(NSString *)name;
418 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
419 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
420 - (bool) cy$deleteProperty:(NSString *)name;
421 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
423 + (bool) cy$hasImplicitProperties;
429 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
432 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
433 _assert(value != nil);
435 Class _class(object_getClass(value));
437 if (class_isMetaClass(_class)) {
438 const char *name(class_getName(value));
439 if (class_isMetaClass(value))
440 return [NSString stringWithFormat:@"object_getClass(%s)", name];
442 return [NSString stringWithUTF8String:name];
445 if (_class == NSZombie_)
446 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
448 SEL sel(@selector(cy$toCYON:inSet:));
450 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
451 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
452 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
453 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
454 return [value cy$toCYON:objective inSet:objects];
456 return [NSString stringWithFormat:@"%@", value];
459 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
461 return CYCastNSCYON(value, objective, *objects);
463 std::set<void *> objects;
464 return CYCastNSCYON(value, objective, objects);
468 struct PropertyAttributes {
473 const char *variable;
486 PropertyAttributes(objc_property_t property) :
498 name = property_getName(property);
499 const char *attributes(property_getAttributes(property));
501 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
502 if ((next = strchr(token, ',')) != NULL)
505 case 'R': readonly = true; break;
506 case 'C': copy = true; break;
507 case '&': retain = true; break;
508 case 'N': nonatomic = true; break;
509 case 'G': getter_ = token + 1; break;
510 case 'S': setter_ = token + 1; break;
511 case 'V': variable = token + 1; break;
515 /*if (variable == NULL) {
516 variable = property_getName(property);
517 size_t size(strlen(variable));
518 char *name(new(pool_) char[size + 2]);
520 memcpy(name + 1, variable, size);
521 name[size + 1] = '\0';
526 const char *Getter() {
528 getter_ = pool_.strdup(name);
532 const char *Setter() {
533 if (setter_ == NULL && !readonly) {
534 size_t length(strlen(name));
536 char *temp(new(pool_) char[length + 5]);
542 temp[3] = toupper(name[0]);
543 memcpy(temp + 4, name + 1, length - 1);
546 temp[length + 3] = ':';
547 temp[length + 4] = '\0';
556 @interface CYWebUndefined : NSObject {
559 + (CYWebUndefined *) undefined;
563 @implementation CYWebUndefined
565 + (CYWebUndefined *) undefined {
566 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
572 #define WebUndefined CYWebUndefined
574 /* Bridge: CYJSObject {{{ */
575 @interface CYJSObject : NSMutableDictionary {
577 JSGlobalContextRef context_;
580 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
582 - (NSUInteger) count;
583 - (id) objectForKey:(id)key;
584 - (NSEnumerator *) keyEnumerator;
585 - (void) setObject:(id)object forKey:(id)key;
586 - (void) removeObjectForKey:(id)key;
590 /* Bridge: CYJSArray {{{ */
591 @interface CYJSArray : NSMutableArray {
593 JSGlobalContextRef context_;
596 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
598 - (NSUInteger) count;
599 - (id) objectAtIndex:(NSUInteger)index;
601 - (void) addObject:(id)anObject;
602 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
603 - (void) removeLastObject;
604 - (void) removeObjectAtIndex:(NSUInteger)index;
605 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
610 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
611 return JSValueIsObjectOfClass(context, value, Instance::Class_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
614 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
615 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
619 struct CYBlockDescriptor {
621 BlockDescriptor1 one_;
622 BlockDescriptor2 two_;
623 BlockDescriptor3 three_;
626 Closure_privateData *internal_;
629 void CYDisposeBlock(BlockLiteral *literal) {
630 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
633 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
634 JSObjectRef _this(CYCastJSObject(context, values[0]));
635 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
638 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
639 _assert(__NSMallocBlock__ != Nil);
640 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
642 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
643 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
645 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockAdapter_);
646 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->value_);
648 literal->isa = __NSMallocBlock__;
649 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
650 literal->reserved = 0;
651 literal->descriptor = descriptor;
653 descriptor->d_.one_.size = sizeof(descriptor->d_);
654 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
655 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
657 return reinterpret_cast<NSBlock *>(literal);
661 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
662 if (CYJSValueIsNSObject(context, object)) {
663 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
664 return internal->value_;
667 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
668 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
669 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
672 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
673 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
677 @interface NSBoolNumber : NSNumber {
682 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
686 switch (JSType type = JSValueGetType(context, value)) {
687 case kJSTypeUndefined:
688 object = [WebUndefined undefined];
698 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
701 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
707 object = CYCopyNSNumber(context, value);
712 object = CYCopyNSString(context, value);
717 // XXX: this might could be more efficient
718 object = CYCastNSObject(pool, context, (JSObjectRef) value);
723 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
730 return CYPoolRelease(pool, object);
732 return [object retain];
735 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
736 return CYNSObject(pool, context, value, true);
739 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
740 return CYNSObject(&pool, context, value, false);
743 /* Bridge: NSArray {{{ */
744 @implementation NSArray (Cycript)
747 return [[self mutableCopy] autorelease];
750 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
751 _oassert(objects.insert(self).second);
753 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
754 [json appendString:@"@["];
758 for (id object in self) {
760 for (size_t index(0), count([self count]); index != count; ++index) {
761 id object([self objectAtIndex:index]);
764 [json appendString:@","];
767 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
768 [json appendString:CYCastNSCYON(object, true, objects)];
770 [json appendString:@","];
775 [json appendString:@"]"];
779 - (bool) cy$hasProperty:(NSString *)name {
780 if ([name isEqualToString:@"length"])
783 size_t index(CYGetIndex(name));
784 if (index == _not(size_t) || index >= [self count])
785 return [super cy$hasProperty:name];
790 - (NSObject *) cy$getProperty:(NSString *)name {
791 size_t index(CYGetIndex(name));
792 if (index == _not(size_t) || index >= [self count])
793 return [super cy$getProperty:name];
795 return [self objectAtIndex:index];
798 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
800 if ([name isEqualToString:@"length"])
801 return CYCastJSValue(context, [self count]);
804 return [super cy$getProperty:name inContext:context];
807 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
808 [super cy$getPropertyNames:names inContext:context];
810 for (size_t index(0), count([self count]); index != count; ++index) {
811 id object([self objectAtIndex:index]);
812 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
814 sprintf(name, "%zu", index);
815 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
820 + (bool) cy$hasImplicitProperties {
826 /* Bridge: NSBlock {{{ */
828 @interface NSBlock : NSObject
832 static const char *CYBlockEncoding(NSBlock *self);
833 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature);
835 @implementation NSBlock (Cycript)
837 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
841 if (!CYBlockSignature(pool, self, type.signature))
842 return [super cy$toCYON:objective inSet:objects];
843 _oassert(objects.insert(self).second);
845 CYTypedIdentifier *typed((new(pool) CYTypeExpression(CYDecodeType(pool, &type)))->typed_);
846 CYTypeModifier *&modifier(CYGetLast(typed->modifier_));
847 CYTypeBlockWith *with(dynamic_cast<CYTypeBlockWith *>(modifier));
848 _assert(with != NULL);
849 CYObjCBlock *block(new(pool) CYObjCBlock(typed, with->parameters_, NULL));
852 std::ostringstream str;
854 CYOutput out(*str.rdbuf(), options);
855 block->Output(out, CYNoFlags);
857 std::string value(str.str());
858 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
864 /* Bridge: NSBoolNumber {{{ */
866 @implementation NSBoolNumber (Cycript)
868 - (JSType) cy$JSType {
869 return kJSTypeBoolean;
872 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
873 NSString *value([self boolValue] ? @"true" : @"false");
874 return objective ? value : [NSString stringWithFormat:@"@%@", value];
877 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
878 return CYCastJSValue(context, (bool) [self boolValue]);
884 /* Bridge: NSDictionary {{{ */
885 @implementation NSDictionary (Cycript)
888 return [[self mutableCopy] autorelease];
891 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
892 _oassert(objects.insert(self).second);
894 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
895 [json appendString:@"@{"];
899 for (NSObject *key in self) {
901 NSEnumerator *keys([self keyEnumerator]);
902 while (NSObject *key = [keys nextObject]) {
905 [json appendString:@","];
908 [json appendString:CYCastNSCYON(key, true, objects)];
909 [json appendString:@":"];
910 NSObject *object([self objectForKey:key]);
911 [json appendString:CYCastNSCYON(object, true, objects)];
914 [json appendString:@"}"];
918 - (bool) cy$hasProperty:(NSString *)name {
919 return [self objectForKey:name] != nil;
922 - (NSObject *) cy$getProperty:(NSString *)name {
923 return [self objectForKey:name];
926 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
927 [super cy$getPropertyNames:names inContext:context];
930 for (NSObject *key in self) {
932 NSEnumerator *keys([self keyEnumerator]);
933 while (NSObject *key = [keys nextObject]) {
935 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
939 + (bool) cy$hasImplicitProperties {
945 /* Bridge: NSMutableArray {{{ */
946 @implementation NSMutableArray (Cycript)
948 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
949 if ([name isEqualToString:@"length"]) {
950 // XXX: is this not intelligent?
951 NSNumber *number(reinterpret_cast<NSNumber *>(value));
952 NSUInteger size([number unsignedIntegerValue]);
953 NSUInteger count([self count]);
955 [self removeObjectsInRange:NSMakeRange(size, count - size)];
956 else if (size != count) {
957 WebUndefined *undefined([WebUndefined undefined]);
958 for (size_t i(count); i != size; ++i)
959 [self addObject:undefined];
964 size_t index(CYGetIndex(name));
965 if (index == _not(size_t))
966 return [super cy$setProperty:name to:value];
968 id object(value ?: [NSNull null]);
970 size_t count([self count]);
972 [self replaceObjectAtIndex:index withObject:object];
974 if (index != count) {
975 WebUndefined *undefined([WebUndefined undefined]);
976 for (size_t i(count); i != index; ++i)
977 [self addObject:undefined];
980 [self addObject:object];
986 - (bool) cy$deleteProperty:(NSString *)name {
987 size_t index(CYGetIndex(name));
988 if (index == _not(size_t) || index >= [self count])
989 return [super cy$deleteProperty:name];
990 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
996 /* Bridge: NSMutableDictionary {{{ */
997 @implementation NSMutableDictionary (Cycript)
999 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1000 [self setObject:(value ?: [NSNull null]) forKey:name];
1004 - (bool) cy$deleteProperty:(NSString *)name {
1005 if ([self objectForKey:name] == nil)
1008 [self removeObjectForKey:name];
1015 /* Bridge: NSNumber {{{ */
1016 @implementation NSNumber (Cycript)
1018 - (JSType) cy$JSType {
1020 // XXX: this just seems stupid
1021 if ([self class] == NSCFBoolean_)
1022 return kJSTypeBoolean;
1024 return kJSTypeNumber;
1027 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1028 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1029 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1032 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1033 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1034 } CYObjectiveCatch }
1038 /* Bridge: NSNull {{{ */
1039 @implementation NSNull (Cycript)
1041 - (JSType) cy$JSType {
1045 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1046 NSString *value(@"null");
1047 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1050 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1051 return CYJSNull(context);
1052 } CYObjectiveCatch }
1056 /* Bridge: NSObject {{{ */
1057 @implementation NSObject (Cycript)
1063 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1064 return [self cy$valueOfInContext:context];
1067 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1069 } CYObjectiveCatch }
1071 - (JSType) cy$JSType {
1072 return kJSTypeObject;
1075 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1076 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1079 - (bool) cy$hasProperty:(NSString *)name {
1083 - (NSObject *) cy$getProperty:(NSString *)name {
1087 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1088 if (NSObject *value = [self cy$getProperty:name])
1089 return CYCastJSValue(context, value);
1091 } CYObjectiveCatch }
1093 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1097 - (bool) cy$deleteProperty:(NSString *)name {
1101 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1104 + (bool) cy$hasImplicitProperties {
1110 /* Bridge: NSOrderedSet {{{ */
1112 @implementation NSOrderedSet (Cycript)
1114 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1115 _oassert(objects.insert(self).second);
1117 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1118 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1119 [json appendString:CYCastNSCYON([self array], true, objects)];
1120 [json appendString:@"]]"];
1127 /* Bridge: NSProxy {{{ */
1128 @implementation NSProxy (Cycript)
1130 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1131 return [[self description] cy$toCYON:objective inSet:objects];
1136 /* Bridge: NSSet {{{ */
1137 @implementation NSSet (Cycript)
1139 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1140 _oassert(objects.insert(self).second);
1142 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1143 [json appendString:@"[NSSet setWithArray:"];
1144 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1145 [json appendString:@"]]"];
1151 /* Bridge: NSString {{{ */
1152 @implementation NSString (Cycript)
1155 return [[self copy] autorelease];
1158 - (JSType) cy$JSType {
1159 return kJSTypeString;
1162 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1163 std::ostringstream str;
1166 CYUTF8String string(CYCastUTF8String(self));
1167 CYStringify(str, string.data, string.size, true);
1168 std::string value(str.str());
1169 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1172 - (bool) cy$hasProperty:(NSString *)name {
1173 size_t index(CYGetIndex(name));
1174 if (index == _not(size_t) || index >= [self length])
1175 return [super cy$hasProperty:name];
1180 - (NSObject *) cy$getProperty:(NSString *)name {
1181 size_t index(CYGetIndex(name));
1182 if (index == _not(size_t) || index >= [self length])
1183 return [super cy$getProperty:name];
1185 return [self substringWithRange:NSMakeRange(index, 1)];
1188 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1189 [super cy$getPropertyNames:names inContext:context];
1191 for (size_t index(0), length([self length]); index != length; ++index) {
1193 sprintf(name, "%zu", index);
1194 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1198 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1199 return CYCastJSValue(context, CYJSString(context, self));
1200 } CYObjectiveCatch }
1204 /* Bridge: WebUndefined {{{ */
1205 @implementation WebUndefined (Cycript)
1207 - (JSType) cy$JSType {
1208 return kJSTypeUndefined;
1211 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1212 NSString *value(@"undefined");
1213 return value; // XXX: maybe use the below code, adding @undefined?
1214 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1217 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1218 return CYJSUndefined(context);
1219 } CYObjectiveCatch }
1224 static bool CYIsClass(id self) {
1225 return class_isMetaClass(object_getClass(self));
1228 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1229 id self(CYCastNSObject(&pool, context, value));
1230 if (CYIsClass(self))
1231 return (Class) self;
1232 throw CYJSError(context, "got something that is not a Class");
1236 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1238 size_t size(JSPropertyNameArrayGetCount(names));
1239 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1240 for (size_t index(0); index != size; ++index)
1241 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1245 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) {
1247 return CYJSNull(context);
1248 return CYMakeInstance(context, value);
1251 @implementation CYJSObject
1253 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1254 if ((self = [super init]) != nil) {
1256 context_ = CYGetJSContext(context);
1257 JSGlobalContextRetain(context_);
1258 JSValueProtect(context_, object_);
1260 } CYObjectiveCatch }
1262 - (void) dealloc { CYObjectiveTry {
1263 JSValueUnprotect(context_, object_);
1264 JSGlobalContextRelease(context_);
1266 } CYObjectiveCatch }
1268 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1270 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1272 return [super cy$toCYON:objective inSet:objects];
1274 return [NSString stringWithUTF8String:cyon];
1275 } CYObjectiveCatch }
1277 - (NSUInteger) count { CYObjectiveTry {
1278 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1279 size_t size(JSPropertyNameArrayGetCount(names));
1280 JSPropertyNameArrayRelease(names);
1282 } CYObjectiveCatch }
1284 - (id) objectForKey:(id)key { CYObjectiveTry {
1285 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1286 if (JSValueIsUndefined(context, value))
1288 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1289 } CYObjectiveCatch }
1291 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1292 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1293 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1294 JSPropertyNameArrayRelease(names);
1296 } CYObjectiveCatch }
1298 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1299 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1300 } CYObjectiveCatch }
1302 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1303 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1304 } CYObjectiveCatch }
1308 @implementation CYJSArray
1310 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1312 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1313 } CYObjectiveCatch }
1315 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1316 if ((self = [super init]) != nil) {
1318 context_ = CYGetJSContext(context);
1319 JSGlobalContextRetain(context_);
1320 JSValueProtect(context_, object_);
1322 } CYObjectiveCatch }
1324 - (void) dealloc { CYObjectiveTry {
1325 JSValueUnprotect(context_, object_);
1326 JSGlobalContextRelease(context_);
1328 } CYObjectiveCatch }
1330 - (NSUInteger) count { CYObjectiveTry {
1331 return CYArrayLength(context, object_);
1332 } CYObjectiveCatch }
1334 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1335 size_t bounds([self count]);
1336 if (index >= bounds)
1337 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1338 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1339 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1340 } CYObjectiveCatch }
1342 - (void) addObject:(id)object { CYObjectiveTry {
1343 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1344 } CYObjectiveCatch }
1346 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1347 size_t bounds([self count] + 1);
1348 if (index >= bounds)
1349 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1350 JSValueRef arguments[3];
1351 arguments[0] = CYCastJSValue(context, index);
1352 arguments[1] = CYCastJSValue(context, 0);
1353 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1354 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1355 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1356 } CYObjectiveCatch }
1358 - (void) removeLastObject { CYObjectiveTry {
1359 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1360 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1361 } CYObjectiveCatch }
1363 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1364 size_t bounds([self count]);
1365 if (index >= bounds)
1366 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1367 JSValueRef arguments[2];
1368 arguments[0] = CYCastJSValue(context, index);
1369 arguments[1] = CYCastJSValue(context, 1);
1370 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1371 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1372 } CYObjectiveCatch }
1374 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1375 size_t bounds([self count]);
1376 if (index >= bounds)
1377 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1378 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1379 } CYObjectiveCatch }
1383 // XXX: inherit from or replace with CYJSObject
1384 @interface CYInternal : NSObject {
1385 JSGlobalContextRef context_;
1386 JSObjectRef object_;
1391 @implementation CYInternal
1393 - (void) dealloc { CYObjectiveTry {
1394 JSValueUnprotect(context_, object_);
1395 JSGlobalContextRelease(context_);
1397 } CYObjectiveCatch }
1399 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1400 if ((self = [super init]) != nil) {
1401 context_ = CYGetJSContext(context);
1402 JSGlobalContextRetain(context_);
1404 } CYObjectiveCatch }
1406 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1407 if (object_ == NULL)
1410 return JSObjectHasProperty(context, object_, name);
1413 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1414 if (object_ == NULL)
1417 return CYGetProperty(context, object_, name);
1420 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1421 @synchronized (self) {
1422 if (object_ == NULL) {
1423 object_ = JSObjectMake(context, NULL, NULL);
1424 JSValueProtect(context, object_);
1428 CYSetProperty(context, object_, name, value);
1431 + (CYInternal *) get:(id)object {
1433 if (&objc_getAssociatedObject == NULL)
1436 @synchronized (object) {
1437 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1445 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1447 if (&objc_getAssociatedObject == NULL)
1450 @synchronized (object) {
1451 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1454 if (&objc_setAssociatedObject == NULL)
1457 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1458 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1468 static JSValueRef CYCastJSValue(JSContextRef context, SEL sel) {
1470 return CYJSNull(context);
1471 return Selector_privateData::Make(context, sel);
1474 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1475 if (JSValueIsObjectOfClass(context, value, Selector_privateData::Class_)) {
1476 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1477 return reinterpret_cast<SEL>(internal->value_);
1480 return sel_registerName(CYPoolCString(pool, context, value));
1484 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1485 return (void *) [[NSAutoreleasePool alloc] init];
1486 } CYSadCatch(NULL) }
1488 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1489 return [(NSAutoreleasePool *) handle release];
1492 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1493 CYCallFunction(pool, context, cif, function, value, values);
1496 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, const sig::Signature *signature) {
1498 if (JSValueIsNull(context, value))
1500 JSObjectRef object(CYCastJSObject(context, value));
1502 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1503 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_;
1505 if (JSValueIsObjectOfClass(context, object, Instance::Class_)) {
1506 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_ == nil);
1510 _assert(JSObjectIsFunction(context, object));
1512 _assert(signature != NULL);
1513 _assert(signature->count != 0);
1515 sig::Signature modified;
1516 modified.count = signature->count + 1;
1517 modified.elements = new(pool) sig::Element[modified.count];
1519 modified.elements[0] = signature->elements[0];
1520 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1522 modified.elements[1].name = NULL;
1523 modified.elements[1].type = new(pool) sig::Object();
1524 modified.elements[1].offset = _not(size_t);
1526 return CYMakeBlock(context, object, modified);
1534 void Block::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1535 // XXX: this function might not handle the idea of a null pool
1536 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &signature);
1539 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1540 void Object::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1541 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1544 void Meta::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1545 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1548 void Selector::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1549 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1552 JSValueRef Object::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1553 NSObject *value(*reinterpret_cast<NSObject **>(data));
1555 return CYJSNull(context);
1556 JSObjectRef object(CYMakeInstance(context, value));
1559 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1561 if ((internal->flags_ & Instance::Uninitialized) != 0) {
1562 internal->flags_ = static_cast<Instance::Flags>(internal->flags_ & ~Instance::Uninitialized);
1563 _assert(internal->value_ == nil);
1564 internal->value_ = value;
1573 JSValueRef Meta::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1574 if (Class value = *reinterpret_cast<Class *>(data))
1575 return CYMakeInstance(context, value, Instance::Permanent);
1576 return CYJSNull(context);
1579 JSValueRef Selector::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1580 return CYCastJSValue(context, *reinterpret_cast<SEL *>(data));
1583 JSValueRef Block::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1584 return CYCastJSValue(context, *reinterpret_cast<NSObject **>(data));
1589 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1590 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1594 method_getReturnType(method, type, sizeof(type));
1599 // XXX: possibly use a more "awesome" check?
1603 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1604 JSObjectRef _this(CYCastJSObject(context, values[0]));
1605 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1608 JSObjectRef Message_privateData::Make(JSContextRef context, SEL sel, const char *type, IMP value) {
1609 Message_privateData *internal(new Message_privateData(sel, type, value));
1610 return JSObjectMake(context, Message_privateData::Class_, internal);
1613 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1614 JSObjectRef function(CYCastJSObject(context, value));
1616 sig::Signature signature;
1617 sig::Parse(pool, &signature, encoding, &Structor_);
1618 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1619 // XXX: see notes in Library.cpp about needing to leak
1620 return reinterpret_cast<IMP>(internal->value_);
1623 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1624 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1625 Class _class(internal->value_);
1628 const char *name(CYPoolCString(pool, context, property));
1630 if (SEL sel = sel_getUid(name))
1631 if (class_getInstanceMethod(_class, sel) != NULL)
1637 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1638 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1639 Class _class(internal->value_);
1642 const char *name(CYPoolCString(pool, context, property));
1644 if (SEL sel = sel_getUid(name))
1645 if (objc_method *method = class_getInstanceMethod(_class, sel))
1646 return Message_privateData::Make(context, sel, method_getTypeEncoding(method), method_getImplementation(method));
1651 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1652 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1653 Class _class(internal->value_);
1656 const char *name(CYPoolCString(pool, context, property));
1657 SEL sel(sel_registerName(name));
1662 if (JSValueIsObjectOfClass(context, value, Message_privateData::Class_)) {
1663 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1664 type = sig::Unparse(pool, &message->signature_);
1665 imp = reinterpret_cast<IMP>(message->value_);
1666 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1667 type = method_getTypeEncoding(method);
1668 imp = CYMakeMessage(context, value, type);
1669 } else _assert(false);
1671 objc_method *method(NULL);
1673 objc_method **methods(class_copyMethodList(_class, &size));
1674 for (size_t i(0); i != size; ++i)
1675 if (sel_isEqual(method_getName(methods[i]), sel)) {
1676 method = methods[i];
1682 method_setImplementation(method, imp);
1684 class_addMethod(_class, sel, imp, type);
1689 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1690 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1691 Class _class(internal->value_);
1694 objc_method **data(class_copyMethodList(_class, &size));
1695 for (size_t i(0); i != size; ++i)
1696 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1700 static bool CYHasImplicitProperties(Class _class) {
1701 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1702 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1704 return [_class cy$hasImplicitProperties];
1707 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1708 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1709 id self(internal->value_);
1711 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1715 NSString *name(CYCastNSString(&pool, context, property));
1717 if (CYInternal *internal = [CYInternal get:self])
1718 if ([internal hasProperty:property inContext:context])
1721 Class _class(object_getClass(self));
1724 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1725 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1726 if ([self cy$hasProperty:name])
1728 } CYPoolCatch(false)
1730 const char *string(CYPoolCString(pool, context, name));
1732 if (class_getProperty(_class, string) != NULL)
1735 if (CYHasImplicitProperties(_class))
1736 if (SEL sel = sel_getUid(string))
1737 if (CYImplements(self, _class, sel, true))
1743 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1744 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1745 id self(internal->value_);
1747 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1748 return Interior::Make(context, self, context, object);
1751 NSString *name(CYCastNSString(&pool, context, property));
1753 if (CYInternal *internal = [CYInternal get:self])
1754 if (JSValueRef value = [internal getProperty:property inContext:context])
1758 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1762 const char *string(CYPoolCString(pool, context, name));
1763 Class _class(object_getClass(self));
1765 if (objc_property_t property = class_getProperty(_class, string)) {
1766 PropertyAttributes attributes(property);
1767 SEL sel(sel_registerName(attributes.Getter()));
1768 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1771 if (CYHasImplicitProperties(_class))
1772 if (SEL sel = sel_getUid(string))
1773 if (CYImplements(self, _class, sel, true))
1774 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1779 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1780 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1781 id self(internal->value_);
1785 NSString *name(CYCastNSString(&pool, context, property));
1786 NSObject *data(CYCastNSObject(&pool, context, value));
1789 if ([self cy$setProperty:name to:data])
1791 } CYPoolCatch(false)
1793 const char *string(CYPoolCString(pool, context, name));
1794 Class _class(object_getClass(self));
1796 if (objc_property_t property = class_getProperty(_class, string)) {
1797 PropertyAttributes attributes(property);
1798 if (const char *setter = attributes.Setter()) {
1799 SEL sel(sel_registerName(setter));
1800 JSValueRef arguments[1] = {value};
1801 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1806 size_t length(strlen(string));
1808 char set[length + 5];
1814 if (string[0] != '\0') {
1815 set[3] = toupper(string[0]);
1816 memcpy(set + 4, string + 1, length - 1);
1819 set[length + 3] = ':';
1820 set[length + 4] = '\0';
1822 if (SEL sel = sel_getUid(set))
1823 if (CYImplements(self, _class, sel)) {
1824 JSValueRef arguments[1] = {value};
1825 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1829 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1830 [internal setProperty:property toValue:value inContext:context];
1837 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1838 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1839 id self(internal->value_);
1842 NSString *name(CYCastNSString(NULL, context, property));
1843 return [self cy$deleteProperty:name];
1844 } CYPoolCatch(false)
1845 } CYCatch(false) return /*XXX*/ false; }
1847 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1848 const char *name(sel_getName(method_getName(method)));
1849 if (strchr(name, ':') != NULL)
1852 const char *type(method_getTypeEncoding(method));
1853 if (type == NULL || *type == '\0' || *type == 'v')
1856 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1859 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1860 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1861 id self(internal->value_);
1864 Class _class(object_getClass(self));
1868 objc_property_t *data(class_copyPropertyList(_class, &size));
1869 for (size_t i(0); i != size; ++i)
1870 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1874 if (CYHasImplicitProperties(_class))
1875 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1877 objc_method **data(class_copyMethodList(current, &size));
1878 for (size_t i(0); i != size; ++i)
1879 Instance_getPropertyNames_message(names, data[i]);
1884 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1885 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1886 [self cy$getPropertyNames:names inContext:context];
1890 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1891 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1892 JSObjectRef value(CYMakeInstance(context, [internal->value_ alloc], Instance::Uninitialized));
1896 static const char *CYBlockEncoding(NSBlock *self) {
1897 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1898 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1900 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1901 descriptor += sizeof(BlockDescriptor1);
1902 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1903 descriptor += sizeof(BlockDescriptor2);
1904 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1905 return descriptor3->signature;
1908 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature) {
1909 const char *encoding(CYBlockEncoding(self));
1910 if (encoding == NULL)
1913 sig::Parse(pool, &signature, encoding, &Structor_);
1914 _assert(signature.count >= 2);
1916 _assert(dynamic_cast<sig::Object *>(signature.elements[1].type) != NULL);
1917 signature.elements[1] = signature.elements[0];
1919 ++signature.elements;
1925 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1926 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1927 id self(internal->value_);
1929 if (const char *encoding = CYBlockEncoding(self)) {
1935 sig::Signature signature;
1936 sig::Parse(pool, &signature, encoding, &Structor_);
1939 sig::sig_ffi_cif(pool, 0, signature, &cif);
1941 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1942 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1943 return CYCallFunction(pool, context, 1, setup, count, arguments, false, false, signature, &cif, function);
1947 CYThrow("NSBlock without signature field passed arguments");
1951 } CYPoolCatch(NULL);
1956 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1957 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1958 Class _class(internal->value_);
1959 if (!CYIsClass(_class))
1962 if (CYJSValueIsNSObject(context, instance)) {
1963 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1964 // XXX: this isn't always safe
1965 return [linternal->value_ isKindOfClass:_class];
1971 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1973 throw CYJSError(context, "incorrect number of arguments to Instance");
1975 id value(CYCastNSObject(&pool, context, arguments[0]));
1977 value = [NSNull null];
1978 return CYCastJSValue(context, [value cy$box]);
1981 static bool Interior_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1982 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
1985 id self(internal->value_);
1986 const char *name(CYPoolCString(pool, context, property));
1988 if (object_getInstanceVariable(self, name, NULL) != NULL)
1994 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
1995 length = CYCastDouble(encoding + 1);
1999 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2000 for (size_t i(0); i != size; ++i)
2001 if (ivars[i] == ivar)
2003 else if (ivar_getOffset(ivars[i]) == offset) {
2004 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2005 _assert(encoding != NULL);
2006 _assert(encoding[0] == 'b');
2007 shift += CYCastDouble(encoding + 1);
2012 static JSValueRef Interior_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2013 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2016 id self(internal->value_);
2017 const char *name(CYPoolCString(pool, context, property));
2019 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2020 ptrdiff_t offset(ivar_getOffset(ivar));
2021 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2023 const char *encoding(ivar_getTypeEncoding(ivar));
2024 _assert(encoding != NULL);
2025 _assert(encoding[0] != '\0');
2026 if (encoding[0] == 'b') {
2027 unsigned length, shift;
2028 CYBitField(length, shift, self, ivar, encoding, offset);
2029 _assert(shift + length <= sizeof(uintptr_t) * 8);
2030 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2031 uintptr_t mask((1 << length) - 1);
2032 return CYCastJSValue(context, (field >> shift) & mask);
2034 #if defined(__APPLE__) && defined(__LP64__)
2035 // XXX: maybe do even more verifications here
2036 if (strcmp(name, "isa") == 0)
2037 return CYCastJSValue(context, object_getClass(self));
2040 auto type(new(pool) Type_privateData(encoding));
2041 return type->type_->FromFFI(context, type->GetFFI(), data);
2048 static bool Interior_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2049 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2052 id self(internal->value_);
2053 const char *name(CYPoolCString(pool, context, property));
2055 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2056 ptrdiff_t offset(ivar_getOffset(ivar));
2057 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2059 const char *encoding(ivar_getTypeEncoding(ivar));
2060 _assert(encoding != NULL);
2061 if (encoding[0] == 'b') {
2062 unsigned length, shift;
2063 CYBitField(length, shift, self, ivar, encoding, offset);
2064 _assert(shift + length <= sizeof(uintptr_t) * 8);
2065 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2066 uintptr_t mask((1 << length) - 1);
2067 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2069 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2070 type->type_->PoolFFI(&pool, context, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2078 static void Interior_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2079 if (Class super = class_getSuperclass(_class))
2080 Interior_getPropertyNames_(super, names);
2083 objc_ivar **data(class_copyIvarList(_class, &size));
2084 for (size_t i(0); i != size; ++i)
2085 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2089 static void Interior_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2090 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2093 id self(internal->value_);
2094 Class _class(object_getClass(self));
2096 Interior_getPropertyNames_(_class, names);
2099 static JSValueRef Interior_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2100 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2101 return internal->owner_;
2104 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2106 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2109 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2111 NSString *name(CYCastNSString(&pool, context, property));
2112 if (Class _class = NSClassFromString(name))
2113 return CYMakeInstance(context, _class, Instance::Permanent);
2117 static Class *CYCopyClassList(size_t &size) {
2118 size = objc_getClassList(NULL, 0);
2119 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2122 size_t writ(objc_getClassList(data, size));
2128 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2139 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2141 if (Class *data = CYCopyClassList(size)) {
2142 for (size_t i(0); i != size; ++i)
2143 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2149 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2150 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2153 const char *name(CYPoolCString(pool, context, property));
2155 const char **data(objc_copyClassNamesForImage(internal, &size));
2157 for (size_t i(0); i != size; ++i)
2158 if (strcmp(name, data[i]) == 0) {
2159 if (Class _class = objc_getClass(name)) {
2160 value = CYMakeInstance(context, _class, Instance::Permanent);
2171 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2172 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2174 const char **data(objc_copyClassNamesForImage(internal, &size));
2175 for (size_t i(0); i != size; ++i)
2176 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2180 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2182 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2185 const char **data(objc_copyImageNames(&size));
2186 pool.atexit(free, data);
2188 for (size_t i(0); i != size; ++i)
2189 if (name == data[i]) {
2190 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2191 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2198 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2200 const char **data(objc_copyImageNames(&size));
2201 for (size_t i(0); i != size; ++i)
2202 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2207 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2209 const char *name(CYPoolCString(pool, context, property));
2210 if (Protocol *protocol = objc_getProtocol(name))
2211 return CYMakeInstance(context, protocol, Instance::Permanent);
2215 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2217 Protocol **data(objc_copyProtocolList(&size));
2218 for (size_t i(0); i != size; ++i)
2219 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2223 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2225 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2227 return CYJSNull(context);
2231 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2232 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2236 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2237 *data = reinterpret_cast<void *>(address);
2238 return KERN_SUCCESS;
2242 std::set<Class> query_;
2243 JSContextRef context_;
2244 JSObjectRef results_;
2247 struct CYObjectStruct {
2251 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2252 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2253 JSContextRef context(choice->context_);
2255 for (unsigned i(0); i != count; ++i) {
2256 vm_range_t &range(ranges[i]);
2257 void *data(reinterpret_cast<void *>(range.address));
2258 size_t size(range.size);
2260 if (size < sizeof(CYObjectStruct))
2263 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2264 #if defined(__APPLE__) && defined(__LP64__)
2265 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2267 Class isa(reinterpret_cast<Class>(pointers[0]));
2270 std::set<Class>::const_iterator result(choice->query_.find(isa));
2271 if (result == choice->query_.end())
2274 size_t needed(class_getInstanceSize(*result));
2275 // XXX: if (size < needed)
2277 size_t boundary(496);
2281 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2283 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2287 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2289 throw CYJSError(context, "choose() takes a class argument");
2291 CYGarbageCollect(context);
2294 id _class(CYCastNSObject(&pool, context, arguments[0]));
2296 vm_address_t *zones(NULL);
2298 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2299 _assert(error == KERN_SUCCESS);
2301 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2302 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2305 choice.context_ = context;
2306 choice.results_ = results;
2309 Class *classes(CYCopyClassList(number));
2310 _assert(classes != NULL);
2312 for (size_t i(0); i != number; ++i)
2313 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2314 if (current == _class) {
2315 choice.query_.insert(classes[i]);
2321 for (unsigned i(0); i != size; ++i) {
2322 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2323 if (zone == NULL || zone->introspect == NULL)
2326 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2334 #if defined(__i386__) || defined(__x86_64__)
2335 #define OBJC_MAX_STRUCT_BY_VALUE 8
2336 static int struct_forward_array[] = {
2337 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2338 #elif defined(__arm__)
2339 #define OBJC_MAX_STRUCT_BY_VALUE 1
2340 static int struct_forward_array[] = {
2342 #elif defined(__arm64__)
2345 #error missing objc-runtime-info
2349 static bool stret(ffi_type *ffi_type) {
2350 return ffi_type->type == FFI_TYPE_STRUCT && (
2351 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2352 struct_forward_array[ffi_type->size] != 0
2360 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2364 _class = object_getClass(self);
2368 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2369 imp = method_getImplementation(method);
2370 type = method_getTypeEncoding(method);
2375 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2376 type = CYPoolCString(pool, context, [method _typeString]);
2382 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2389 sig::Signature signature;
2390 sig::Parse(pool, &signature, type, &Structor_);
2393 sig::sig_ffi_cif(pool, 0, signature, &cif);
2397 if (stret(cif.rtype))
2398 imp = class_getMethodImplementation_stret(_class, _cmd);
2401 imp = class_getMethodImplementation(_class, _cmd);
2404 void (*function)() = reinterpret_cast<void (*)()>(imp);
2405 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, true, signature, &cif, function);
2408 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2410 throw CYJSError(context, "too few arguments to objc_msgSend");
2420 if (JSValueIsObjectOfClass(context, arguments[0], cy::Super::Class_)) {
2421 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2422 self = internal->value_;
2423 _class = internal->class_;;
2424 uninitialized = false;
2425 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2426 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2427 self = internal->value_;
2429 uninitialized = internal->IsUninitialized();
2431 internal->value_ = nil;
2433 self = CYCastNSObject(&pool, context, arguments[0]);
2435 uninitialized = false;
2439 return CYJSNull(context);
2441 _cmd = CYCastSEL(context, arguments[1]);
2443 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2446 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2447 return $objc_msgSend(context, object, _this, count, arguments);
2450 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2451 JSValueRef setup[count + 2];
2454 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2455 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2458 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2460 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2462 // XXX: handle Instance::Uninitialized?
2463 id self(CYCastNSObject(&pool, context, _this));
2467 setup[1] = &internal->sel_;
2469 return CYCallFunction(pool, context, 2, setup, count, arguments, false, true, internal->signature_, &internal->cif_, internal->value_);
2472 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2474 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2476 id self(CYCastNSObject(&pool, context, arguments[0]));
2477 Class _class(CYCastClass(pool, context, arguments[1]));
2478 return cy::Super::Make(context, self, _class);
2481 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2483 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2485 const char *name(CYPoolCString(pool, context, arguments[0]));
2486 return Selector_privateData::Make(context, sel_registerName(name));
2489 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2491 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2492 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2495 static JSValueRef Selector_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2496 return CYMakeType(context, sig::Selector());
2499 static JSValueRef Instance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2500 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2501 id self(internal->value_);
2502 if (CYIsClass(self))
2503 return CYMakeType(context, sig::Meta());
2504 return CYMakeType(context, sig::Object(class_getName(object_getClass(self))));
2507 static JSValueRef FunctionInstance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2508 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2511 if (!CYBlockSignature(pool, internal->value_, type.signature))
2512 return CYJSNull(context);
2513 return CYMakeType(context, type);
2516 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2517 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2518 return CYMakeInstance(context, object_getClass(internal->value_), Instance::Permanent);
2521 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2522 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2523 id self(internal->value_);
2524 if (!CYIsClass(self))
2525 return CYJSUndefined(context);
2526 return CYGetClassPrototype(context, self);
2529 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2530 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2531 id self(internal->value_);
2532 if (!CYIsClass(self))
2533 return CYJSUndefined(context);
2534 return Messages::Make(context, (Class) self);
2537 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2538 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2540 if (!CYJSValueIsNSObject(context, _this))
2543 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2544 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->value_, false, objects)));
2547 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2548 if (!CYJSValueIsNSObject(context, _this))
2551 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2552 id value(internal->value_);
2559 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2561 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2562 return CYJSUndefined(context);
2563 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2566 return CYCastJSValue(context, CYJSString(context, [value description]));
2568 } CYCatch(NULL) return /*XXX*/ NULL; }
2570 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2571 if (!CYJSValueIsNSObject(context, _this))
2574 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2575 id value(internal->value_);
2576 _assert(value != nil);
2578 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2581 if (JSValueRef result = [value cy$valueOfInContext:context])
2585 } CYCatch(NULL) return /*XXX*/ NULL; }
2587 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2588 if (!CYJSValueIsNSObject(context, _this))
2591 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2592 // XXX: but... but... THIS ISN'T A POINTER! :(
2593 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2594 } CYCatch(NULL) return /*XXX*/ NULL; }
2596 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2597 if (!CYJSValueIsNSObject(context, _this))
2600 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2601 id value(internal->value_);
2604 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2605 return CYCastJSValue(context, CYJSString(context, [value description]));
2607 } CYCatch(NULL) return /*XXX*/ NULL; }
2609 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2610 if (!CYJSValueIsNSObject(context, _this))
2613 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2614 id value(internal->value_);
2616 if (!CYIsClass(value))
2617 CYThrow("non-Class object cannot be used as Type");
2619 sig::Object type(class_getName(value));
2620 return CYMakeType(context, type);
2621 } CYCatch(NULL) return /*XXX*/ NULL; }
2623 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2624 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2625 return CYCastJSValue(context, sel_getName(internal->value_));
2628 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2629 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2632 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2633 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2634 const char *name(sel_getName(internal->value_));
2637 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2638 return CYCastJSValue(context, CYJSString(context, string));
2640 } CYCatch(NULL) return /*XXX*/ NULL; }
2642 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2644 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2647 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2648 SEL sel(internal->value_);
2650 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2651 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2652 const char *encoding(method_getTypeEncoding(method));
2654 sig::Function type(false);
2655 sig::Parse(pool, &type.signature, encoding, &Structor_);
2656 return CYMakeType(context, type);
2659 static JSStaticValue Selector_staticValues[2] = {
2660 {"$cyt", &Selector_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2661 {NULL, NULL, NULL, 0}
2664 static JSStaticValue Instance_staticValues[5] = {
2665 {"$cyt", &Instance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2666 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2667 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2668 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2669 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2670 {NULL, NULL, NULL, 0}
2673 static JSStaticValue FunctionInstance_staticValues[5] = {
2674 {"$cyt", &FunctionInstance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2675 // XXX: this is sadly a duplicate of Instance_staticValues
2676 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2677 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2678 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2679 {NULL, NULL, NULL, 0}
2682 static JSStaticFunction Instance_staticFunctions[6] = {
2683 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2684 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2685 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2686 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2687 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2691 static JSStaticFunction Class_staticFunctions[2] = {
2692 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2696 static JSStaticFunction Interior_staticFunctions[2] = {
2697 {"$cya", &Interior_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2701 static JSStaticFunction Selector_staticFunctions[5] = {
2702 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2703 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2704 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2705 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2710 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2711 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2712 } CYObjectiveCatch }
2715 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2716 NSArray_ = objc_getClass("NSArray");
2717 NSBlock_ = objc_getClass("NSBlock");
2718 NSDictionary_ = objc_getClass("NSDictionary");
2719 NSNumber_ = objc_getClass("NSNumber");
2720 NSString_ = objc_getClass("NSString");
2721 Object_ = objc_getClass("Object");
2724 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2726 // XXX: apparently, iOS now has both of these
2727 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2728 if (NSCFBoolean_ == nil)
2729 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2731 NSCFType_ = objc_getClass("NSCFType");
2733 NSZombie_ = objc_getClass("_NSZombie_");
2735 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2736 NSZombie_ = objc_getClass("NSZombie");
2739 JSClassDefinition definition;
2741 definition = kJSClassDefinitionEmpty;
2742 definition.className = "Instance";
2743 definition.staticValues = Instance_staticValues;
2744 definition.staticFunctions = Instance_staticFunctions;
2745 definition.hasProperty = &Instance_hasProperty;
2746 definition.getProperty = &Instance_getProperty;
2747 definition.setProperty = &Instance_setProperty;
2748 definition.deleteProperty = &Instance_deleteProperty;
2749 definition.getPropertyNames = &Instance_getPropertyNames;
2750 definition.callAsConstructor = &Instance_callAsConstructor;
2751 definition.hasInstance = &Instance_hasInstance;
2752 definition.finalize = &CYFinalize;
2753 Instance::Class_ = JSClassCreate(&definition);
2755 definition.className = "ArrayInstance";
2756 ArrayInstance_ = JSClassCreate(&definition);
2758 definition.className = "BooleanInstance";
2759 BooleanInstance_ = JSClassCreate(&definition);
2761 definition.className = "NumberInstance";
2762 NumberInstance_ = JSClassCreate(&definition);
2764 definition.className = "ObjectInstance";
2765 ObjectInstance_ = JSClassCreate(&definition);
2767 definition.className = "StringInstance";
2768 StringInstance_ = JSClassCreate(&definition);
2770 definition.className = "FunctionInstance";
2771 definition.staticValues = FunctionInstance_staticValues;
2772 definition.callAsFunction = &FunctionInstance_callAsFunction;
2773 FunctionInstance_ = JSClassCreate(&definition);
2775 definition = kJSClassDefinitionEmpty;
2776 definition.className = "Class";
2777 definition.staticFunctions = Class_staticFunctions;
2778 ClassInstance_ = JSClassCreate(&definition);
2780 definition = kJSClassDefinitionEmpty;
2781 definition.className = "Interior";
2782 definition.staticFunctions = Interior_staticFunctions;
2783 definition.hasProperty = &Interior_hasProperty;
2784 definition.getProperty = &Interior_getProperty;
2785 definition.setProperty = &Interior_setProperty;
2786 definition.getPropertyNames = &Interior_getPropertyNames;
2787 definition.finalize = &CYFinalize;
2788 Interior::Class_ = JSClassCreate(&definition);
2790 definition = kJSClassDefinitionEmpty;
2791 definition.className = "Message";
2792 definition.staticFunctions = cy::Functor::StaticFunctions;
2793 definition.staticValues = cy::Functor::StaticValues;
2794 definition.callAsFunction = &Message_callAsFunction;
2795 definition.finalize = &CYFinalize;
2796 Message_privateData::Class_ = JSClassCreate(&definition);
2798 definition = kJSClassDefinitionEmpty;
2799 definition.className = "Messages";
2800 definition.hasProperty = &Messages_hasProperty;
2801 definition.getProperty = &Messages_getProperty;
2802 definition.setProperty = &Messages_setProperty;
2803 definition.getPropertyNames = &Messages_getPropertyNames;
2804 definition.finalize = &CYFinalize;
2805 Messages::Class_ = JSClassCreate(&definition);
2807 definition = kJSClassDefinitionEmpty;
2808 definition.className = "Selector";
2809 definition.staticValues = Selector_staticValues;
2810 definition.staticFunctions = Selector_staticFunctions;
2811 definition.callAsFunction = &Selector_callAsFunction;
2812 definition.finalize = &CYFinalize;
2813 Selector_privateData::Class_ = JSClassCreate(&definition);
2815 definition = kJSClassDefinitionEmpty;
2816 definition.className = "Super";
2817 definition.finalize = &CYFinalize;
2818 cy::Super::Class_ = JSClassCreate(&definition);
2820 definition = kJSClassDefinitionEmpty;
2821 definition.className = "ObjectiveC::Classes";
2822 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2823 definition.getProperty = &ObjectiveC_Classes_getProperty;
2824 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2825 ObjectiveC_Classes_ = JSClassCreate(&definition);
2827 definition = kJSClassDefinitionEmpty;
2828 definition.className = "ObjectiveC::Constants";
2829 definition.getProperty = &ObjectiveC_Constants_getProperty;
2830 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2831 ObjectiveC_Constants_ = JSClassCreate(&definition);
2834 definition = kJSClassDefinitionEmpty;
2835 definition.className = "ObjectiveC::Images";
2836 definition.getProperty = &ObjectiveC_Images_getProperty;
2837 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2838 ObjectiveC_Images_ = JSClassCreate(&definition);
2840 definition = kJSClassDefinitionEmpty;
2841 definition.className = "ObjectiveC::Image::Classes";
2842 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2843 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2844 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2847 definition = kJSClassDefinitionEmpty;
2848 definition.className = "ObjectiveC::Protocols";
2849 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2850 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2851 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2854 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2855 // XXX: this is horrible; there has to be a better way to do this
2857 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2859 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2865 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2866 JSObjectRef global(CYGetGlobalObject(context));
2867 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2868 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2869 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2870 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2872 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2873 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2875 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2876 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2877 CYArrayPush(context, alls, protocols);
2879 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2880 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2881 CYArrayPush(context, alls, classes);
2883 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2884 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2885 CYArrayPush(context, alls, constants);
2888 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2891 JSObjectRef Message(JSObjectMakeConstructor(context, Message_privateData::Class_, NULL));
2892 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_privateData::Class_, &Selector_new));
2893 JSObjectRef Super(JSObjectMakeConstructor(context, cy::Super::Class_, &Super_new));
2895 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance::Class_, &Instance_new));
2896 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2897 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2899 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2900 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2901 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2902 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2903 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2905 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2906 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2907 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2908 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2909 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2911 JSObjectRef ClassInstance(JSObjectMakeConstructor(context, ClassInstance_, NULL));
2912 JSObjectRef ClassInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ClassInstance, prototype_s)));
2913 CYSetProperty(context, cy, CYJSString("ClassInstance_prototype"), ClassInstance_prototype);
2914 // XXX: this doesn't fit the pattern of the other ones; maybe it sort of should?
2915 CYSetPrototype(context, ClassInstance_prototype, Instance_prototype);
2917 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2918 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2919 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2920 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2921 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2923 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2924 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2925 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2926 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2927 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2929 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2930 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2931 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2932 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2933 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2935 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2936 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2937 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2938 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2939 CYSetPrototype(context, StringInstance_prototype, String_prototype);
2941 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2942 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2943 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
2945 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2946 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
2949 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2952 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2954 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2955 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2957 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
2958 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
2959 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
2960 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::Object()), kJSPropertyAttributeDontEnum);
2961 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::Meta()), kJSPropertyAttributeDontEnum);
2962 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::Selector()), kJSPropertyAttributeDontEnum);
2965 static void *CYObjectiveC_CastSymbol(const char *name) {
2967 #ifdef __GNU_LIBOBJC__
2968 else if (strcmp(name, "object_getClass") == 0)
2969 return reinterpret_cast<void *>(&object_getClass);
2974 static CYHook CYObjectiveCHook = {
2975 &CYObjectiveC_ExecuteStart,
2976 &CYObjectiveC_ExecuteEnd,
2977 &CYObjectiveC_CallFunction,
2978 &CYObjectiveC_Initialize,
2979 &CYObjectiveC_SetupContext,
2980 &CYObjectiveC_CastSymbol,
2983 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
2985 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
2986 CYSetupContext(context);
2987 } CYObjectiveCatch }
2989 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
2992 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
2993 utf8 = CYPoolCode(pool, utf8);
2995 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
2996 size_t bytes(utf16.size * sizeof(uint16_t));
2997 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
2998 memcpy(copy, utf16.data, bytes);
3002 } catch (const CYException &exception) {
3004 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];