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>
48 #include "JavaScript.hpp"
50 #include "Execute.hpp"
52 #include "ObjectiveC/Internal.hpp"
54 #define CYObjectiveTry_ { \
56 #define CYObjectiveTry { \
57 JSContextRef context(context_); \
59 #define CYObjectiveCatch \
60 catch (const CYException &error) { \
61 @throw CYCastNSObject(NULL, context, error.CastJSValue(context, "Error")); \
67 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
69 #define CYPoolCatch(value) \
70 @catch (NSException *error) { \
71 _saved = [error retain]; \
72 throw CYJSError(context, CYCastJSValue(context, error)); \
77 [_saved autorelease]; \
83 #define CYSadCatch(value) \
84 @catch (NSException *error ) { \
85 throw CYJSError(context, CYCastJSValue(context, error)); \
89 #define _oassert(test) \
91 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"_assert(" #test ")" userInfo:nil];
99 void (*invoke)(void *, ...);
103 struct BlockDescriptor1 {
104 unsigned long int reserved;
105 unsigned long int size;
108 struct BlockDescriptor2 {
109 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
110 void (*dispose_helper)(BlockLiteral *src);
113 struct BlockDescriptor3 {
114 const char *signature;
119 BLOCK_DEALLOCATING = 0x0001,
120 BLOCK_REFCOUNT_MASK = 0xfffe,
121 BLOCK_NEEDS_FREE = 1 << 24,
122 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
123 BLOCK_HAS_CTOR = 1 << 26,
124 BLOCK_IS_GC = 1 << 27,
125 BLOCK_IS_GLOBAL = 1 << 28,
126 BLOCK_HAS_STRET = 1 << 29,
127 BLOCK_HAS_SIGNATURE = 1 << 30,
130 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
132 /* Objective-C Pool Release {{{ */
133 void CYPoolRelease_(void *data) {
134 id object(reinterpret_cast<id>(data));
138 id CYPoolRelease_(CYPool *pool, id object) {
141 else if (pool == NULL)
142 return [object autorelease];
144 pool->atexit(CYPoolRelease_);
149 template <typename Type_>
150 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
151 return (Type_) CYPoolRelease_(pool, (id) object);
154 /* Objective-C Strings {{{ */
155 CYUTF8String CYPoolUTF8String(CYPool &pool, JSContextRef context, NSString *value) {
156 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
157 char *string(new(pool) char[size + 1]);
158 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
159 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
160 return CYUTF8String(string, [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
163 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
164 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
165 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
170 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
171 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
175 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
178 // XXX: this definition scares me; is anyone using this?!
179 NSString *string([value description]);
181 return CYCopyJSString(context, string);
184 return CYCopyJSString(CYPoolUTF8String(pool, context, string));
188 NSString *CYCopyNSString(const CYUTF8String &value) {
190 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
192 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
196 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
198 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
201 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
205 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
206 return CYCopyNSString(context, CYJSString(context, value));
209 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
210 return CYPoolRelease(pool, CYCopyNSString(value));
213 NSString *CYCastNSString(CYPool *pool, SEL sel) {
214 const char *name(sel_getName(sel));
215 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
218 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
219 return CYPoolRelease(pool, CYCopyNSString(context, value));
222 CYUTF8String CYCastUTF8String(NSString *value) {
223 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
224 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
228 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
230 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
231 if (exception == NULL)
233 *exception = CYCastJSValue(context, error);
236 size_t CYGetIndex(NSString *value) {
237 return CYGetIndex(CYCastUTF8String(value));
240 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
241 return CYGetOffset(CYPoolCString(pool, context, value), index);
244 static JSClassRef Instance_;
246 static JSClassRef ArrayInstance_;
247 static JSClassRef BooleanInstance_;
248 static JSClassRef FunctionInstance_;
249 static JSClassRef NumberInstance_;
250 static JSClassRef ObjectInstance_;
251 static JSClassRef StringInstance_;
253 static JSClassRef Class_;
254 static JSClassRef Internal_;
255 static JSClassRef Message_;
256 static JSClassRef Messages_;
257 static JSClassRef Selector_;
258 static JSClassRef Super_;
260 static JSClassRef ObjectiveC_Classes_;
261 static JSClassRef ObjectiveC_Constants_;
262 static JSClassRef ObjectiveC_Protocols_;
265 static JSClassRef ObjectiveC_Image_Classes_;
266 static JSClassRef ObjectiveC_Images_;
270 static Class __NSMallocBlock__;
271 static Class NSCFBoolean_;
272 static Class NSCFType_;
273 static Class NSGenericDeallocHandler_;
275 static Class NSBoolNumber_;
278 static Class NSArray_;
279 static Class NSBlock_;
280 static Class NSDictionary_;
281 static Class NSNumber_;
282 static Class NSString_;
283 static Class NSZombie_;
284 static Class Object_;
286 static Type_privateData *Object_type;
287 static Type_privateData *Selector_type;
289 Type_privateData *Instance::GetType() const {
293 Type_privateData *Selector_privateData::GetType() const {
294 return Selector_type;
297 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
299 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
301 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
302 else if (meta && !class_isMetaClass(self))
303 return CYGetCachedObject(context, CYJSString("Class_prototype"));
305 JSObjectRef global(CYGetGlobalObject(context));
306 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
309 sprintf(label, "i%p", self);
310 CYJSString name(label);
312 JSValueRef value(CYGetProperty(context, cy, name));
313 if (!JSValueIsUndefined(context, value))
316 JSClassRef _class(NULL);
317 JSValueRef prototype;
320 if (self == NSCFBoolean_)
322 if (self == NSBoolNumber_)
324 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
325 else if (self == NSArray_)
326 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
327 else if (self == NSBlock_)
328 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
329 else if (self == NSNumber_)
330 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
331 else if (self == NSDictionary_)
332 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
333 else if (self == NSString_)
334 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
336 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
338 JSObjectRef object(JSObjectMake(context, _class, NULL));
339 CYSetPrototype(context, object, prototype);
340 CYSetProperty(context, cy, name, object);
345 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
346 return CYGetClassPrototype(context, self, class_isMetaClass(self));
349 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
350 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
351 if (Class super = class_getSuperclass(_class))
352 CYSetPrototype(context, value, Messages::Make(context, super));
356 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
357 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
361 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
362 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
366 bool CYIsKindOfClass(id object, Class _class) {
367 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
373 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
374 JSObjectRef value(JSObjectMake(context, CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance_, new Instance(object, flags)));
375 CYSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
379 Instance::~Instance() {
380 if ((flags_ & Permanent) == 0)
381 [GetValue() release];
384 struct Message_privateData :
389 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
390 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
396 JSObjectRef CYMakeInstance(JSContextRef context, id object, Instance::Flags flags = Instance::None) {
397 _assert(object != nil);
400 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
402 if (weak != NULL && &JSWeakObjectMapGet != NULL)
403 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
407 if ((flags & Instance::Permanent) == 0)
408 object = [object retain];
410 JSObjectRef instance(Instance::Make(context, object, flags));
413 if (weak != NULL && &JSWeakObjectMapSet != NULL)
414 JSWeakObjectMapSet(context, weak, object, instance);
420 @interface NSMethodSignature (Cycript)
421 - (NSString *) _typeString;
424 @interface NSObject (Cycript)
426 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
427 - (JSType) cy$JSType;
429 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
430 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
432 - (bool) cy$hasProperty:(NSString *)name;
433 - (NSObject *) cy$getProperty:(NSString *)name;
434 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
435 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
436 - (bool) cy$deleteProperty:(NSString *)name;
437 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
439 + (bool) cy$hasImplicitProperties;
445 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
448 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
449 _assert(value != nil);
451 Class _class(object_getClass(value));
453 if (class_isMetaClass(_class)) {
454 const char *name(class_getName(value));
455 if (class_isMetaClass(value))
456 return [NSString stringWithFormat:@"object_getClass(%s)", name];
458 return [NSString stringWithUTF8String:name];
461 if (_class == NSZombie_)
462 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
464 SEL sel(@selector(cy$toCYON:inSet:));
466 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
467 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
468 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
469 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
470 return [value cy$toCYON:objective inSet:objects];
472 return [NSString stringWithFormat:@"%@", value];
475 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
477 return CYCastNSCYON(value, objective, *objects);
479 std::set<void *> objects;
480 return CYCastNSCYON(value, objective, objects);
484 struct PropertyAttributes {
489 const char *variable;
502 PropertyAttributes(objc_property_t property) :
514 name = property_getName(property);
515 const char *attributes(property_getAttributes(property));
517 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
518 if ((next = strchr(token, ',')) != NULL)
521 case 'R': readonly = true; break;
522 case 'C': copy = true; break;
523 case '&': retain = true; break;
524 case 'N': nonatomic = true; break;
525 case 'G': getter_ = token + 1; break;
526 case 'S': setter_ = token + 1; break;
527 case 'V': variable = token + 1; break;
531 /*if (variable == NULL) {
532 variable = property_getName(property);
533 size_t size(strlen(variable));
534 char *name(new(pool_) char[size + 2]);
536 memcpy(name + 1, variable, size);
537 name[size + 1] = '\0';
542 const char *Getter() {
544 getter_ = pool_.strdup(name);
548 const char *Setter() {
549 if (setter_ == NULL && !readonly) {
550 size_t length(strlen(name));
552 char *temp(new(pool_) char[length + 5]);
558 temp[3] = toupper(name[0]);
559 memcpy(temp + 4, name + 1, length - 1);
562 temp[length + 3] = ':';
563 temp[length + 4] = '\0';
572 @interface CYWebUndefined : NSObject {
575 + (CYWebUndefined *) undefined;
579 @implementation CYWebUndefined
581 + (CYWebUndefined *) undefined {
582 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
588 #define WebUndefined CYWebUndefined
590 /* Bridge: CYJSObject {{{ */
591 @interface CYJSObject : NSMutableDictionary {
593 JSGlobalContextRef context_;
596 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
598 - (NSUInteger) count;
599 - (id) objectForKey:(id)key;
600 - (NSEnumerator *) keyEnumerator;
601 - (void) setObject:(id)object forKey:(id)key;
602 - (void) removeObjectForKey:(id)key;
606 /* Bridge: CYJSArray {{{ */
607 @interface CYJSArray : NSMutableArray {
609 JSGlobalContextRef context_;
612 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
614 - (NSUInteger) count;
615 - (id) objectAtIndex:(NSUInteger)index;
617 - (void) addObject:(id)anObject;
618 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
619 - (void) removeLastObject;
620 - (void) removeObjectAtIndex:(NSUInteger)index;
621 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
626 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
627 return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
630 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
631 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
635 struct CYBlockDescriptor {
637 BlockDescriptor1 one_;
638 BlockDescriptor2 two_;
639 BlockDescriptor3 three_;
642 Closure_privateData *internal_;
645 void CYDisposeBlock(BlockLiteral *literal) {
646 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
649 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
650 JSObjectRef _this(CYCastJSObject(context, values[0]));
651 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
654 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
655 _assert(__NSMallocBlock__ != Nil);
656 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
658 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
659 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
661 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockAdapter_);
662 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
664 literal->isa = __NSMallocBlock__;
665 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
666 literal->reserved = 0;
667 literal->descriptor = descriptor;
669 descriptor->d_.one_.size = sizeof(descriptor->d_);
670 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
671 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
673 return reinterpret_cast<NSBlock *>(literal);
677 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
678 if (CYJSValueIsNSObject(context, object)) {
679 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
680 return internal->GetValue();
683 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
684 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
685 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
688 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
689 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
693 @interface NSBoolNumber : NSNumber {
698 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
702 switch (JSType type = JSValueGetType(context, value)) {
703 case kJSTypeUndefined:
704 object = [WebUndefined undefined];
714 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
717 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
723 object = CYCopyNSNumber(context, value);
728 object = CYCopyNSString(context, value);
733 // XXX: this might could be more efficient
734 object = CYCastNSObject(pool, context, (JSObjectRef) value);
739 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
746 return CYPoolRelease(pool, object);
748 return [object retain];
751 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
752 return CYNSObject(pool, context, value, true);
755 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
756 return CYNSObject(&pool, context, value, false);
759 /* Bridge: NSArray {{{ */
760 @implementation NSArray (Cycript)
763 return [[self mutableCopy] autorelease];
766 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
767 _oassert(objects.insert(self).second);
769 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
770 [json appendString:@"@["];
774 for (id object in self) {
776 for (size_t index(0), count([self count]); index != count; ++index) {
777 id object([self objectAtIndex:index]);
780 [json appendString:@","];
783 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
784 [json appendString:CYCastNSCYON(object, true, objects)];
786 [json appendString:@","];
791 [json appendString:@"]"];
795 - (bool) cy$hasProperty:(NSString *)name {
796 if ([name isEqualToString:@"length"])
799 size_t index(CYGetIndex(name));
800 if (index == _not(size_t) || index >= [self count])
801 return [super cy$hasProperty:name];
806 - (NSObject *) cy$getProperty:(NSString *)name {
807 size_t index(CYGetIndex(name));
808 if (index == _not(size_t) || index >= [self count])
809 return [super cy$getProperty:name];
811 return [self objectAtIndex:index];
814 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
816 if ([name isEqualToString:@"length"])
817 return CYCastJSValue(context, [self count]);
820 return [super cy$getProperty:name inContext:context];
823 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
824 [super cy$getPropertyNames:names inContext:context];
826 for (size_t index(0), count([self count]); index != count; ++index) {
827 id object([self objectAtIndex:index]);
828 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
830 sprintf(name, "%zu", index);
831 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
836 + (bool) cy$hasImplicitProperties {
842 /* Bridge: NSBlock {{{ */
849 /* Bridge: NSBoolNumber {{{ */
851 @implementation NSBoolNumber (Cycript)
853 - (JSType) cy$JSType {
854 return kJSTypeBoolean;
857 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
858 NSString *value([self boolValue] ? @"true" : @"false");
859 return objective ? value : [NSString stringWithFormat:@"@%@", value];
862 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
863 return CYCastJSValue(context, (bool) [self boolValue]);
869 /* Bridge: NSDictionary {{{ */
870 @implementation NSDictionary (Cycript)
873 return [[self mutableCopy] autorelease];
876 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
877 _oassert(objects.insert(self).second);
879 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
880 [json appendString:@"@{"];
884 for (NSObject *key in self) {
886 NSEnumerator *keys([self keyEnumerator]);
887 while (NSObject *key = [keys nextObject]) {
890 [json appendString:@","];
893 [json appendString:CYCastNSCYON(key, true, objects)];
894 [json appendString:@":"];
895 NSObject *object([self objectForKey:key]);
896 [json appendString:CYCastNSCYON(object, true, objects)];
899 [json appendString:@"}"];
903 - (bool) cy$hasProperty:(NSString *)name {
904 return [self objectForKey:name] != nil;
907 - (NSObject *) cy$getProperty:(NSString *)name {
908 return [self objectForKey:name];
911 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
912 [super cy$getPropertyNames:names inContext:context];
915 for (NSObject *key in self) {
917 NSEnumerator *keys([self keyEnumerator]);
918 while (NSObject *key = [keys nextObject]) {
920 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
924 + (bool) cy$hasImplicitProperties {
930 /* Bridge: NSMutableArray {{{ */
931 @implementation NSMutableArray (Cycript)
933 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
934 if ([name isEqualToString:@"length"]) {
935 // XXX: is this not intelligent?
936 NSNumber *number(reinterpret_cast<NSNumber *>(value));
937 NSUInteger size([number unsignedIntegerValue]);
938 NSUInteger count([self count]);
940 [self removeObjectsInRange:NSMakeRange(size, count - size)];
941 else if (size != count) {
942 WebUndefined *undefined([WebUndefined undefined]);
943 for (size_t i(count); i != size; ++i)
944 [self addObject:undefined];
949 size_t index(CYGetIndex(name));
950 if (index == _not(size_t))
951 return [super cy$setProperty:name to:value];
953 id object(value ?: [NSNull null]);
955 size_t count([self count]);
957 [self replaceObjectAtIndex:index withObject:object];
959 if (index != count) {
960 WebUndefined *undefined([WebUndefined undefined]);
961 for (size_t i(count); i != index; ++i)
962 [self addObject:undefined];
965 [self addObject:object];
971 - (bool) cy$deleteProperty:(NSString *)name {
972 size_t index(CYGetIndex(name));
973 if (index == _not(size_t) || index >= [self count])
974 return [super cy$deleteProperty:name];
975 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
981 /* Bridge: NSMutableDictionary {{{ */
982 @implementation NSMutableDictionary (Cycript)
984 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
985 [self setObject:(value ?: [NSNull null]) forKey:name];
989 - (bool) cy$deleteProperty:(NSString *)name {
990 if ([self objectForKey:name] == nil)
993 [self removeObjectForKey:name];
1000 /* Bridge: NSNumber {{{ */
1001 @implementation NSNumber (Cycript)
1003 - (JSType) cy$JSType {
1005 // XXX: this just seems stupid
1006 if ([self class] == NSCFBoolean_)
1007 return kJSTypeBoolean;
1009 return kJSTypeNumber;
1012 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1013 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1014 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1017 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1018 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1019 } CYObjectiveCatch }
1023 /* Bridge: NSNull {{{ */
1024 @implementation NSNull (Cycript)
1026 - (JSType) cy$JSType {
1030 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1031 NSString *value(@"null");
1032 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1035 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1036 return CYJSNull(context);
1037 } CYObjectiveCatch }
1041 /* Bridge: NSObject {{{ */
1042 @implementation NSObject (Cycript)
1048 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1049 return [self cy$valueOfInContext:context];
1052 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1054 } CYObjectiveCatch }
1056 - (JSType) cy$JSType {
1057 return kJSTypeObject;
1060 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1061 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1064 - (bool) cy$hasProperty:(NSString *)name {
1068 - (NSObject *) cy$getProperty:(NSString *)name {
1072 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1073 if (NSObject *value = [self cy$getProperty:name])
1074 return CYCastJSValue(context, value);
1076 } CYObjectiveCatch }
1078 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1082 - (bool) cy$deleteProperty:(NSString *)name {
1086 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1089 + (bool) cy$hasImplicitProperties {
1095 /* Bridge: NSOrderedSet {{{ */
1097 @implementation NSOrderedSet (Cycript)
1099 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1100 _oassert(objects.insert(self).second);
1102 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1103 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1104 [json appendString:CYCastNSCYON([self array], true, objects)];
1105 [json appendString:@"]]"];
1112 /* Bridge: NSProxy {{{ */
1113 @implementation NSProxy (Cycript)
1115 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1116 return [[self description] cy$toCYON:objective inSet:objects];
1121 /* Bridge: NSSet {{{ */
1122 @implementation NSSet (Cycript)
1124 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1125 _oassert(objects.insert(self).second);
1127 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1128 [json appendString:@"[NSSet setWithArray:"];
1129 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1130 [json appendString:@"]]"];
1136 /* Bridge: NSString {{{ */
1137 @implementation NSString (Cycript)
1140 return [[self copy] autorelease];
1143 - (JSType) cy$JSType {
1144 return kJSTypeString;
1147 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1148 std::ostringstream str;
1151 CYUTF8String string(CYCastUTF8String(self));
1152 CYStringify(str, string.data, string.size, true);
1153 std::string value(str.str());
1154 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1157 - (bool) cy$hasProperty:(NSString *)name {
1158 size_t index(CYGetIndex(name));
1159 if (index == _not(size_t) || index >= [self length])
1160 return [super cy$hasProperty:name];
1165 - (NSObject *) cy$getProperty:(NSString *)name {
1166 size_t index(CYGetIndex(name));
1167 if (index == _not(size_t) || index >= [self length])
1168 return [super cy$getProperty:name];
1170 return [self substringWithRange:NSMakeRange(index, 1)];
1173 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1174 [super cy$getPropertyNames:names inContext:context];
1176 for (size_t index(0), length([self length]); index != length; ++index) {
1178 sprintf(name, "%zu", index);
1179 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1183 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1184 return CYCastJSValue(context, CYJSString(context, self));
1185 } CYObjectiveCatch }
1189 /* Bridge: WebUndefined {{{ */
1190 @implementation WebUndefined (Cycript)
1192 - (JSType) cy$JSType {
1193 return kJSTypeUndefined;
1196 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1197 NSString *value(@"undefined");
1198 return value; // XXX: maybe use the below code, adding @undefined?
1199 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1202 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1203 return CYJSUndefined(context);
1204 } CYObjectiveCatch }
1209 static bool CYIsClass(id self) {
1210 return class_isMetaClass(object_getClass(self));
1213 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1214 id self(CYCastNSObject(&pool, context, value));
1215 if (CYIsClass(self))
1216 return (Class) self;
1217 throw CYJSError(context, "got something that is not a Class");
1221 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1223 size_t size(JSPropertyNameArrayGetCount(names));
1224 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1225 for (size_t index(0); index != size; ++index)
1226 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1230 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1232 return CYJSNull(context);
1234 return CYMakeInstance(context, value);
1235 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1237 @implementation CYJSObject
1239 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1240 if ((self = [super init]) != nil) {
1242 context_ = CYGetJSContext(context);
1243 JSGlobalContextRetain(context_);
1244 JSValueProtect(context_, object_);
1246 } CYObjectiveCatch }
1248 - (void) dealloc { CYObjectiveTry {
1249 JSValueUnprotect(context_, object_);
1250 JSGlobalContextRelease(context_);
1252 } CYObjectiveCatch }
1254 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1256 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1258 return [super cy$toCYON:objective inSet:objects];
1260 return [NSString stringWithUTF8String:cyon];
1261 } CYObjectiveCatch }
1263 - (NSUInteger) count { CYObjectiveTry {
1264 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1265 size_t size(JSPropertyNameArrayGetCount(names));
1266 JSPropertyNameArrayRelease(names);
1268 } CYObjectiveCatch }
1270 - (id) objectForKey:(id)key { CYObjectiveTry {
1271 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1272 if (JSValueIsUndefined(context, value))
1274 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1275 } CYObjectiveCatch }
1277 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1278 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1279 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1280 JSPropertyNameArrayRelease(names);
1282 } CYObjectiveCatch }
1284 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1285 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1286 } CYObjectiveCatch }
1288 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1289 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1290 } CYObjectiveCatch }
1294 @implementation CYJSArray
1296 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1298 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1299 } CYObjectiveCatch }
1301 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1302 if ((self = [super init]) != nil) {
1304 context_ = CYGetJSContext(context);
1305 JSGlobalContextRetain(context_);
1306 JSValueProtect(context_, object_);
1308 } CYObjectiveCatch }
1310 - (void) dealloc { CYObjectiveTry {
1311 JSValueUnprotect(context_, object_);
1312 JSGlobalContextRelease(context_);
1314 } CYObjectiveCatch }
1316 - (NSUInteger) count { CYObjectiveTry {
1317 return CYArrayLength(context, object_);
1318 } CYObjectiveCatch }
1320 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1321 size_t bounds([self count]);
1322 if (index >= bounds)
1323 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1324 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1325 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1326 } CYObjectiveCatch }
1328 - (void) addObject:(id)object { CYObjectiveTry {
1329 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1330 } CYObjectiveCatch }
1332 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1333 size_t bounds([self count] + 1);
1334 if (index >= bounds)
1335 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1336 JSValueRef arguments[3];
1337 arguments[0] = CYCastJSValue(context, index);
1338 arguments[1] = CYCastJSValue(context, 0);
1339 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1340 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1341 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1342 } CYObjectiveCatch }
1344 - (void) removeLastObject { CYObjectiveTry {
1345 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1346 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1347 } CYObjectiveCatch }
1349 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1350 size_t bounds([self count]);
1351 if (index >= bounds)
1352 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1353 JSValueRef arguments[2];
1354 arguments[0] = CYCastJSValue(context, index);
1355 arguments[1] = CYCastJSValue(context, 1);
1356 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1357 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1358 } CYObjectiveCatch }
1360 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1361 size_t bounds([self count]);
1362 if (index >= bounds)
1363 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1364 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1365 } CYObjectiveCatch }
1369 // XXX: inherit from or replace with CYJSObject
1370 @interface CYInternal : NSObject {
1371 JSGlobalContextRef context_;
1372 JSObjectRef object_;
1377 @implementation CYInternal
1379 - (void) dealloc { CYObjectiveTry {
1380 JSValueUnprotect(context_, object_);
1381 JSGlobalContextRelease(context_);
1383 } CYObjectiveCatch }
1385 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1386 if ((self = [super init]) != nil) {
1387 context_ = CYGetJSContext(context);
1388 JSGlobalContextRetain(context_);
1390 } CYObjectiveCatch }
1392 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1393 if (object_ == NULL)
1396 return JSObjectHasProperty(context, object_, name);
1399 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1400 if (object_ == NULL)
1403 return CYGetProperty(context, object_, name);
1406 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1407 @synchronized (self) {
1408 if (object_ == NULL) {
1409 object_ = JSObjectMake(context, NULL, NULL);
1410 JSValueProtect(context, object_);
1414 CYSetProperty(context, object_, name, value);
1417 + (CYInternal *) get:(id)object {
1419 if (&objc_getAssociatedObject == NULL)
1422 @synchronized (object) {
1423 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1431 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1433 if (&objc_getAssociatedObject == NULL)
1436 @synchronized (object) {
1437 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1440 if (&objc_setAssociatedObject == NULL)
1443 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1444 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1454 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1455 Selector_privateData *internal(new Selector_privateData(sel));
1456 return JSObjectMake(context, Selector_, internal);
1459 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1460 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1461 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1462 return reinterpret_cast<SEL>(internal->value_);
1465 return sel_registerName(CYPoolCString(pool, context, value));
1469 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1470 return (void *) [[NSAutoreleasePool alloc] init];
1471 } CYSadCatch(NULL) }
1473 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1474 return [(NSAutoreleasePool *) handle release];
1477 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1478 CYCallFunction(pool, context, cif, function, value, values);
1482 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, sig::Signature *signature) {
1483 if (JSValueIsNull(context, value))
1485 JSObjectRef object(CYCastJSObject(context, value));
1487 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1488 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1490 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1491 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1495 _assert(JSObjectIsFunction(context, object));
1497 _assert(signature != NULL);
1498 _assert(signature->count != 0);
1500 sig::Signature modified;
1501 modified.count = signature->count + 1;
1502 modified.elements = new(pool) sig::Element[modified.count];
1504 modified.elements[0] = signature->elements[0];
1505 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1507 modified.elements[1].name = NULL;
1508 modified.elements[1].type = new(pool) sig::Type();
1509 modified.elements[1].offset = _not(size_t);
1511 memset(modified.elements[1].type, 0, sizeof(sig::Type));
1512 modified.elements[1].type->primitive = sig::object_P;
1514 return CYMakeBlock(context, object, modified);
1518 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1519 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1521 switch (type->primitive) {
1524 // XXX: this function might not handle the idea of a null pool
1525 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &type->data.signature);
1530 case sig::typename_P:
1531 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1534 case sig::selector_P:
1535 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1543 } CYSadCatch(false) }
1545 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1546 switch (type->primitive) {
1547 // XXX: do something epic about blocks
1550 if (NSObject *value = *reinterpret_cast<NSObject **>(data)) {
1551 JSObjectRef object(CYMakeInstance(context, value));
1554 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1556 if ((internal->flags_ & Instance::Uninitialized) != 0) {
1557 internal->flags_ = static_cast<Instance::Flags>(internal->flags_ & ~Instance::Uninitialized);
1558 _assert(internal->value_ == nil);
1559 internal->value_ = value;
1568 case sig::typename_P:
1569 if (Class value = *reinterpret_cast<Class *>(data))
1570 return CYMakeInstance(context, value, Instance::Permanent);
1573 case sig::selector_P:
1574 if (SEL value = *reinterpret_cast<SEL *>(data))
1575 return CYMakeSelector(context, value);
1579 return CYJSNull(context);
1583 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1585 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1586 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1590 method_getReturnType(method, type, sizeof(type));
1595 // XXX: possibly use a more "awesome" check?
1599 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1600 JSObjectRef _this(CYCastJSObject(context, values[0]));
1601 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1604 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1605 Message_privateData *internal(new Message_privateData(sel, type, imp));
1606 return JSObjectMake(context, Message_, internal);
1609 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1610 JSObjectRef function(CYCastJSObject(context, value));
1612 sig::Signature signature;
1613 sig::Parse(pool, &signature, encoding, &Structor_);
1614 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1615 // XXX: see notes in Library.cpp about needing to leak
1616 return reinterpret_cast<IMP>(internal->GetValue());
1619 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1620 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1621 Class _class(internal->GetValue());
1624 const char *name(CYPoolCString(pool, context, property));
1626 if (SEL sel = sel_getUid(name))
1627 if (class_getInstanceMethod(_class, sel) != NULL)
1633 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1634 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1635 Class _class(internal->GetValue());
1638 const char *name(CYPoolCString(pool, context, property));
1640 if (SEL sel = sel_getUid(name))
1641 if (objc_method *method = class_getInstanceMethod(_class, sel))
1642 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1647 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1648 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1649 Class _class(internal->GetValue());
1652 const char *name(CYPoolCString(pool, context, property));
1653 SEL sel(sel_registerName(name));
1658 if (JSValueIsObjectOfClass(context, value, Message_)) {
1659 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1660 type = sig::Unparse(pool, &message->signature_);
1661 imp = reinterpret_cast<IMP>(message->GetValue());
1662 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1663 type = method_getTypeEncoding(method);
1664 imp = CYMakeMessage(context, value, type);
1665 } else _assert(false);
1667 objc_method *method(NULL);
1669 objc_method **methods(class_copyMethodList(_class, &size));
1670 for (size_t i(0); i != size; ++i)
1671 if (sel_isEqual(method_getName(methods[i]), sel)) {
1672 method = methods[i];
1678 method_setImplementation(method, imp);
1680 class_addMethod(_class, sel, imp, type);
1685 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1686 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1687 Class _class(internal->GetValue());
1690 objc_method **data(class_copyMethodList(_class, &size));
1691 for (size_t i(0); i != size; ++i)
1692 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1696 static bool CYHasImplicitProperties(Class _class) {
1697 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1698 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1700 return [_class cy$hasImplicitProperties];
1703 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1704 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1705 id self(internal->GetValue());
1707 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1711 NSString *name(CYCastNSString(&pool, context, property));
1713 if (CYInternal *internal = [CYInternal get:self])
1714 if ([internal hasProperty:property inContext:context])
1717 Class _class(object_getClass(self));
1720 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1721 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1722 if ([self cy$hasProperty:name])
1724 } CYPoolCatch(false)
1726 const char *string(CYPoolCString(pool, context, name));
1728 if (class_getProperty(_class, string) != NULL)
1731 if (CYHasImplicitProperties(_class))
1732 if (SEL sel = sel_getUid(string))
1733 if (CYImplements(self, _class, sel, true))
1739 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1740 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1741 id self(internal->GetValue());
1743 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1744 return Internal::Make(context, self, object);
1747 NSString *name(CYCastNSString(&pool, context, property));
1749 if (CYInternal *internal = [CYInternal get:self])
1750 if (JSValueRef value = [internal getProperty:property inContext:context])
1754 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1758 const char *string(CYPoolCString(pool, context, name));
1759 Class _class(object_getClass(self));
1761 if (objc_property_t property = class_getProperty(_class, string)) {
1762 PropertyAttributes attributes(property);
1763 SEL sel(sel_registerName(attributes.Getter()));
1764 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1767 if (CYHasImplicitProperties(_class))
1768 if (SEL sel = sel_getUid(string))
1769 if (CYImplements(self, _class, sel, true))
1770 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1775 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1776 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1777 id self(internal->GetValue());
1781 NSString *name(CYCastNSString(&pool, context, property));
1782 NSObject *data(CYCastNSObject(&pool, context, value));
1785 if ([self cy$setProperty:name to:data])
1787 } CYPoolCatch(false)
1789 const char *string(CYPoolCString(pool, context, name));
1790 Class _class(object_getClass(self));
1792 if (objc_property_t property = class_getProperty(_class, string)) {
1793 PropertyAttributes attributes(property);
1794 if (const char *setter = attributes.Setter()) {
1795 SEL sel(sel_registerName(setter));
1796 JSValueRef arguments[1] = {value};
1797 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1802 size_t length(strlen(string));
1804 char set[length + 5];
1810 if (string[0] != '\0') {
1811 set[3] = toupper(string[0]);
1812 memcpy(set + 4, string + 1, length - 1);
1815 set[length + 3] = ':';
1816 set[length + 4] = '\0';
1818 if (SEL sel = sel_getUid(set))
1819 if (CYImplements(self, _class, sel)) {
1820 JSValueRef arguments[1] = {value};
1821 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1825 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1826 [internal setProperty:property toValue:value inContext:context];
1833 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1834 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1835 id self(internal->GetValue());
1838 NSString *name(CYCastNSString(NULL, context, property));
1839 return [self cy$deleteProperty:name];
1840 } CYPoolCatch(false)
1841 } CYCatch(false) return /*XXX*/ false; }
1843 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1844 const char *name(sel_getName(method_getName(method)));
1845 if (strchr(name, ':') != NULL)
1848 const char *type(method_getTypeEncoding(method));
1849 if (type == NULL || *type == '\0' || *type == 'v')
1852 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1855 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1856 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1857 id self(internal->GetValue());
1860 Class _class(object_getClass(self));
1864 objc_property_t *data(class_copyPropertyList(_class, &size));
1865 for (size_t i(0); i != size; ++i)
1866 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1870 if (CYHasImplicitProperties(_class))
1871 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1873 objc_method **data(class_copyMethodList(current, &size));
1874 for (size_t i(0); i != size; ++i)
1875 Instance_getPropertyNames_message(names, data[i]);
1880 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1881 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1882 [self cy$getPropertyNames:names inContext:context];
1886 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1887 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1888 JSObjectRef value(CYMakeInstance(context, [internal->GetValue() alloc], Instance::Uninitialized));
1892 static const char *CYBlockEncoding(NSBlock *self) {
1893 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1894 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1896 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1897 descriptor += sizeof(BlockDescriptor1);
1898 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1899 descriptor += sizeof(BlockDescriptor2);
1900 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1901 return descriptor3->signature;
1904 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1905 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1906 id self(internal->GetValue());
1908 if (const char *encoding = CYBlockEncoding(self)) {
1914 sig::Signature signature;
1915 sig::Parse(pool, &signature, encoding, &Structor_);
1918 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1920 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1921 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1922 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1926 CYThrow("NSBlock without signature field passed arguments");
1930 } CYPoolCatch(NULL);
1935 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1936 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1937 Class _class(internal->GetValue());
1938 if (!CYIsClass(_class))
1941 if (CYJSValueIsNSObject(context, instance)) {
1942 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1943 // XXX: this isn't always safe
1944 return [linternal->GetValue() isKindOfClass:_class];
1950 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1952 throw CYJSError(context, "incorrect number of arguments to Instance");
1954 id value(CYCastNSObject(&pool, context, arguments[0]));
1956 value = [NSNull null];
1957 return CYCastJSValue(context, [value cy$box]);
1960 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1961 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1964 id self(internal->GetValue());
1965 const char *name(CYPoolCString(pool, context, property));
1967 if (object_getInstanceVariable(self, name, NULL) != NULL)
1973 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
1974 length = CYCastDouble(encoding + 1);
1978 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
1979 for (size_t i(0); i != size; ++i)
1980 if (ivars[i] == ivar)
1982 else if (ivar_getOffset(ivars[i]) == offset) {
1983 const char *encoding(ivar_getTypeEncoding(ivars[i]));
1984 _assert(encoding != NULL);
1985 _assert(encoding[0] == 'b');
1986 shift += CYCastDouble(encoding + 1);
1991 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1992 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1995 id self(internal->GetValue());
1996 const char *name(CYPoolCString(pool, context, property));
1998 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1999 ptrdiff_t offset(ivar_getOffset(ivar));
2000 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2002 const char *encoding(ivar_getTypeEncoding(ivar));
2003 _assert(encoding != NULL);
2004 _assert(encoding[0] != '\0');
2005 if (encoding[0] == 'b') {
2006 unsigned length, shift;
2007 CYBitField(length, shift, self, ivar, encoding, offset);
2008 _assert(shift + length <= sizeof(uintptr_t) * 8);
2009 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2010 uintptr_t mask((1 << length) - 1);
2011 return CYCastJSValue(context, (field >> shift) & mask);
2013 #if defined(__APPLE__) && defined(__LP64__)
2014 // XXX: maybe do even more verifications here
2015 if (strcmp(name, "isa") == 0)
2016 return CYCastJSValue(context, object_getClass(self));
2019 auto type(new(pool) Type_privateData(encoding));
2020 return CYFromFFI(context, type->type_, type->GetFFI(), data);
2027 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2028 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2031 id self(internal->GetValue());
2032 const char *name(CYPoolCString(pool, context, property));
2034 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2035 ptrdiff_t offset(ivar_getOffset(ivar));
2036 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2038 const char *encoding(ivar_getTypeEncoding(ivar));
2039 _assert(encoding != NULL);
2040 if (encoding[0] == 'b') {
2041 unsigned length, shift;
2042 CYBitField(length, shift, self, ivar, encoding, offset);
2043 _assert(shift + length <= sizeof(uintptr_t) * 8);
2044 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2045 uintptr_t mask((1 << length) - 1);
2046 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2048 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2049 CYPoolFFI(&pool, context, type->type_, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2057 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2058 if (Class super = class_getSuperclass(_class))
2059 Internal_getPropertyNames_(super, names);
2062 objc_ivar **data(class_copyIvarList(_class, &size));
2063 for (size_t i(0); i != size; ++i)
2064 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2068 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2069 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2072 id self(internal->GetValue());
2073 Class _class(object_getClass(self));
2075 Internal_getPropertyNames_(_class, names);
2078 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2079 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2080 return internal->GetOwner();
2083 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2085 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2088 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2090 NSString *name(CYCastNSString(&pool, context, property));
2091 if (Class _class = NSClassFromString(name))
2092 return CYMakeInstance(context, _class, Instance::Permanent);
2096 static Class *CYCopyClassList(size_t &size) {
2097 size = objc_getClassList(NULL, 0);
2098 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2101 size_t writ(objc_getClassList(data, size));
2107 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2118 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2120 if (Class *data = CYCopyClassList(size)) {
2121 for (size_t i(0); i != size; ++i)
2122 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2128 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2129 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2132 const char *name(CYPoolCString(pool, context, property));
2134 const char **data(objc_copyClassNamesForImage(internal, &size));
2136 for (size_t i(0); i != size; ++i)
2137 if (strcmp(name, data[i]) == 0) {
2138 if (Class _class = objc_getClass(name)) {
2139 value = CYMakeInstance(context, _class, Instance::Permanent);
2150 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2151 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2153 const char **data(objc_copyClassNamesForImage(internal, &size));
2154 for (size_t i(0); i != size; ++i)
2155 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2159 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2161 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2164 const char **data(objc_copyImageNames(&size));
2165 pool.atexit(free, data);
2167 for (size_t i(0); i != size; ++i)
2168 if (name == data[i]) {
2169 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2170 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2177 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2179 const char **data(objc_copyImageNames(&size));
2180 for (size_t i(0); i != size; ++i)
2181 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2186 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2188 const char *name(CYPoolCString(pool, context, property));
2189 if (Protocol *protocol = objc_getProtocol(name))
2190 return CYMakeInstance(context, protocol, Instance::Permanent);
2194 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2196 Protocol **data(objc_copyProtocolList(&size));
2197 for (size_t i(0); i != size; ++i)
2198 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2202 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2204 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2206 return CYJSNull(context);
2210 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2211 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2215 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2216 *data = reinterpret_cast<void *>(address);
2217 return KERN_SUCCESS;
2221 std::set<Class> query_;
2222 JSContextRef context_;
2223 JSObjectRef results_;
2226 struct CYObjectStruct {
2230 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2231 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2232 JSContextRef context(choice->context_);
2234 for (unsigned i(0); i != count; ++i) {
2235 vm_range_t &range(ranges[i]);
2236 void *data(reinterpret_cast<void *>(range.address));
2237 size_t size(range.size);
2239 if (size < sizeof(CYObjectStruct))
2242 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2243 #if defined(__APPLE__) && defined(__LP64__)
2244 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2246 Class isa(reinterpret_cast<Class>(pointers[0]));
2249 std::set<Class>::const_iterator result(choice->query_.find(isa));
2250 if (result == choice->query_.end())
2253 size_t needed(class_getInstanceSize(*result));
2254 // XXX: if (size < needed)
2256 size_t boundary(496);
2260 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2262 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2266 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2268 throw CYJSError(context, "choose() takes a class argument");
2270 CYGarbageCollect(context);
2273 id _class(CYCastNSObject(&pool, context, arguments[0]));
2275 vm_address_t *zones(NULL);
2277 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2278 _assert(error == KERN_SUCCESS);
2280 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2281 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2284 choice.context_ = context;
2285 choice.results_ = results;
2288 Class *classes(CYCopyClassList(number));
2289 _assert(classes != NULL);
2291 for (size_t i(0); i != number; ++i)
2292 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2293 if (current == _class) {
2294 choice.query_.insert(classes[i]);
2300 for (unsigned i(0); i != size; ++i) {
2301 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2302 if (zone == NULL || zone->introspect == NULL)
2305 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2313 #if defined(__i386__) || defined(__x86_64__)
2314 #define OBJC_MAX_STRUCT_BY_VALUE 8
2315 static int struct_forward_array[] = {
2316 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2317 #elif defined(__arm__)
2318 #define OBJC_MAX_STRUCT_BY_VALUE 1
2319 static int struct_forward_array[] = {
2321 #elif defined(__arm64__)
2324 #error missing objc-runtime-info
2328 static bool stret(ffi_type *ffi_type) {
2329 return ffi_type->type == FFI_TYPE_STRUCT && (
2330 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2331 struct_forward_array[ffi_type->size] != 0
2339 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2343 _class = object_getClass(self);
2347 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2348 imp = method_getImplementation(method);
2349 type = method_getTypeEncoding(method);
2354 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2355 type = CYPoolCString(pool, context, [method _typeString]);
2361 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2368 sig::Signature signature;
2369 sig::Parse(pool, &signature, type, &Structor_);
2371 size_t used(count + 3);
2372 if (used > signature.count) {
2373 sig::Element *elements(new (pool) sig::Element[used]);
2374 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2376 for (size_t index(signature.count); index != used; ++index) {
2377 sig::Element *element(&elements[index]);
2378 element->name = NULL;
2379 element->offset = _not(size_t);
2381 sig::Type *type(new (pool) sig::Type);
2382 memset(type, 0, sizeof(*type));
2383 type->primitive = sig::object_P;
2384 element->type = type;
2387 signature.elements = elements;
2388 signature.count = used;
2392 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2396 if (stret(cif.rtype))
2397 imp = class_getMethodImplementation_stret(_class, _cmd);
2400 imp = class_getMethodImplementation(_class, _cmd);
2403 void (*function)() = reinterpret_cast<void (*)()>(imp);
2404 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2407 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2409 throw CYJSError(context, "too few arguments to objc_msgSend");
2419 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2420 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2421 self = internal->GetValue();
2422 _class = internal->class_;;
2423 uninitialized = false;
2424 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2425 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2426 self = internal->GetValue();
2428 uninitialized = internal->IsUninitialized();
2430 internal->value_ = nil;
2432 self = CYCastNSObject(&pool, context, arguments[0]);
2434 uninitialized = false;
2438 return CYJSNull(context);
2440 _cmd = CYCastSEL(context, arguments[1]);
2442 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2445 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2446 return $objc_msgSend(context, object, _this, count, arguments);
2449 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2450 JSValueRef setup[count + 2];
2453 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2454 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2457 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2459 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2461 // XXX: handle Instance::Uninitialized?
2462 id self(CYCastNSObject(&pool, context, _this));
2466 setup[1] = &internal->sel_;
2468 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2471 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2473 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2475 id self(CYCastNSObject(&pool, context, arguments[0]));
2476 Class _class(CYCastClass(pool, context, arguments[1]));
2477 return cy::Super::Make(context, self, _class);
2480 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2482 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2484 const char *name(CYPoolCString(pool, context, arguments[0]));
2485 return CYMakeSelector(context, sel_registerName(name));
2488 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2490 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2491 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2492 return CYMakeInstance(context, self);
2495 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2496 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2497 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2500 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2501 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2502 Type_privateData *typical(internal->GetType());
2507 if (typical == NULL) {
2511 type = typical->type_;
2512 ffi = typical->ffi_;
2515 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2518 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2519 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2520 const char *encoding(CYBlockEncoding(internal->GetValue()));
2521 if (encoding == NULL)
2522 return CYJSNull(context);
2523 // XXX: this should be stored on a FunctionInstance private value subclass
2525 sig::Signature signature;
2526 sig::Parse(pool, &signature, encoding, &Structor_);
2527 return CYMakeType(context, &signature);
2530 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2531 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2532 return CYMakeInstance(context, object_getClass(internal->GetValue()), Instance::Permanent);
2535 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2536 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2537 id self(internal->GetValue());
2538 if (!CYIsClass(self))
2539 return CYJSUndefined(context);
2540 return CYGetClassPrototype(context, self);
2543 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2544 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2545 id self(internal->GetValue());
2546 if (!CYIsClass(self))
2547 return CYJSUndefined(context);
2548 return Messages::Make(context, (Class) self);
2551 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2552 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2554 if (!CYJSValueIsNSObject(context, _this))
2557 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2558 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2561 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2562 if (!CYJSValueIsNSObject(context, _this))
2565 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2566 id value(internal->GetValue());
2573 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2575 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2576 return CYJSUndefined(context);
2577 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2580 return CYCastJSValue(context, CYJSString(context, [value description]));
2582 } CYCatch(NULL) return /*XXX*/ NULL; }
2584 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2585 if (!CYJSValueIsNSObject(context, _this))
2588 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2589 id value(internal->GetValue());
2590 _assert(value != nil);
2592 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2595 if (JSValueRef result = [value cy$valueOfInContext:context])
2599 } CYCatch(NULL) return /*XXX*/ NULL; }
2601 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2602 if (!CYJSValueIsNSObject(context, _this))
2605 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2606 // XXX: but... but... THIS ISN'T A POINTER! :(
2607 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2608 } CYCatch(NULL) return /*XXX*/ NULL; }
2610 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2611 if (!CYJSValueIsNSObject(context, _this))
2614 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2615 id value(internal->GetValue());
2618 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2619 return CYCastJSValue(context, CYJSString(context, [value description]));
2621 } CYCatch(NULL) return /*XXX*/ NULL; }
2623 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2624 if (!CYJSValueIsNSObject(context, _this))
2627 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2628 id value(internal->GetValue());
2630 if (!CYIsClass(value))
2631 CYThrow("non-Class object cannot be used as Type");
2634 memset(&type, 0, sizeof(type));
2635 type.primitive = sig::object_P;
2636 type.name = class_getName(value);
2637 return CYMakeType(context, &type);
2638 } CYCatch(NULL) return /*XXX*/ NULL; }
2640 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2641 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2642 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2645 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2646 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2649 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2650 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2651 const char *name(sel_getName(internal->GetValue()));
2654 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2655 return CYCastJSValue(context, CYJSString(context, string));
2657 } CYCatch(NULL) return /*XXX*/ NULL; }
2659 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2661 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2664 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2665 SEL sel(internal->GetValue());
2667 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2668 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2669 const char *encoding(method_getTypeEncoding(method));
2671 sig::Signature signature;
2672 sig::Parse(pool, &signature, encoding, &Structor_);
2673 return CYMakeType(context, &signature);
2676 static JSStaticValue Selector_staticValues[2] = {
2677 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2678 {NULL, NULL, NULL, 0}
2681 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2682 static JSStaticValue Instance_staticValues[5] = {
2683 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2684 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2685 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2686 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2687 {NULL, NULL, NULL, 0}
2690 static JSStaticValue FunctionInstance_staticValues[6] = {
2691 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2692 // XXX: this is sadly a duplicate of Instance_staticValues
2693 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2694 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2695 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2696 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2697 {NULL, NULL, NULL, 0}
2700 static JSStaticFunction Instance_staticFunctions[7] = {
2701 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2702 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2703 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2704 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2705 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2706 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2710 static JSStaticFunction Class_staticFunctions[2] = {
2711 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2715 static JSStaticFunction Internal_staticFunctions[2] = {
2716 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2720 static JSStaticFunction Selector_staticFunctions[5] = {
2721 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2722 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2723 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2724 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2729 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2730 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2731 } CYObjectiveCatch }
2734 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2735 CYPool &pool(CYGetGlobalPool());
2737 Object_type = new(pool) Type_privateData(sig::object_P);
2738 Selector_type = new(pool) Type_privateData(sig::selector_P);
2740 NSArray_ = objc_getClass("NSArray");
2741 NSBlock_ = objc_getClass("NSBlock");
2742 NSDictionary_ = objc_getClass("NSDictionary");
2743 NSNumber_ = objc_getClass("NSNumber");
2744 NSString_ = objc_getClass("NSString");
2745 Object_ = objc_getClass("Object");
2748 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2750 // XXX: apparently, iOS now has both of these
2751 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2752 if (NSCFBoolean_ == nil)
2753 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2755 NSCFType_ = objc_getClass("NSCFType");
2757 NSZombie_ = objc_getClass("_NSZombie_");
2759 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2760 NSZombie_ = objc_getClass("NSZombie");
2763 JSClassDefinition definition;
2765 definition = kJSClassDefinitionEmpty;
2766 definition.className = "Instance";
2767 definition.staticValues = Instance_staticValues;
2768 definition.staticFunctions = Instance_staticFunctions;
2769 definition.hasProperty = &Instance_hasProperty;
2770 definition.getProperty = &Instance_getProperty;
2771 definition.setProperty = &Instance_setProperty;
2772 definition.deleteProperty = &Instance_deleteProperty;
2773 definition.getPropertyNames = &Instance_getPropertyNames;
2774 definition.callAsConstructor = &Instance_callAsConstructor;
2775 definition.hasInstance = &Instance_hasInstance;
2776 definition.finalize = &CYFinalize;
2777 Instance_ = JSClassCreate(&definition);
2779 definition.className = "ArrayInstance";
2780 ArrayInstance_ = JSClassCreate(&definition);
2782 definition.className = "BooleanInstance";
2783 BooleanInstance_ = JSClassCreate(&definition);
2785 definition.className = "NumberInstance";
2786 NumberInstance_ = JSClassCreate(&definition);
2788 definition.className = "ObjectInstance";
2789 ObjectInstance_ = JSClassCreate(&definition);
2791 definition.className = "StringInstance";
2792 StringInstance_ = JSClassCreate(&definition);
2794 definition.className = "FunctionInstance";
2795 definition.staticValues = FunctionInstance_staticValues;
2796 definition.callAsFunction = &FunctionInstance_callAsFunction;
2797 FunctionInstance_ = JSClassCreate(&definition);
2799 definition = kJSClassDefinitionEmpty;
2800 definition.className = "Class";
2801 definition.staticFunctions = Class_staticFunctions;
2802 Class_ = JSClassCreate(&definition);
2804 definition = kJSClassDefinitionEmpty;
2805 definition.className = "Internal";
2806 definition.staticFunctions = Internal_staticFunctions;
2807 definition.hasProperty = &Internal_hasProperty;
2808 definition.getProperty = &Internal_getProperty;
2809 definition.setProperty = &Internal_setProperty;
2810 definition.getPropertyNames = &Internal_getPropertyNames;
2811 definition.finalize = &CYFinalize;
2812 Internal_ = JSClassCreate(&definition);
2814 definition = kJSClassDefinitionEmpty;
2815 definition.className = "Message";
2816 definition.staticFunctions = cy::Functor::StaticFunctions;
2817 definition.staticValues = cy::Functor::StaticValues;
2818 definition.callAsFunction = &Message_callAsFunction;
2819 definition.finalize = &CYFinalize;
2820 Message_ = JSClassCreate(&definition);
2822 definition = kJSClassDefinitionEmpty;
2823 definition.className = "Messages";
2824 definition.hasProperty = &Messages_hasProperty;
2825 definition.getProperty = &Messages_getProperty;
2826 definition.setProperty = &Messages_setProperty;
2827 definition.getPropertyNames = &Messages_getPropertyNames;
2828 definition.finalize = &CYFinalize;
2829 Messages_ = JSClassCreate(&definition);
2831 definition = kJSClassDefinitionEmpty;
2832 definition.className = "Selector";
2833 definition.staticValues = Selector_staticValues;
2834 definition.staticFunctions = Selector_staticFunctions;
2835 definition.callAsFunction = &Selector_callAsFunction;
2836 definition.finalize = &CYFinalize;
2837 Selector_ = JSClassCreate(&definition);
2839 definition = kJSClassDefinitionEmpty;
2840 definition.className = "Super";
2841 definition.staticFunctions = Internal_staticFunctions;
2842 definition.finalize = &CYFinalize;
2843 Super_ = JSClassCreate(&definition);
2845 definition = kJSClassDefinitionEmpty;
2846 definition.className = "ObjectiveC::Classes";
2847 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2848 definition.getProperty = &ObjectiveC_Classes_getProperty;
2849 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2850 ObjectiveC_Classes_ = JSClassCreate(&definition);
2852 definition = kJSClassDefinitionEmpty;
2853 definition.className = "ObjectiveC::Constants";
2854 definition.getProperty = &ObjectiveC_Constants_getProperty;
2855 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2856 ObjectiveC_Constants_ = JSClassCreate(&definition);
2859 definition = kJSClassDefinitionEmpty;
2860 definition.className = "ObjectiveC::Images";
2861 definition.getProperty = &ObjectiveC_Images_getProperty;
2862 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2863 ObjectiveC_Images_ = JSClassCreate(&definition);
2865 definition = kJSClassDefinitionEmpty;
2866 definition.className = "ObjectiveC::Image::Classes";
2867 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2868 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2869 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2872 definition = kJSClassDefinitionEmpty;
2873 definition.className = "ObjectiveC::Protocols";
2874 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2875 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2876 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2879 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2880 // XXX: this is horrible; there has to be a better way to do this
2882 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2884 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2890 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2891 JSObjectRef global(CYGetGlobalObject(context));
2892 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2893 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2894 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2895 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2897 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2898 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2900 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2901 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2902 CYArrayPush(context, alls, protocols);
2904 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2905 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2906 CYArrayPush(context, alls, classes);
2908 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2909 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2910 CYArrayPush(context, alls, constants);
2913 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2916 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2917 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2918 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2919 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2920 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2922 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2923 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2925 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2926 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2927 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2928 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2929 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2931 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2932 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2933 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2934 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2935 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2937 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2938 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2939 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2940 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2941 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2943 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2944 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2945 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2946 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2947 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2949 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2950 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2951 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2952 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2953 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2955 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2956 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2957 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2958 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2959 CYSetPrototype(context, StringInstance_prototype, String_prototype);
2961 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2962 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2963 CYSetPrototype(context, Class_prototype, Instance_prototype);
2965 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2966 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2967 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
2969 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2970 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
2973 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2976 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2978 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2979 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2982 static void *CYObjectiveC_CastSymbol(const char *name) {
2984 #ifdef __GNU_LIBOBJC__
2985 else if (strcmp(name, "object_getClass") == 0)
2986 return reinterpret_cast<void *>(&object_getClass);
2991 static CYHook CYObjectiveCHook = {
2992 &CYObjectiveC_ExecuteStart,
2993 &CYObjectiveC_ExecuteEnd,
2994 &CYObjectiveC_CallFunction,
2995 &CYObjectiveC_Initialize,
2996 &CYObjectiveC_SetupContext,
2997 &CYObjectiveC_PoolFFI,
2998 &CYObjectiveC_FromFFI,
2999 &CYObjectiveC_CastSymbol,
3002 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3004 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3005 CYSetupContext(context);
3006 } CYObjectiveCatch }
3008 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3011 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3012 CYStream stream(utf8.data, utf8.data + utf8.size);
3013 utf8 = CYPoolCode(pool, stream);
3015 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3016 size_t bytes(utf16.size * sizeof(uint16_t));
3017 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3018 memcpy(copy, utf16.data, bytes);
3022 } catch (const CYException &exception) {
3024 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];