1 /* Cycript - The Truly Universal Scripting Language
2 * Copyright (C) 2009-2016 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "cycript.hpp"
32 #include <malloc/malloc.h>
33 #include <mach/mach.h>
36 #include <objc/message.h>
37 #include <objc/runtime.h>
40 #include <CoreFoundation/CoreFoundation.h>
41 #include <JavaScriptCore/JSStringRefCF.h>
44 #include <Foundation/Foundation.h>
49 #include "JavaScript.hpp"
51 #include "Execute.hpp"
53 #include "ObjectiveC/Internal.hpp"
54 #include "ObjectiveC/Syntax.hpp"
56 #define CYObjectiveTry_ { \
58 #define CYObjectiveTry { \
59 JSContextRef context(context_); \
61 #define CYObjectiveCatch \
62 catch (const CYException &error) { \
63 @throw CYCastNSObject(NULL, context, error.CastJSValue(context, "Error")); \
69 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
71 #define CYPoolCatch(value) \
72 @catch (NSException *error) { \
73 _saved = [error retain]; \
74 throw CYJSError(context, CYCastJSValue(context, error)); \
79 [_saved autorelease]; \
85 #define CYSadCatch(value) \
86 @catch (NSException *error ) { \
87 throw CYJSError(context, CYCastJSValue(context, error)); \
91 #define _oassert(test) \
93 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"_assert(" #test ")" userInfo:nil];
101 void (*invoke)(void *, ...);
105 struct BlockDescriptor1 {
106 unsigned long int reserved;
107 unsigned long int size;
110 struct BlockDescriptor2 {
111 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
112 void (*dispose_helper)(BlockLiteral *src);
115 struct BlockDescriptor3 {
116 const char *signature;
121 BLOCK_DEALLOCATING = 0x0001,
122 BLOCK_REFCOUNT_MASK = 0xfffe,
123 BLOCK_NEEDS_FREE = 1 << 24,
124 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
125 BLOCK_HAS_CTOR = 1 << 26,
126 BLOCK_IS_GC = 1 << 27,
127 BLOCK_IS_GLOBAL = 1 << 28,
128 BLOCK_HAS_STRET = 1 << 29,
129 BLOCK_HAS_SIGNATURE = 1 << 30,
132 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
134 /* Objective-C Pool Release {{{ */
135 void CYPoolRelease_(void *data) {
136 id object(reinterpret_cast<id>(data));
140 id CYPoolRelease_(CYPool *pool, id object) {
143 else if (pool == NULL)
144 return [object autorelease];
146 pool->atexit(CYPoolRelease_);
151 template <typename Type_>
152 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
153 return (Type_) CYPoolRelease_(pool, (id) object);
156 /* Objective-C Strings {{{ */
157 CYUTF8String CYPoolUTF8String(CYPool &pool, JSContextRef context, NSString *value) {
158 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
159 char *string(new(pool) char[size + 1]);
160 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
161 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
162 return CYUTF8String(string, [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
165 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
166 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
167 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
172 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
173 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
177 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
180 // XXX: this definition scares me; is anyone using this?!
181 NSString *string([value description]);
183 return CYCopyJSString(context, string);
186 return CYCopyJSString(CYPoolUTF8String(pool, context, string));
190 NSString *CYCopyNSString(const CYUTF8String &value) {
192 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
194 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
198 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
200 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
203 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
207 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
208 return CYCopyNSString(context, CYJSString(context, value));
211 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
212 return CYPoolRelease(pool, CYCopyNSString(value));
215 NSString *CYCastNSString(CYPool *pool, SEL sel) {
216 const char *name(sel_getName(sel));
217 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
220 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
221 return CYPoolRelease(pool, CYCopyNSString(context, value));
224 CYUTF8String CYCastUTF8String(NSString *value) {
225 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
226 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
230 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
232 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
233 if (exception == NULL)
235 *exception = CYCastJSValue(context, error);
238 size_t CYGetIndex(NSString *value) {
239 return CYGetIndex(CYCastUTF8String(value));
242 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
243 return CYGetOffset(CYPoolCString(pool, context, value), index);
246 static JSClassRef ArrayInstance_;
247 static JSClassRef BooleanInstance_;
248 static JSClassRef ClassInstance_;
249 static JSClassRef FunctionInstance_;
250 static JSClassRef NumberInstance_;
251 static JSClassRef ObjectInstance_;
252 static JSClassRef StringInstance_;
254 static JSClassRef ObjectiveC_Classes_;
255 static JSClassRef ObjectiveC_Constants_;
256 static JSClassRef ObjectiveC_Protocols_;
259 static JSClassRef ObjectiveC_Image_Classes_;
260 static JSClassRef ObjectiveC_Images_;
264 static Class __NSMallocBlock__;
265 static Class NSCFBoolean_;
266 static Class NSCFType_;
267 static Class NSGenericDeallocHandler_;
269 static Class NSBoolNumber_;
272 static Class NSArray_;
273 static Class NSBlock_;
274 static Class NSDictionary_;
275 static Class NSNumber_;
276 static Class NSString_;
277 static Class NSZombie_;
278 static Class Object_;
280 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
282 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
284 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
285 else if (meta && !class_isMetaClass(self))
286 return CYGetCachedObject(context, CYJSString("ClassInstance_prototype"));
288 JSObjectRef global(CYGetGlobalObject(context));
289 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
292 sprintf(label, "i%p", self);
293 CYJSString name(label);
295 JSValueRef value(CYGetProperty(context, cy, name));
296 if (!JSValueIsUndefined(context, value))
299 JSValueRef prototype;
302 if (self == NSCFBoolean_)
304 if (self == NSBoolNumber_)
306 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
307 else if (self == NSArray_)
308 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
309 else if (self == NSBlock_)
310 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
311 else if (self == NSNumber_)
312 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
313 else if (self == NSDictionary_)
314 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
315 else if (self == NSString_)
316 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
318 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
320 JSObjectRef object(JSObjectMake(context, NULL, NULL));
321 CYSetPrototype(context, object, prototype);
322 CYSetProperty(context, cy, name, object);
327 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
328 return CYGetClassPrototype(context, self, class_isMetaClass(self));
331 JSValueRef Messages::GetPrototype(JSContextRef context) const {
332 if (Class super = class_getSuperclass(value_))
333 return Messages::Make(context, super);
337 bool CYIsKindOfClass(id object, Class _class) {
338 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
344 JSValueRef Instance::GetPrototype(JSContextRef context) const {
345 return CYGetClassPrototype(context, object_getClass(value_));
348 JSClassRef Instance::GetClass(id object, Flags flags) {
349 return CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance::Class_;
352 Instance::Instance(id value, Flags flags) :
356 if ((flags & Instance::Permanent) == 0)
357 value_ = [value_ retain];
360 Instance::~Instance() {
361 if ((flags_ & Permanent) == 0)
365 struct Message_privateData :
368 static JSClassRef Class_;
372 Message_privateData(SEL sel, const char *type, IMP value) :
373 cy::Functor(reinterpret_cast<void (*)()>(value), type),
378 static JSObjectRef Make(JSContextRef context, SEL sel, const char *type, IMP value);
381 JSClassRef Message_privateData::Class_;
383 JSObjectRef CYMakeInstance(JSContextRef context, id object, Instance::Flags flags = Instance::None) {
384 _assert(object != nil);
387 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
389 if (weak != NULL && &JSWeakObjectMapGet != NULL)
390 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
394 JSObjectRef instance(Instance::Make(context, object, flags));
397 if (weak != NULL && &JSWeakObjectMapSet != NULL)
398 JSWeakObjectMapSet(context, weak, object, instance);
404 @interface NSMethodSignature (Cycript)
405 - (NSString *) _typeString;
408 @interface NSObject (Cycript)
410 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
411 - (JSType) cy$JSType;
413 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
414 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
416 - (bool) cy$hasProperty:(NSString *)name;
417 - (NSObject *) cy$getProperty:(NSString *)name;
418 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
419 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
420 - (bool) cy$deleteProperty:(NSString *)name;
421 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
423 + (bool) cy$hasImplicitProperties;
429 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
432 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
433 _assert(value != nil);
435 Class _class(object_getClass(value));
437 if (class_isMetaClass(_class)) {
438 const char *name(class_getName(value));
439 if (class_isMetaClass(value))
440 return [NSString stringWithFormat:@"object_getClass(%s)", name];
442 return [NSString stringWithUTF8String:name];
445 if (_class == NSZombie_)
446 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
448 SEL sel(@selector(cy$toCYON:inSet:));
450 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
451 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
452 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
453 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
454 return [value cy$toCYON:objective inSet:objects];
456 return [NSString stringWithFormat:@"%@", value];
459 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
461 return CYCastNSCYON(value, objective, *objects);
463 std::set<void *> objects;
464 return CYCastNSCYON(value, objective, objects);
468 struct PropertyAttributes {
473 const char *variable;
486 PropertyAttributes(objc_property_t property) :
498 name = property_getName(property);
499 const char *attributes(property_getAttributes(property));
501 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
502 if ((next = strchr(token, ',')) != NULL)
505 case 'R': readonly = true; break;
506 case 'C': copy = true; break;
507 case '&': retain = true; break;
508 case 'N': nonatomic = true; break;
509 case 'G': getter_ = token + 1; break;
510 case 'S': setter_ = token + 1; break;
511 case 'V': variable = token + 1; break;
515 /*if (variable == NULL) {
516 variable = property_getName(property);
517 size_t size(strlen(variable));
518 char *name(new(pool_) char[size + 2]);
520 memcpy(name + 1, variable, size);
521 name[size + 1] = '\0';
526 const char *Getter() {
528 getter_ = pool_.strdup(name);
532 const char *Setter() {
533 if (setter_ == NULL && !readonly) {
534 size_t length(strlen(name));
536 char *temp(new(pool_) char[length + 5]);
542 temp[3] = toupper(name[0]);
543 memcpy(temp + 4, name + 1, length - 1);
546 temp[length + 3] = ':';
547 temp[length + 4] = '\0';
556 @interface CYWebUndefined : NSObject {
559 + (CYWebUndefined *) undefined;
563 @implementation CYWebUndefined
565 + (CYWebUndefined *) undefined {
566 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
572 #define WebUndefined CYWebUndefined
574 /* Bridge: CYJSObject {{{ */
575 @interface CYJSObject : NSMutableDictionary {
577 JSGlobalContextRef context_;
580 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
582 - (NSUInteger) count;
583 - (id) objectForKey:(id)key;
584 - (NSEnumerator *) keyEnumerator;
585 - (void) setObject:(id)object forKey:(id)key;
586 - (void) removeObjectForKey:(id)key;
590 /* Bridge: CYJSArray {{{ */
591 @interface CYJSArray : NSMutableArray {
593 JSGlobalContextRef context_;
596 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
598 - (NSUInteger) count;
599 - (id) objectAtIndex:(NSUInteger)index;
601 - (void) addObject:(id)anObject;
602 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
603 - (void) removeLastObject;
604 - (void) removeObjectAtIndex:(NSUInteger)index;
605 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
610 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
611 return JSValueIsObjectOfClass(context, value, Instance::Class_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
614 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
615 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
619 struct CYBlockDescriptor {
621 BlockDescriptor1 one_;
622 BlockDescriptor2 two_;
623 BlockDescriptor3 three_;
626 Closure_privateData *internal_;
629 void CYDisposeBlock(BlockLiteral *literal) {
630 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
633 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
634 JSObjectRef _this(CYCastJSObject(context, values[0]));
635 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
638 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
639 _assert(__NSMallocBlock__ != Nil);
640 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
642 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
643 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
645 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockAdapter_);
646 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->value_);
648 literal->isa = __NSMallocBlock__;
649 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
650 literal->reserved = 0;
651 literal->descriptor = descriptor;
653 descriptor->d_.one_.size = sizeof(descriptor->d_);
654 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
655 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
657 return reinterpret_cast<NSBlock *>(literal);
661 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
662 if (CYJSValueIsNSObject(context, object)) {
663 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
664 return internal->value_;
667 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
668 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
669 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
672 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
673 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
677 @interface NSBoolNumber : NSNumber {
682 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
686 switch (JSType type = JSValueGetType(context, value)) {
687 case kJSTypeUndefined:
688 object = [WebUndefined undefined];
698 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
701 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
707 object = CYCopyNSNumber(context, value);
712 object = CYCopyNSString(context, value);
717 // XXX: this might could be more efficient
718 object = CYCastNSObject(pool, context, (JSObjectRef) value);
723 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
730 return CYPoolRelease(pool, object);
732 return [object retain];
735 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
736 return CYNSObject(pool, context, value, true);
739 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
740 return CYNSObject(&pool, context, value, false);
743 /* Bridge: NSArray {{{ */
744 @implementation NSArray (Cycript)
747 return [[self mutableCopy] autorelease];
750 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
751 _oassert(objects.insert(self).second);
753 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
754 [json appendString:@"@["];
758 for (id object in self) {
760 for (size_t index(0), count([self count]); index != count; ++index) {
761 id object([self objectAtIndex:index]);
764 [json appendString:@","];
767 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
768 [json appendString:CYCastNSCYON(object, true, objects)];
770 [json appendString:@","];
775 [json appendString:@"]"];
779 - (bool) cy$hasProperty:(NSString *)name {
780 if ([name isEqualToString:@"length"])
783 size_t index(CYGetIndex(name));
784 if (index == _not(size_t) || index >= [self count])
785 return [super cy$hasProperty:name];
790 - (NSObject *) cy$getProperty:(NSString *)name {
791 size_t index(CYGetIndex(name));
792 if (index == _not(size_t) || index >= [self count])
793 return [super cy$getProperty:name];
795 return [self objectAtIndex:index];
798 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
800 if ([name isEqualToString:@"length"])
801 return CYCastJSValue(context, [self count]);
804 return [super cy$getProperty:name inContext:context];
807 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
808 [super cy$getPropertyNames:names inContext:context];
810 for (size_t index(0), count([self count]); index != count; ++index) {
811 id object([self objectAtIndex:index]);
812 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
814 sprintf(name, "%zu", index);
815 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
820 + (bool) cy$hasImplicitProperties {
826 /* Bridge: NSBlock {{{ */
828 @interface NSBlock : NSObject
832 static const char *CYBlockEncoding(NSBlock *self);
833 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature);
835 @implementation NSBlock (Cycript)
837 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
841 if (!CYBlockSignature(pool, self, type.signature))
842 return [super cy$toCYON:objective inSet:objects];
843 _oassert(objects.insert(self).second);
845 CYType *typed((new(pool) CYTypeExpression(CYDecodeType(pool, &type)))->typed_);
846 CYTypeModifier *&modifier(CYGetLast(typed->modifier_));
847 CYTypeBlockWith *with(dynamic_cast<CYTypeBlockWith *>(modifier));
848 _assert(with != NULL);
849 CYObjCBlock *block(new(pool) CYObjCBlock(typed, with->parameters_, NULL));
852 std::ostringstream str;
854 CYOutput out(*str.rdbuf(), options);
855 block->Output(out, CYNoFlags);
857 std::string value(str.str());
858 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
864 /* Bridge: NSBoolNumber {{{ */
866 @implementation NSBoolNumber (Cycript)
868 - (JSType) cy$JSType {
869 return kJSTypeBoolean;
872 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
873 NSString *value([self boolValue] ? @"true" : @"false");
874 return objective ? value : [NSString stringWithFormat:@"@%@", value];
877 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
878 return CYCastJSValue(context, (bool) [self boolValue]);
884 /* Bridge: NSDictionary {{{ */
885 @implementation NSDictionary (Cycript)
888 return [[self mutableCopy] autorelease];
891 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
892 _oassert(objects.insert(self).second);
894 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
895 [json appendString:@"@{"];
899 for (NSObject *key in self) {
901 NSEnumerator *keys([self keyEnumerator]);
902 while (NSObject *key = [keys nextObject]) {
905 [json appendString:@","];
908 [json appendString:CYCastNSCYON(key, true, objects)];
909 [json appendString:@":"];
910 NSObject *object([self objectForKey:key]);
911 [json appendString:CYCastNSCYON(object, true, objects)];
914 [json appendString:@"}"];
918 - (bool) cy$hasProperty:(NSString *)name {
919 return [self objectForKey:name] != nil;
922 - (NSObject *) cy$getProperty:(NSString *)name {
923 return [self objectForKey:name];
926 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
927 [super cy$getPropertyNames:names inContext:context];
930 for (NSObject *key in self) {
932 NSEnumerator *keys([self keyEnumerator]);
933 while (NSObject *key = [keys nextObject]) {
935 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
939 + (bool) cy$hasImplicitProperties {
945 /* Bridge: NSMutableArray {{{ */
946 @implementation NSMutableArray (Cycript)
948 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
949 if ([name isEqualToString:@"length"]) {
950 // XXX: is this not intelligent?
951 NSNumber *number(reinterpret_cast<NSNumber *>(value));
952 NSUInteger size([number unsignedIntegerValue]);
953 NSUInteger count([self count]);
955 [self removeObjectsInRange:NSMakeRange(size, count - size)];
956 else if (size != count) {
957 WebUndefined *undefined([WebUndefined undefined]);
958 for (size_t i(count); i != size; ++i)
959 [self addObject:undefined];
964 size_t index(CYGetIndex(name));
965 if (index == _not(size_t))
966 return [super cy$setProperty:name to:value];
968 id object(value ?: [NSNull null]);
970 size_t count([self count]);
972 [self replaceObjectAtIndex:index withObject:object];
974 if (index != count) {
975 WebUndefined *undefined([WebUndefined undefined]);
976 for (size_t i(count); i != index; ++i)
977 [self addObject:undefined];
980 [self addObject:object];
986 - (bool) cy$deleteProperty:(NSString *)name {
987 size_t index(CYGetIndex(name));
988 if (index == _not(size_t) || index >= [self count])
989 return [super cy$deleteProperty:name];
990 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
996 /* Bridge: NSMutableDictionary {{{ */
997 @implementation NSMutableDictionary (Cycript)
999 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1000 [self setObject:(value ?: [NSNull null]) forKey:name];
1004 - (bool) cy$deleteProperty:(NSString *)name {
1005 if ([self objectForKey:name] == nil)
1008 [self removeObjectForKey:name];
1015 /* Bridge: NSNumber {{{ */
1016 @implementation NSNumber (Cycript)
1018 - (JSType) cy$JSType {
1020 // XXX: this just seems stupid
1021 if ([self class] == NSCFBoolean_)
1022 return kJSTypeBoolean;
1024 return kJSTypeNumber;
1027 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1028 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1029 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1032 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1033 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1034 } CYObjectiveCatch }
1038 /* Bridge: NSNull {{{ */
1039 @implementation NSNull (Cycript)
1041 - (JSType) cy$JSType {
1045 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1046 NSString *value(@"null");
1047 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1050 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1051 return CYJSNull(context);
1052 } CYObjectiveCatch }
1056 /* Bridge: NSObject {{{ */
1057 @implementation NSObject (Cycript)
1063 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1064 return [self cy$valueOfInContext:context];
1067 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1069 } CYObjectiveCatch }
1071 - (JSType) cy$JSType {
1072 return kJSTypeObject;
1075 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1076 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1079 - (bool) cy$hasProperty:(NSString *)name {
1083 - (NSObject *) cy$getProperty:(NSString *)name {
1087 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1088 if (NSObject *value = [self cy$getProperty:name])
1089 return CYCastJSValue(context, value);
1091 } CYObjectiveCatch }
1093 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1097 - (bool) cy$deleteProperty:(NSString *)name {
1101 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1104 + (bool) cy$hasImplicitProperties {
1110 /* Bridge: NSOrderedSet {{{ */
1112 @implementation NSOrderedSet (Cycript)
1114 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1115 _oassert(objects.insert(self).second);
1117 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1118 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1119 [json appendString:CYCastNSCYON([self array], true, objects)];
1120 [json appendString:@"]]"];
1127 /* Bridge: NSProxy {{{ */
1128 @implementation NSProxy (Cycript)
1130 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1131 return [[self description] cy$toCYON:objective inSet:objects];
1136 /* Bridge: NSSet {{{ */
1137 @implementation NSSet (Cycript)
1139 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1140 _oassert(objects.insert(self).second);
1142 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1143 [json appendString:@"[NSSet setWithArray:"];
1144 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1145 [json appendString:@"]]"];
1151 /* Bridge: NSString {{{ */
1152 @implementation NSString (Cycript)
1155 return [[self copy] autorelease];
1158 - (JSType) cy$JSType {
1159 return kJSTypeString;
1162 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1163 std::ostringstream str;
1166 CYUTF8String string(CYCastUTF8String(self));
1167 CYStringify(str, string.data, string.size, true);
1168 std::string value(str.str());
1169 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1172 - (bool) cy$hasProperty:(NSString *)name {
1173 size_t index(CYGetIndex(name));
1174 if (index == _not(size_t) || index >= [self length])
1175 return [super cy$hasProperty:name];
1180 - (NSObject *) cy$getProperty:(NSString *)name {
1181 size_t index(CYGetIndex(name));
1182 if (index == _not(size_t) || index >= [self length])
1183 return [super cy$getProperty:name];
1185 return [self substringWithRange:NSMakeRange(index, 1)];
1188 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1189 [super cy$getPropertyNames:names inContext:context];
1191 for (size_t index(0), length([self length]); index != length; ++index) {
1193 sprintf(name, "%zu", index);
1194 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1198 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1199 return CYCastJSValue(context, CYJSString(context, self));
1200 } CYObjectiveCatch }
1204 /* Bridge: WebUndefined {{{ */
1205 @implementation WebUndefined (Cycript)
1207 - (JSType) cy$JSType {
1208 return kJSTypeUndefined;
1211 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1212 NSString *value(@"undefined");
1213 return value; // XXX: maybe use the below code, adding @undefined?
1214 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1217 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1218 return CYJSUndefined(context);
1219 } CYObjectiveCatch }
1224 static bool CYIsClass(id self) {
1225 return class_isMetaClass(object_getClass(self));
1228 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1229 id self(CYCastNSObject(&pool, context, value));
1230 if (CYIsClass(self))
1231 return (Class) self;
1232 throw CYJSError(context, "got something that is not a Class");
1236 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1238 size_t size(JSPropertyNameArrayGetCount(names));
1239 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1240 for (size_t index(0); index != size; ++index)
1241 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1245 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) {
1247 return CYJSNull(context);
1248 return CYMakeInstance(context, value);
1251 @implementation CYJSObject
1253 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1254 if ((self = [super init]) != nil) {
1256 context_ = CYGetJSContext(context);
1257 JSGlobalContextRetain(context_);
1258 JSValueProtect(context_, object_);
1260 } CYObjectiveCatch }
1262 - (void) dealloc { CYObjectiveTry {
1263 JSValueUnprotect(context_, object_);
1264 JSGlobalContextRelease(context_);
1266 } CYObjectiveCatch }
1268 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1270 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1272 return [super cy$toCYON:objective inSet:objects];
1274 return [NSString stringWithUTF8String:cyon];
1275 } CYObjectiveCatch }
1277 - (NSUInteger) count { CYObjectiveTry {
1278 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1279 size_t size(JSPropertyNameArrayGetCount(names));
1280 JSPropertyNameArrayRelease(names);
1282 } CYObjectiveCatch }
1284 - (id) objectForKey:(id)key { CYObjectiveTry {
1285 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1286 if (JSValueIsUndefined(context, value))
1288 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1289 } CYObjectiveCatch }
1291 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1292 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1293 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1294 JSPropertyNameArrayRelease(names);
1296 } CYObjectiveCatch }
1298 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1299 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1300 } CYObjectiveCatch }
1302 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1303 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1304 } CYObjectiveCatch }
1308 @implementation CYJSArray
1310 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1312 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1313 } CYObjectiveCatch }
1315 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1316 if ((self = [super init]) != nil) {
1318 context_ = CYGetJSContext(context);
1319 JSGlobalContextRetain(context_);
1320 JSValueProtect(context_, object_);
1322 } CYObjectiveCatch }
1324 - (void) dealloc { CYObjectiveTry {
1325 JSValueUnprotect(context_, object_);
1326 JSGlobalContextRelease(context_);
1328 } CYObjectiveCatch }
1330 - (NSUInteger) count { CYObjectiveTry {
1331 return CYArrayLength(context, object_);
1332 } CYObjectiveCatch }
1334 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1335 size_t bounds([self count]);
1336 if (index >= bounds)
1337 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1338 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1339 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1340 } CYObjectiveCatch }
1342 - (void) addObject:(id)object { CYObjectiveTry {
1343 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1344 } CYObjectiveCatch }
1346 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1347 size_t bounds([self count] + 1);
1348 if (index >= bounds)
1349 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1350 JSValueRef arguments[3];
1351 arguments[0] = CYCastJSValue(context, index);
1352 arguments[1] = CYCastJSValue(context, 0);
1353 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1354 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1355 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1356 } CYObjectiveCatch }
1358 - (void) removeLastObject { CYObjectiveTry {
1359 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1360 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1361 } CYObjectiveCatch }
1363 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1364 size_t bounds([self count]);
1365 if (index >= bounds)
1366 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1367 JSValueRef arguments[2];
1368 arguments[0] = CYCastJSValue(context, index);
1369 arguments[1] = CYCastJSValue(context, 1);
1370 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1371 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1372 } CYObjectiveCatch }
1374 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1375 size_t bounds([self count]);
1376 if (index >= bounds)
1377 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1378 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1379 } CYObjectiveCatch }
1383 // XXX: inherit from or replace with CYJSObject
1384 @interface CYInternal : NSObject {
1385 JSGlobalContextRef context_;
1386 JSObjectRef object_;
1391 @implementation CYInternal
1393 - (void) dealloc { CYObjectiveTry {
1394 JSValueUnprotect(context_, object_);
1395 JSGlobalContextRelease(context_);
1397 } CYObjectiveCatch }
1399 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1400 if ((self = [super init]) != nil) {
1401 context_ = CYGetJSContext(context);
1402 JSGlobalContextRetain(context_);
1404 } CYObjectiveCatch }
1406 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1407 if (object_ == NULL)
1410 return JSObjectHasProperty(context, object_, name);
1413 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1414 if (object_ == NULL)
1417 return CYGetProperty(context, object_, name);
1420 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1421 @synchronized (self) {
1422 if (object_ == NULL) {
1423 object_ = JSObjectMake(context, NULL, NULL);
1424 JSValueProtect(context, object_);
1428 CYSetProperty(context, object_, name, value);
1431 + (CYInternal *) get:(id)object {
1433 if (&objc_getAssociatedObject == NULL)
1436 @synchronized (object) {
1437 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1445 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1447 if (&objc_getAssociatedObject == NULL)
1450 @synchronized (object) {
1451 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1454 if (&objc_setAssociatedObject == NULL)
1457 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1458 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1468 static JSValueRef CYCastJSValue(JSContextRef context, SEL sel) {
1470 return CYJSNull(context);
1471 return Selector_privateData::Make(context, sel);
1474 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1475 if (JSValueIsObjectOfClass(context, value, Selector_privateData::Class_)) {
1476 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1477 return reinterpret_cast<SEL>(internal->value_);
1480 return sel_registerName(CYPoolCString(pool, context, value));
1484 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1485 return (void *) [[NSAutoreleasePool alloc] init];
1486 } CYSadCatch(NULL) }
1488 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1489 return [(NSAutoreleasePool *) handle release];
1492 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1493 CYCallFunction(pool, context, cif, function, value, values);
1496 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, const sig::Signature *signature) {
1498 if (JSValueIsNull(context, value))
1500 JSObjectRef object(CYCastJSObject(context, value));
1502 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1503 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_;
1505 if (JSValueIsObjectOfClass(context, object, Instance::Class_)) {
1506 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_ == nil);
1510 _assert(JSObjectIsFunction(context, object));
1512 _assert(signature != NULL);
1513 _assert(signature->count != 0);
1515 sig::Signature modified;
1516 modified.count = signature->count + 1;
1517 modified.elements = new(pool) sig::Element[modified.count];
1519 modified.elements[0] = signature->elements[0];
1520 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1522 modified.elements[1].name = NULL;
1523 modified.elements[1].type = new(pool) sig::Object();
1524 modified.elements[1].offset = _not(size_t);
1526 return CYMakeBlock(context, object, modified);
1534 void Block::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1535 // XXX: this function might not handle the idea of a null pool
1536 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &signature);
1539 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1540 void Object::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1541 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1544 void Meta::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1545 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1548 void Selector::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1549 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1552 JSValueRef Object::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1553 NSObject *value(*reinterpret_cast<NSObject **>(data));
1555 return CYJSNull(context);
1556 JSObjectRef object(CYMakeInstance(context, value));
1559 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1561 if ((internal->flags_ & Instance::Uninitialized) != 0) {
1562 internal->flags_ = static_cast<Instance::Flags>(internal->flags_ & ~Instance::Uninitialized);
1563 _assert(internal->value_ == nil);
1564 internal->value_ = value;
1573 JSValueRef Meta::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1574 if (Class value = *reinterpret_cast<Class *>(data))
1575 return CYMakeInstance(context, value, Instance::Permanent);
1576 return CYJSNull(context);
1579 JSValueRef Selector::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1580 return CYCastJSValue(context, *reinterpret_cast<SEL *>(data));
1583 JSValueRef Block::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1584 return CYCastJSValue(context, *reinterpret_cast<NSObject **>(data));
1589 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1590 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1594 method_getReturnType(method, type, sizeof(type));
1599 // XXX: possibly use a more "awesome" check?
1603 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1604 JSObjectRef _this(CYCastJSObject(context, values[0]));
1605 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1608 JSObjectRef Message_privateData::Make(JSContextRef context, SEL sel, const char *type, IMP value) {
1609 Message_privateData *internal(new Message_privateData(sel, type, value));
1610 return JSObjectMake(context, Message_privateData::Class_, internal);
1613 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1614 JSObjectRef function(CYCastJSObject(context, value));
1616 sig::Signature signature;
1617 sig::Parse(pool, &signature, encoding, &Structor_);
1618 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1619 // XXX: see notes in Library.cpp about needing to leak
1620 return reinterpret_cast<IMP>(internal->value_);
1623 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1624 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1625 Class _class(internal->value_);
1628 const char *name(CYPoolCString(pool, context, property));
1630 if (SEL sel = sel_getUid(name))
1631 if (class_getInstanceMethod(_class, sel) != NULL)
1637 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1638 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1639 Class _class(internal->value_);
1642 const char *name(CYPoolCString(pool, context, property));
1644 if (SEL sel = sel_getUid(name))
1645 if (objc_method *method = class_getInstanceMethod(_class, sel))
1646 return Message_privateData::Make(context, sel, method_getTypeEncoding(method), method_getImplementation(method));
1651 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1652 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1653 Class _class(internal->value_);
1656 const char *name(CYPoolCString(pool, context, property));
1657 SEL sel(sel_registerName(name));
1662 if (JSValueIsObjectOfClass(context, value, Message_privateData::Class_)) {
1663 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1664 type = sig::Unparse(pool, &message->signature_);
1665 imp = reinterpret_cast<IMP>(message->value_);
1666 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1667 type = method_getTypeEncoding(method);
1668 imp = CYMakeMessage(context, value, type);
1669 } else _assert(false);
1671 objc_method *method(NULL);
1673 objc_method **methods(class_copyMethodList(_class, &size));
1674 for (size_t i(0); i != size; ++i)
1675 if (sel_isEqual(method_getName(methods[i]), sel)) {
1676 method = methods[i];
1682 method_setImplementation(method, imp);
1684 class_addMethod(_class, sel, imp, type);
1689 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1690 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1691 Class _class(internal->value_);
1694 objc_method **data(class_copyMethodList(_class, &size));
1695 for (size_t i(0); i != size; ++i)
1696 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1700 static bool CYHasImplicitProperties(JSContextRef context, Class _class) {
1701 if (!CYCastBool(context, CYGetCachedValue(context, CYJSString("cydget"))))
1703 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1704 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1706 return [_class cy$hasImplicitProperties];
1709 static objc_property_t CYFindProperty(CYPool &pool, Class _class, const char *name) {
1712 if (objc_property_t property = class_getProperty(_class, name))
1716 /* // XXX: I don't think any of this is required
1718 Protocol **protocols(class_copyProtocolList(_class, &count));
1719 // XXX: just implement a scope guard already :/
1720 pool.atexit(free, protocols);
1722 for (unsigned int i(0); i != count; ++i)
1723 if (objc_property_t property = protocol_getProperty(protocols[i], name, true, true))
1726 return CYFindProperty(pool, class_getSuperclass(_class), name); */
1729 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1730 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1731 id self(internal->value_);
1733 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1737 NSString *name(CYCastNSString(&pool, context, property));
1739 if (CYInternal *internal = [CYInternal get:self])
1740 if ([internal hasProperty:property inContext:context])
1743 Class _class(object_getClass(self));
1746 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1747 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1748 if ([self cy$hasProperty:name])
1750 } CYPoolCatch(false)
1752 const char *string(CYPoolCString(pool, context, name));
1754 if (CYFindProperty(pool, _class, string) != NULL)
1757 if (CYHasImplicitProperties(context, _class))
1758 if (SEL sel = sel_getUid(string))
1759 if (CYImplements(self, _class, sel, true))
1765 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1766 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1767 id self(internal->value_);
1769 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1770 return Interior::Make(context, self, context, object);
1773 NSString *name(CYCastNSString(&pool, context, property));
1775 if (CYInternal *internal = [CYInternal get:self])
1776 if (JSValueRef value = [internal getProperty:property inContext:context])
1780 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1784 const char *string(CYPoolCString(pool, context, name));
1785 Class _class(object_getClass(self));
1787 if (objc_property_t property = CYFindProperty(pool, _class, string)) {
1788 PropertyAttributes attributes(property);
1789 SEL sel(sel_registerName(attributes.Getter()));
1790 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1793 if (CYHasImplicitProperties(context, _class))
1794 if (SEL sel = sel_getUid(string))
1795 if (CYImplements(self, _class, sel, true))
1796 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1801 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1802 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1803 id self(internal->value_);
1807 NSString *name(CYCastNSString(&pool, context, property));
1808 NSObject *data(CYCastNSObject(&pool, context, value));
1811 if ([self cy$setProperty:name to:data])
1813 } CYPoolCatch(false)
1815 const char *string(CYPoolCString(pool, context, name));
1816 Class _class(object_getClass(self));
1818 if (objc_property_t property = CYFindProperty(pool, _class, string)) {
1819 PropertyAttributes attributes(property);
1820 if (const char *setter = attributes.Setter()) {
1821 SEL sel(sel_registerName(setter));
1822 JSValueRef arguments[1] = {value};
1823 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1828 size_t length(strlen(string));
1830 char set[length + 5];
1836 if (string[0] != '\0') {
1837 set[3] = toupper(string[0]);
1838 memcpy(set + 4, string + 1, length - 1);
1841 set[length + 3] = ':';
1842 set[length + 4] = '\0';
1844 if (SEL sel = sel_getUid(set))
1845 if (CYImplements(self, _class, sel)) {
1846 JSValueRef arguments[1] = {value};
1847 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1851 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1852 [internal setProperty:property toValue:value inContext:context];
1859 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1860 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1861 id self(internal->value_);
1864 NSString *name(CYCastNSString(NULL, context, property));
1865 return [self cy$deleteProperty:name];
1866 } CYPoolCatch(false)
1867 } CYCatch(false) return /*XXX*/ false; }
1869 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1870 const char *name(sel_getName(method_getName(method)));
1871 if (strchr(name, ':') != NULL)
1874 const char *type(method_getTypeEncoding(method));
1875 if (type == NULL || *type == '\0' || *type == 'v')
1878 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1881 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1882 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1883 id self(internal->value_);
1886 Class _class(object_getClass(self));
1890 objc_property_t *data(class_copyPropertyList(_class, &size));
1891 for (size_t i(0); i != size; ++i)
1892 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1896 if (CYHasImplicitProperties(context, _class))
1897 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1899 objc_method **data(class_copyMethodList(current, &size));
1900 for (size_t i(0); i != size; ++i)
1901 Instance_getPropertyNames_message(names, data[i]);
1906 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1907 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1908 [self cy$getPropertyNames:names inContext:context];
1912 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1913 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1914 JSObjectRef value(CYMakeInstance(context, [internal->value_ alloc], Instance::Uninitialized));
1918 static const char *CYBlockEncoding(NSBlock *self) {
1919 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1920 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1922 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1923 descriptor += sizeof(BlockDescriptor1);
1924 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1925 descriptor += sizeof(BlockDescriptor2);
1926 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1927 return descriptor3->signature;
1930 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature) {
1931 const char *encoding(CYBlockEncoding(self));
1932 if (encoding == NULL)
1935 sig::Parse(pool, &signature, encoding, &Structor_);
1936 _assert(signature.count >= 2);
1938 _assert(dynamic_cast<sig::Object *>(signature.elements[1].type) != NULL);
1939 signature.elements[1] = signature.elements[0];
1941 ++signature.elements;
1947 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1948 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1949 id self(internal->value_);
1951 if (const char *encoding = CYBlockEncoding(self)) {
1957 sig::Signature signature;
1958 sig::Parse(pool, &signature, encoding, &Structor_);
1961 sig::sig_ffi_cif(pool, 0, signature, &cif);
1963 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1964 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1965 return CYCallFunction(pool, context, 1, setup, count, arguments, false, false, signature, &cif, function);
1969 CYThrow("NSBlock without signature field passed arguments");
1973 } CYPoolCatch(NULL);
1978 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1979 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1980 Class _class(internal->value_);
1981 if (!CYIsClass(_class))
1984 if (CYJSValueIsNSObject(context, instance)) {
1985 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1986 // XXX: this isn't always safe
1987 return [linternal->value_ isKindOfClass:_class];
1993 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1995 throw CYJSError(context, "incorrect number of arguments to Instance");
1997 id value(CYCastNSObject(&pool, context, arguments[0]));
1999 value = [NSNull null];
2000 return CYCastJSValue(context, [value cy$box]);
2003 static bool Interior_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2004 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2007 id self(internal->value_);
2008 const char *name(CYPoolCString(pool, context, property));
2010 if (object_getInstanceVariable(self, name, NULL) != NULL)
2016 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2017 length = CYCastDouble(encoding + 1);
2021 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2022 for (size_t i(0); i != size; ++i)
2023 if (ivars[i] == ivar)
2025 else if (ivar_getOffset(ivars[i]) == offset) {
2026 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2027 _assert(encoding != NULL);
2028 _assert(encoding[0] == 'b');
2029 shift += CYCastDouble(encoding + 1);
2034 static JSValueRef Interior_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2035 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2038 id self(internal->value_);
2039 const char *name(CYPoolCString(pool, context, property));
2041 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2042 ptrdiff_t offset(ivar_getOffset(ivar));
2043 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2045 const char *encoding(ivar_getTypeEncoding(ivar));
2046 _assert(encoding != NULL);
2047 _assert(encoding[0] != '\0');
2048 if (encoding[0] == 'b') {
2049 unsigned length, shift;
2050 CYBitField(length, shift, self, ivar, encoding, offset);
2051 _assert(shift + length <= sizeof(uintptr_t) * 8);
2052 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2053 uintptr_t mask((1 << length) - 1);
2054 return CYCastJSValue(context, (field >> shift) & mask);
2056 #if defined(__APPLE__) && defined(__LP64__)
2057 // XXX: maybe do even more verifications here
2058 if (strcmp(name, "isa") == 0)
2059 return CYCastJSValue(context, object_getClass(self));
2062 auto type(new(pool) Type_privateData(encoding));
2063 return type->type_->FromFFI(context, type->GetFFI(), data);
2070 static bool Interior_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2071 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2074 id self(internal->value_);
2075 const char *name(CYPoolCString(pool, context, property));
2077 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2078 ptrdiff_t offset(ivar_getOffset(ivar));
2079 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2081 const char *encoding(ivar_getTypeEncoding(ivar));
2082 _assert(encoding != NULL);
2083 if (encoding[0] == 'b') {
2084 unsigned length, shift;
2085 CYBitField(length, shift, self, ivar, encoding, offset);
2086 _assert(shift + length <= sizeof(uintptr_t) * 8);
2087 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2088 uintptr_t mask((1 << length) - 1);
2089 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2091 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2092 type->type_->PoolFFI(&pool, context, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2100 static void Interior_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2101 if (Class super = class_getSuperclass(_class))
2102 Interior_getPropertyNames_(super, names);
2105 objc_ivar **data(class_copyIvarList(_class, &size));
2106 for (size_t i(0); i != size; ++i)
2107 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2111 static void Interior_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2112 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2115 id self(internal->value_);
2116 Class _class(object_getClass(self));
2118 Interior_getPropertyNames_(_class, names);
2121 static JSValueRef Interior_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2122 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2123 return internal->owner_;
2126 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2128 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2131 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2133 NSString *name(CYCastNSString(&pool, context, property));
2134 if (Class _class = NSClassFromString(name))
2135 return CYMakeInstance(context, _class, Instance::Permanent);
2139 static Class *CYCopyClassList(size_t &size) {
2140 size = objc_getClassList(NULL, 0);
2141 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2144 size_t writ(objc_getClassList(data, size));
2150 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2161 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2163 if (Class *data = CYCopyClassList(size)) {
2164 for (size_t i(0); i != size; ++i)
2165 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2171 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2172 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2175 const char *name(CYPoolCString(pool, context, property));
2177 const char **data(objc_copyClassNamesForImage(internal, &size));
2179 for (size_t i(0); i != size; ++i)
2180 if (strcmp(name, data[i]) == 0) {
2181 if (Class _class = objc_getClass(name)) {
2182 value = CYMakeInstance(context, _class, Instance::Permanent);
2193 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2194 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2196 const char **data(objc_copyClassNamesForImage(internal, &size));
2197 for (size_t i(0); i != size; ++i)
2198 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2202 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2204 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2207 const char **data(objc_copyImageNames(&size));
2208 pool.atexit(free, data);
2210 for (size_t i(0); i != size; ++i)
2211 if (name == data[i]) {
2212 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2213 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2220 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2222 const char **data(objc_copyImageNames(&size));
2223 for (size_t i(0); i != size; ++i)
2224 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2229 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2231 const char *name(CYPoolCString(pool, context, property));
2232 if (Protocol *protocol = objc_getProtocol(name))
2233 return CYMakeInstance(context, protocol, Instance::Permanent);
2237 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2239 Protocol **data(objc_copyProtocolList(&size));
2240 for (size_t i(0); i != size; ++i)
2241 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2245 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2247 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2249 return CYJSNull(context);
2253 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2254 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2258 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2259 *data = reinterpret_cast<void *>(address);
2260 return KERN_SUCCESS;
2264 std::set<Class> query_;
2265 JSContextRef context_;
2266 JSObjectRef results_;
2269 struct CYObjectStruct {
2273 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2274 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2275 JSContextRef context(choice->context_);
2277 for (unsigned i(0); i != count; ++i) {
2278 vm_range_t &range(ranges[i]);
2279 void *data(reinterpret_cast<void *>(range.address));
2280 size_t size(range.size);
2282 if (size < sizeof(CYObjectStruct))
2285 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2286 #if defined(__APPLE__) && defined(__LP64__)
2287 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2289 Class isa(reinterpret_cast<Class>(pointers[0]));
2292 std::set<Class>::const_iterator result(choice->query_.find(isa));
2293 if (result == choice->query_.end())
2296 size_t needed(class_getInstanceSize(*result));
2297 // XXX: if (size < needed)
2299 size_t boundary(496);
2303 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2305 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2309 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2311 throw CYJSError(context, "choose() takes a class argument");
2313 CYGarbageCollect(context);
2316 id _class(CYCastNSObject(&pool, context, arguments[0]));
2318 vm_address_t *zones(NULL);
2320 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2321 _assert(error == KERN_SUCCESS);
2323 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2324 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2327 choice.context_ = context;
2328 choice.results_ = results;
2331 Class *classes(CYCopyClassList(number));
2332 _assert(classes != NULL);
2334 for (size_t i(0); i != number; ++i)
2335 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2336 if (current == _class) {
2337 choice.query_.insert(classes[i]);
2343 for (unsigned i(0); i != size; ++i) {
2344 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2345 if (zone == NULL || zone->introspect == NULL)
2348 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2356 #if defined(__i386__) || defined(__x86_64__)
2357 #define OBJC_MAX_STRUCT_BY_VALUE 8
2358 static int struct_forward_array[] = {
2359 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2360 #elif defined(__arm__)
2361 #define OBJC_MAX_STRUCT_BY_VALUE 1
2362 static int struct_forward_array[] = {
2364 #elif defined(__arm64__)
2367 #error missing objc-runtime-info
2371 static bool stret(ffi_type *ffi_type) {
2372 return ffi_type->type == FFI_TYPE_STRUCT && (
2373 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2374 struct_forward_array[ffi_type->size] != 0
2382 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2386 _class = object_getClass(self);
2390 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2391 imp = method_getImplementation(method);
2392 type = method_getTypeEncoding(method);
2397 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2398 type = CYPoolCString(pool, context, [method _typeString]);
2404 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2411 sig::Signature signature;
2412 sig::Parse(pool, &signature, type, &Structor_);
2415 sig::sig_ffi_cif(pool, 0, signature, &cif);
2419 if (stret(cif.rtype))
2420 imp = class_getMethodImplementation_stret(_class, _cmd);
2423 imp = class_getMethodImplementation(_class, _cmd);
2426 void (*function)() = reinterpret_cast<void (*)()>(imp);
2427 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, true, signature, &cif, function);
2430 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2432 throw CYJSError(context, "too few arguments to objc_msgSend");
2442 if (JSValueIsObjectOfClass(context, arguments[0], cy::Super::Class_)) {
2443 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2444 self = internal->value_;
2445 _class = internal->class_;;
2446 uninitialized = false;
2447 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2448 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2449 self = internal->value_;
2451 uninitialized = internal->IsUninitialized();
2453 internal->value_ = nil;
2455 self = CYCastNSObject(&pool, context, arguments[0]);
2457 uninitialized = false;
2461 return CYJSNull(context);
2463 _cmd = CYCastSEL(context, arguments[1]);
2465 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2468 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2469 return $objc_msgSend(context, object, _this, count, arguments);
2472 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2473 JSValueRef setup[count + 2];
2476 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2477 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2480 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2482 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2484 // XXX: handle Instance::Uninitialized?
2485 id self(CYCastNSObject(&pool, context, _this));
2489 setup[1] = &internal->sel_;
2491 return CYCallFunction(pool, context, 2, setup, count, arguments, false, true, internal->signature_, &internal->cif_, internal->value_);
2494 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2496 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2498 id self(CYCastNSObject(&pool, context, arguments[0]));
2499 Class _class(CYCastClass(pool, context, arguments[1]));
2500 return cy::Super::Make(context, self, _class);
2503 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2505 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2507 const char *name(CYPoolCString(pool, context, arguments[0]));
2508 return Selector_privateData::Make(context, sel_registerName(name));
2511 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2513 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2514 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2517 static JSValueRef Selector_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2518 return CYMakeType(context, sig::Selector());
2521 static JSValueRef Instance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2522 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2523 id self(internal->value_);
2524 if (CYIsClass(self))
2525 return CYMakeType(context, sig::Meta());
2526 return CYMakeType(context, sig::Object(class_getName(object_getClass(self))));
2529 static JSValueRef FunctionInstance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2530 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2533 if (!CYBlockSignature(pool, internal->value_, type.signature))
2534 return CYJSNull(context);
2535 return CYMakeType(context, type);
2538 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2539 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2540 return CYMakeInstance(context, object_getClass(internal->value_), Instance::Permanent);
2543 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2544 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2545 id self(internal->value_);
2546 if (!CYIsClass(self))
2547 return CYJSUndefined(context);
2548 return CYGetClassPrototype(context, self);
2551 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2552 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2553 id self(internal->value_);
2554 if (!CYIsClass(self))
2555 return CYJSUndefined(context);
2556 return Messages::Make(context, (Class) self);
2559 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2560 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2562 if (!CYJSValueIsNSObject(context, _this))
2565 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2566 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->value_, false, objects)));
2569 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2570 if (!CYJSValueIsNSObject(context, _this))
2573 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2574 id value(internal->value_);
2581 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2583 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2584 return CYJSUndefined(context);
2585 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2588 return CYCastJSValue(context, CYJSString(context, [value description]));
2590 } CYCatch(NULL) return /*XXX*/ NULL; }
2592 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2593 if (!CYJSValueIsNSObject(context, _this))
2596 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2597 id value(internal->value_);
2598 _assert(value != nil);
2600 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2603 if (JSValueRef result = [value cy$valueOfInContext:context])
2607 } CYCatch(NULL) return /*XXX*/ NULL; }
2609 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2610 if (!CYJSValueIsNSObject(context, _this))
2613 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2614 // XXX: but... but... THIS ISN'T A POINTER! :(
2615 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2616 } CYCatch(NULL) return /*XXX*/ NULL; }
2618 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2619 if (!CYJSValueIsNSObject(context, _this))
2622 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2623 id value(internal->value_);
2626 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2627 return CYCastJSValue(context, CYJSString(context, [value description]));
2629 } CYCatch(NULL) return /*XXX*/ NULL; }
2631 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2632 if (!CYJSValueIsNSObject(context, _this))
2635 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2636 id value(internal->value_);
2638 if (!CYIsClass(value))
2639 CYThrow("non-Class object cannot be used as Type");
2641 sig::Object type(class_getName(value));
2642 return CYMakeType(context, type);
2643 } CYCatch(NULL) return /*XXX*/ NULL; }
2645 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2646 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2647 return CYCastJSValue(context, sel_getName(internal->value_));
2650 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2651 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2654 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2655 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2656 const char *name(sel_getName(internal->value_));
2659 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2660 return CYCastJSValue(context, CYJSString(context, string));
2662 } CYCatch(NULL) return /*XXX*/ NULL; }
2664 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2666 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2669 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2670 SEL sel(internal->value_);
2672 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2673 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2674 const char *encoding(method_getTypeEncoding(method));
2676 sig::Function type(false);
2677 sig::Parse(pool, &type.signature, encoding, &Structor_);
2678 return CYMakeType(context, type);
2681 static JSStaticValue Selector_staticValues[2] = {
2682 {"$cyt", &Selector_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2683 {NULL, NULL, NULL, 0}
2686 static JSStaticValue Instance_staticValues[5] = {
2687 {"$cyt", &Instance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2688 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2689 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2690 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2691 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2692 {NULL, NULL, NULL, 0}
2695 static JSStaticValue FunctionInstance_staticValues[5] = {
2696 {"$cyt", &FunctionInstance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2697 // XXX: this is sadly a duplicate of Instance_staticValues
2698 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2699 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2700 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2701 {NULL, NULL, NULL, 0}
2704 static JSStaticFunction Instance_staticFunctions[6] = {
2705 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2706 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2707 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2708 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2709 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2713 static JSStaticFunction Class_staticFunctions[2] = {
2714 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2718 static JSStaticFunction Interior_staticFunctions[2] = {
2719 {"$cya", &Interior_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2723 static JSStaticFunction Selector_staticFunctions[5] = {
2724 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2725 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2726 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2727 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2732 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2733 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2734 } CYObjectiveCatch }
2737 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2738 NSArray_ = objc_getClass("NSArray");
2739 NSBlock_ = objc_getClass("NSBlock");
2740 NSDictionary_ = objc_getClass("NSDictionary");
2741 NSNumber_ = objc_getClass("NSNumber");
2742 NSString_ = objc_getClass("NSString");
2743 Object_ = objc_getClass("Object");
2746 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2748 // XXX: apparently, iOS now has both of these
2749 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2750 if (NSCFBoolean_ == nil)
2751 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2753 NSCFType_ = objc_getClass("NSCFType");
2755 NSZombie_ = objc_getClass("_NSZombie_");
2757 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2758 NSZombie_ = objc_getClass("NSZombie");
2761 JSClassDefinition definition;
2763 definition = kJSClassDefinitionEmpty;
2764 definition.className = "Instance";
2765 definition.staticValues = Instance_staticValues;
2766 definition.staticFunctions = Instance_staticFunctions;
2767 definition.hasProperty = &Instance_hasProperty;
2768 definition.getProperty = &Instance_getProperty;
2769 definition.setProperty = &Instance_setProperty;
2770 definition.deleteProperty = &Instance_deleteProperty;
2771 definition.getPropertyNames = &Instance_getPropertyNames;
2772 definition.callAsConstructor = &Instance_callAsConstructor;
2773 definition.hasInstance = &Instance_hasInstance;
2774 definition.finalize = &CYFinalize;
2775 Instance::Class_ = JSClassCreate(&definition);
2777 definition.className = "ArrayInstance";
2778 ArrayInstance_ = JSClassCreate(&definition);
2780 definition.className = "BooleanInstance";
2781 BooleanInstance_ = JSClassCreate(&definition);
2783 definition.className = "NumberInstance";
2784 NumberInstance_ = JSClassCreate(&definition);
2786 definition.className = "ObjectInstance";
2787 ObjectInstance_ = JSClassCreate(&definition);
2789 definition.className = "StringInstance";
2790 StringInstance_ = JSClassCreate(&definition);
2792 definition.className = "FunctionInstance";
2793 definition.staticValues = FunctionInstance_staticValues;
2794 definition.callAsFunction = &FunctionInstance_callAsFunction;
2795 FunctionInstance_ = JSClassCreate(&definition);
2797 definition = kJSClassDefinitionEmpty;
2798 definition.className = "Class";
2799 definition.staticFunctions = Class_staticFunctions;
2800 ClassInstance_ = JSClassCreate(&definition);
2802 definition = kJSClassDefinitionEmpty;
2803 definition.className = "Interior";
2804 definition.staticFunctions = Interior_staticFunctions;
2805 definition.hasProperty = &Interior_hasProperty;
2806 definition.getProperty = &Interior_getProperty;
2807 definition.setProperty = &Interior_setProperty;
2808 definition.getPropertyNames = &Interior_getPropertyNames;
2809 definition.finalize = &CYFinalize;
2810 Interior::Class_ = JSClassCreate(&definition);
2812 definition = kJSClassDefinitionEmpty;
2813 definition.className = "Message";
2814 definition.staticFunctions = cy::Functor::StaticFunctions;
2815 definition.staticValues = cy::Functor::StaticValues;
2816 definition.callAsFunction = &Message_callAsFunction;
2817 definition.finalize = &CYFinalize;
2818 Message_privateData::Class_ = JSClassCreate(&definition);
2820 definition = kJSClassDefinitionEmpty;
2821 definition.className = "Messages";
2822 definition.hasProperty = &Messages_hasProperty;
2823 definition.getProperty = &Messages_getProperty;
2824 definition.setProperty = &Messages_setProperty;
2825 definition.getPropertyNames = &Messages_getPropertyNames;
2826 definition.finalize = &CYFinalize;
2827 Messages::Class_ = JSClassCreate(&definition);
2829 definition = kJSClassDefinitionEmpty;
2830 definition.className = "Selector";
2831 definition.staticValues = Selector_staticValues;
2832 definition.staticFunctions = Selector_staticFunctions;
2833 definition.callAsFunction = &Selector_callAsFunction;
2834 definition.finalize = &CYFinalize;
2835 Selector_privateData::Class_ = JSClassCreate(&definition);
2837 definition = kJSClassDefinitionEmpty;
2838 definition.className = "Super";
2839 definition.finalize = &CYFinalize;
2840 cy::Super::Class_ = JSClassCreate(&definition);
2842 definition = kJSClassDefinitionEmpty;
2843 definition.className = "ObjectiveC::Classes";
2844 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2845 definition.getProperty = &ObjectiveC_Classes_getProperty;
2846 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2847 ObjectiveC_Classes_ = JSClassCreate(&definition);
2849 definition = kJSClassDefinitionEmpty;
2850 definition.className = "ObjectiveC::Constants";
2851 definition.getProperty = &ObjectiveC_Constants_getProperty;
2852 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2853 ObjectiveC_Constants_ = JSClassCreate(&definition);
2856 definition = kJSClassDefinitionEmpty;
2857 definition.className = "ObjectiveC::Images";
2858 definition.getProperty = &ObjectiveC_Images_getProperty;
2859 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2860 ObjectiveC_Images_ = JSClassCreate(&definition);
2862 definition = kJSClassDefinitionEmpty;
2863 definition.className = "ObjectiveC::Image::Classes";
2864 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2865 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2866 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2869 definition = kJSClassDefinitionEmpty;
2870 definition.className = "ObjectiveC::Protocols";
2871 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2872 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2873 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2876 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2877 // XXX: this is horrible; there has to be a better way to do this
2879 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2881 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2887 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2888 JSObjectRef global(CYGetGlobalObject(context));
2889 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2890 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2891 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2892 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2894 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2895 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2897 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2898 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2899 CYArrayPush(context, alls, protocols);
2901 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2902 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2903 CYArrayPush(context, alls, classes);
2905 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2906 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2907 CYArrayPush(context, alls, constants);
2910 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2913 JSObjectRef Message(JSObjectMakeConstructor(context, Message_privateData::Class_, NULL));
2914 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_privateData::Class_, &Selector_new));
2915 JSObjectRef Super(JSObjectMakeConstructor(context, cy::Super::Class_, &Super_new));
2917 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance::Class_, &Instance_new));
2918 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2919 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2921 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2922 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2923 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2924 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2925 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2927 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2928 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2929 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2930 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2931 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2933 JSObjectRef ClassInstance(JSObjectMakeConstructor(context, ClassInstance_, NULL));
2934 JSObjectRef ClassInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ClassInstance, prototype_s)));
2935 CYSetProperty(context, cy, CYJSString("ClassInstance_prototype"), ClassInstance_prototype);
2936 // XXX: this doesn't fit the pattern of the other ones; maybe it sort of should?
2937 CYSetPrototype(context, ClassInstance_prototype, Instance_prototype);
2939 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2940 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2941 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2942 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2943 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2945 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2946 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2947 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2948 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2949 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2951 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2952 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2953 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2954 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2955 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2957 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2958 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2959 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2960 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2961 CYSetPrototype(context, StringInstance_prototype, String_prototype);
2963 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2964 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2965 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
2967 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2968 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
2971 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2974 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2976 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2977 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2979 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
2980 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
2981 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
2982 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::Object()), kJSPropertyAttributeDontEnum);
2983 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::Meta()), kJSPropertyAttributeDontEnum);
2984 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::Selector()), kJSPropertyAttributeDontEnum);
2986 CYSetProperty(context, cy, CYJSString("cydget"), CYCastJSValue(context, false));
2989 static void *CYObjectiveC_CastSymbol(const char *name) {
2991 #ifdef __GNU_LIBOBJC__
2992 else if (strcmp(name, "object_getClass") == 0)
2993 return reinterpret_cast<void *>(&object_getClass);
2998 static CYHook CYObjectiveCHook = {
2999 &CYObjectiveC_ExecuteStart,
3000 &CYObjectiveC_ExecuteEnd,
3001 &CYObjectiveC_CallFunction,
3002 &CYObjectiveC_Initialize,
3003 &CYObjectiveC_SetupContext,
3004 &CYObjectiveC_CastSymbol,
3007 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3009 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3010 CYSetupContext(context);
3011 JSObjectRef global(CYGetGlobalObject(context));
3012 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
3013 CYSetProperty(context, cy, CYJSString("cydget"), CYCastJSValue(context, true));
3014 } CYObjectiveCatch }
3016 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3019 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3020 utf8 = CYPoolCode(pool, utf8);
3022 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3023 size_t bytes(utf16.size * sizeof(uint16_t));
3024 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3025 memcpy(copy, utf16.data, bytes);
3029 } catch (const CYException &exception) {
3031 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];