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 static bool CYIsClass(id self) {
133 return class_isMetaClass(object_getClass(self));
136 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
138 /* Objective-C Pool Release {{{ */
139 void CYPoolRelease_(void *data) {
140 id object(reinterpret_cast<id>(data));
144 id CYPoolRelease_(CYPool *pool, id object) {
147 else if (pool == NULL)
148 return [object autorelease];
150 pool->atexit(CYPoolRelease_);
155 template <typename Type_>
156 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
157 return (Type_) CYPoolRelease_(pool, (id) object);
160 /* Objective-C Strings {{{ */
161 CYUTF8String CYPoolUTF8String(CYPool &pool, JSContextRef context, NSString *value) {
162 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
163 char *string(new(pool) char[size + 1]);
164 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
165 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
166 return CYUTF8String(string, [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
169 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
170 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
171 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
176 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
177 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
181 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
184 // XXX: this definition scares me; is anyone using this?!
185 NSString *string([value description]);
187 return CYCopyJSString(context, string);
190 return CYCopyJSString(CYPoolUTF8String(pool, context, string));
194 NSString *CYCopyNSString(const CYUTF8String &value) {
196 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
198 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
202 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
204 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
207 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
211 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
212 return CYCopyNSString(context, CYJSString(context, value));
215 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
216 return CYPoolRelease(pool, CYCopyNSString(value));
219 NSString *CYCastNSString(CYPool *pool, SEL sel) {
220 const char *name(sel_getName(sel));
221 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
224 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
225 return CYPoolRelease(pool, CYCopyNSString(context, value));
228 CYUTF8String CYCastUTF8String(NSString *value) {
229 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
230 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
234 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
236 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
237 if (exception == NULL)
239 *exception = CYCastJSValue(context, error);
242 size_t CYGetIndex(NSString *value) {
243 return CYGetIndex(CYCastUTF8String(value));
246 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
247 return CYGetOffset(CYPoolCString(pool, context, value), index);
250 static JSClassRef ArrayInstance_;
251 static JSClassRef BooleanInstance_;
252 static JSClassRef FunctionInstance_;
253 static JSClassRef NumberInstance_;
254 static JSClassRef ObjectInstance_;
255 static JSClassRef StringInstance_;
257 static JSClassRef ObjectiveC_Classes_;
258 static JSClassRef ObjectiveC_Constants_;
259 static JSClassRef ObjectiveC_Protocols_;
262 static JSClassRef ObjectiveC_Image_Classes_;
263 static JSClassRef ObjectiveC_Images_;
267 static Class __NSMallocBlock__;
268 static Class NSCFBoolean_;
269 static Class NSCFType_;
270 static Class NSGenericDeallocHandler_;
272 static Class NSBoolNumber_;
275 static Class NSArray_;
276 static Class NSBlock_;
277 static Class NSDictionary_;
278 static Class NSNumber_;
279 static Class NSString_;
280 static Class NSZombie_;
281 static Class Object_;
283 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
285 JSValueRef Prototype::GetPrototype(JSContextRef context) const {
287 if (value_ == NSCFBoolean_)
289 if (value_ == NSBoolNumber_)
291 return CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
292 if (value_ == NSArray_)
293 return CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
294 if (value_ == NSBlock_)
295 return CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
296 if (value_ == NSNumber_)
297 return CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
298 if (value_ == NSDictionary_)
299 return CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
300 if (value_ == NSString_)
301 return CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
303 if (Class super = class_getSuperclass(value_))
304 return CYPrivate<Prototype>::Cache(context, super);
305 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
308 JSValueRef Constructor::GetPrototype(JSContextRef context) const {
309 if (Class super = class_getSuperclass(value_))
310 return CYPrivate<Constructor>::Cache(context, super);
311 return CYGetCachedObject(context, CYJSString("Constructor_prototype"));
314 bool CYIsKindOfClass(id object, Class _class) {
315 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
321 JSValueRef Instance::GetPrototype(JSContextRef context) const {
322 return CYPrivate<Prototype>::Cache(context, object_getClass(value_));
325 JSClassRef Instance::GetClass(id object, Flags flags) {
326 return CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance::Class_;
329 Instance::Instance(id value, Flags flags) :
334 /*else if ([value retainCount] == NSUInteger(-1))
335 flags_ |= Instance::Permanent;*/
337 value_ = [value_ retain];
340 Instance::~Instance() {
345 struct Message_privateData :
348 static JSClassRef Class_;
352 Message_privateData(SEL sel, const char *type, IMP value) :
353 cy::Functor(reinterpret_cast<void (*)()>(value), type),
358 static JSObjectRef Make(JSContextRef context, SEL sel, const char *type, IMP value);
361 JSClassRef Message_privateData::Class_;
363 JSObjectRef CYMakeInstance(JSContextRef context, id object, Instance::Flags flags = Instance::None) {
364 _assert(object != nil);
367 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
369 if (weak != NULL && &JSWeakObjectMapGet != NULL)
370 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
374 JSObjectRef instance;
375 if (CYIsClass(object) && !class_isMetaClass(object))
376 instance = CYPrivate<Constructor>::Cache(context, object);
378 instance = Instance::Make(context, object, flags);
381 if (weak != NULL && &JSWeakObjectMapSet != NULL)
382 JSWeakObjectMapSet(context, weak, object, instance);
388 @interface NSMethodSignature (Cycript)
389 - (NSString *) _typeString;
392 @interface NSObject (Cycript)
394 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
395 - (JSType) cy$JSType;
397 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
398 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
400 - (bool) cy$hasProperty:(NSString *)name;
401 - (NSObject *) cy$getProperty:(NSString *)name;
402 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
403 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
404 - (bool) cy$deleteProperty:(NSString *)name;
405 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
407 + (bool) cy$hasImplicitProperties;
413 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
416 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
417 _assert(value != nil);
419 Class _class(object_getClass(value));
421 if (class_isMetaClass(_class)) {
422 const char *name(class_getName(value));
423 if (class_isMetaClass(value))
424 return [NSString stringWithFormat:@"object_getClass(%s)", name];
426 return [NSString stringWithUTF8String:name];
429 if (_class == NSZombie_)
430 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
432 SEL sel(@selector(cy$toCYON:inSet:));
434 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
435 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
436 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
437 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
438 return [value cy$toCYON:objective inSet:objects];
440 return [NSString stringWithFormat:@"%@", value];
443 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
445 return CYCastNSCYON(value, objective, *objects);
447 std::set<void *> objects;
448 return CYCastNSCYON(value, objective, objects);
452 struct PropertyAttributes {
457 const char *variable;
470 PropertyAttributes(objc_property_t property) :
482 name = property_getName(property);
483 const char *attributes(property_getAttributes(property));
485 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
486 if ((next = strchr(token, ',')) != NULL)
489 case 'R': readonly = true; break;
490 case 'C': copy = true; break;
491 case '&': retain = true; break;
492 case 'N': nonatomic = true; break;
493 case 'G': getter_ = token + 1; break;
494 case 'S': setter_ = token + 1; break;
495 case 'V': variable = token + 1; break;
499 /*if (variable == NULL) {
500 variable = property_getName(property);
501 size_t size(strlen(variable));
502 char *name(new(pool_) char[size + 2]);
504 memcpy(name + 1, variable, size);
505 name[size + 1] = '\0';
510 const char *Getter() {
512 getter_ = pool_.strdup(name);
516 const char *Setter() {
517 if (setter_ == NULL && !readonly) {
518 size_t length(strlen(name));
520 char *temp(new(pool_) char[length + 5]);
526 temp[3] = toupper(name[0]);
527 memcpy(temp + 4, name + 1, length - 1);
530 temp[length + 3] = ':';
531 temp[length + 4] = '\0';
540 @interface CYWebUndefined : NSObject {
543 + (CYWebUndefined *) undefined;
547 @implementation CYWebUndefined
549 + (CYWebUndefined *) undefined {
550 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
556 #define WebUndefined CYWebUndefined
558 /* Bridge: CYJSObject {{{ */
559 @interface CYJSObject : NSMutableDictionary {
561 JSGlobalContextRef context_;
564 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
566 - (NSUInteger) count;
567 - (id) objectForKey:(id)key;
568 - (NSEnumerator *) keyEnumerator;
569 - (void) setObject:(id)object forKey:(id)key;
570 - (void) removeObjectForKey:(id)key;
574 /* Bridge: CYJSArray {{{ */
575 @interface CYJSArray : NSMutableArray {
577 JSGlobalContextRef context_;
580 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
582 - (NSUInteger) count;
583 - (id) objectAtIndex:(NSUInteger)index;
585 - (void) addObject:(id)anObject;
586 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
587 - (void) removeLastObject;
588 - (void) removeObjectAtIndex:(NSUInteger)index;
589 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
594 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
595 return JSValueIsObjectOfClass(context, value, Instance::Class_) || JSValueIsObjectOfClass(context, value, FunctionInstance_) || JSValueIsObjectOfClass(context, value, CYPrivate<Constructor>::Class_);
598 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
599 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
603 struct CYBlockDescriptor {
605 BlockDescriptor1 one_;
606 BlockDescriptor2 two_;
607 BlockDescriptor3 three_;
610 Closure_privateData *internal_;
613 void CYDisposeBlock(BlockLiteral *literal) {
614 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
617 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
618 JSObjectRef _this(CYCastJSObject(context, values[0]));
619 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
622 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
623 _assert(__NSMallocBlock__ != Nil);
624 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
626 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
627 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
629 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockAdapter_);
630 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->value_);
632 literal->isa = __NSMallocBlock__;
633 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
634 literal->reserved = 0;
635 literal->descriptor = descriptor;
637 descriptor->d_.one_.size = sizeof(descriptor->d_);
638 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
639 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
641 return reinterpret_cast<NSBlock *>(literal);
645 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
646 if (CYJSValueIsNSObject(context, object)) {
647 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
648 return internal->value_;
651 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
652 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
653 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
656 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
657 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
661 @interface NSBoolNumber : NSNumber {
666 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
670 switch (JSType type = JSValueGetType(context, value)) {
671 case kJSTypeUndefined:
672 object = [WebUndefined undefined];
682 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
685 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
691 object = CYCopyNSNumber(context, value);
696 object = CYCopyNSString(context, value);
701 // XXX: this might could be more efficient
702 object = CYCastNSObject(pool, context, (JSObjectRef) value);
707 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
714 return CYPoolRelease(pool, object);
716 return [object retain];
719 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
720 return CYNSObject(pool, context, value, true);
723 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
724 return CYNSObject(&pool, context, value, false);
727 /* Bridge: NSArray {{{ */
728 @implementation NSArray (Cycript)
731 return [[self mutableCopy] autorelease];
734 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
735 _oassert(objects.insert(self).second);
737 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
738 [json appendString:@"@["];
742 for (id object in self) {
744 for (size_t index(0), count([self count]); index != count; ++index) {
745 id object([self objectAtIndex:index]);
748 [json appendString:@","];
751 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
752 [json appendString:CYCastNSCYON(object, true, objects)];
754 [json appendString:@","];
759 [json appendString:@"]"];
763 - (bool) cy$hasProperty:(NSString *)name {
764 if ([name isEqualToString:@"length"])
767 size_t index(CYGetIndex(name));
768 if (index == _not(size_t) || index >= [self count])
769 return [super cy$hasProperty:name];
774 - (NSObject *) cy$getProperty:(NSString *)name {
775 size_t index(CYGetIndex(name));
776 if (index == _not(size_t) || index >= [self count])
777 return [super cy$getProperty:name];
779 return [self objectAtIndex:index];
782 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
784 if ([name isEqualToString:@"length"])
785 return CYCastJSValue(context, [self count]);
788 return [super cy$getProperty:name inContext:context];
791 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
792 [super cy$getPropertyNames:names inContext:context];
794 for (size_t index(0), count([self count]); index != count; ++index) {
795 id object([self objectAtIndex:index]);
796 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
798 sprintf(name, "%zu", index);
799 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
804 + (bool) cy$hasImplicitProperties {
810 /* Bridge: NSBlock {{{ */
812 @interface NSBlock : NSObject
816 static const char *CYBlockEncoding(NSBlock *self);
817 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature);
819 @implementation NSBlock (Cycript)
821 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
825 if (!CYBlockSignature(pool, self, type.signature))
826 return [super cy$toCYON:objective inSet:objects];
827 _oassert(objects.insert(self).second);
829 CYType *typed((new(pool) CYTypeExpression(CYDecodeType(pool, &type)))->typed_);
830 CYTypeModifier *&modifier(CYGetLast(typed->modifier_));
831 CYTypeBlockWith *with(dynamic_cast<CYTypeBlockWith *>(modifier));
832 _assert(with != NULL);
833 CYObjCBlock *block(new(pool) CYObjCBlock(typed, with->parameters_, NULL));
836 std::ostringstream str;
838 CYOutput out(*str.rdbuf(), options);
839 block->Output(out, CYNoFlags);
841 std::string value(str.str());
842 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
848 /* Bridge: NSBoolNumber {{{ */
850 @implementation NSBoolNumber (Cycript)
852 - (JSType) cy$JSType {
853 return kJSTypeBoolean;
856 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
857 NSString *value([self boolValue] ? @"true" : @"false");
858 return objective ? value : [NSString stringWithFormat:@"@%@", value];
861 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
862 return CYCastJSValue(context, (bool) [self boolValue]);
868 /* Bridge: NSDictionary {{{ */
869 @implementation NSDictionary (Cycript)
872 return [[self mutableCopy] autorelease];
875 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
876 _oassert(objects.insert(self).second);
878 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
879 [json appendString:@"@{"];
883 for (NSObject *key in self) {
885 NSEnumerator *keys([self keyEnumerator]);
886 while (NSObject *key = [keys nextObject]) {
889 [json appendString:@","];
892 [json appendString:CYCastNSCYON(key, true, objects)];
893 [json appendString:@":"];
894 NSObject *object([self objectForKey:key]);
895 [json appendString:CYCastNSCYON(object, true, objects)];
898 [json appendString:@"}"];
902 - (bool) cy$hasProperty:(NSString *)name {
903 return [self objectForKey:name] != nil;
906 - (NSObject *) cy$getProperty:(NSString *)name {
907 return [self objectForKey:name];
910 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
911 [super cy$getPropertyNames:names inContext:context];
914 for (NSObject *key in self) {
916 NSEnumerator *keys([self keyEnumerator]);
917 while (NSObject *key = [keys nextObject]) {
919 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
923 + (bool) cy$hasImplicitProperties {
929 /* Bridge: NSMutableArray {{{ */
930 @implementation NSMutableArray (Cycript)
932 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
933 if ([name isEqualToString:@"length"]) {
934 // XXX: is this not intelligent?
935 NSNumber *number(reinterpret_cast<NSNumber *>(value));
936 NSUInteger size([number unsignedIntegerValue]);
937 NSUInteger count([self count]);
939 [self removeObjectsInRange:NSMakeRange(size, count - size)];
940 else if (size != count) {
941 WebUndefined *undefined([WebUndefined undefined]);
942 for (size_t i(count); i != size; ++i)
943 [self addObject:undefined];
948 size_t index(CYGetIndex(name));
949 if (index == _not(size_t))
950 return [super cy$setProperty:name to:value];
952 id object(value ?: [NSNull null]);
954 size_t count([self count]);
956 [self replaceObjectAtIndex:index withObject:object];
958 if (index != count) {
959 WebUndefined *undefined([WebUndefined undefined]);
960 for (size_t i(count); i != index; ++i)
961 [self addObject:undefined];
964 [self addObject:object];
970 - (bool) cy$deleteProperty:(NSString *)name {
971 size_t index(CYGetIndex(name));
972 if (index == _not(size_t) || index >= [self count])
973 return [super cy$deleteProperty:name];
974 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
980 /* Bridge: NSMutableDictionary {{{ */
981 @implementation NSMutableDictionary (Cycript)
983 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
984 [self setObject:(value ?: [NSNull null]) forKey:name];
988 - (bool) cy$deleteProperty:(NSString *)name {
989 if ([self objectForKey:name] == nil)
992 [self removeObjectForKey:name];
999 /* Bridge: NSNumber {{{ */
1000 @implementation NSNumber (Cycript)
1002 - (JSType) cy$JSType {
1004 // XXX: this just seems stupid
1005 if ([self class] == NSCFBoolean_)
1006 return kJSTypeBoolean;
1008 return kJSTypeNumber;
1011 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1012 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1013 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1016 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1017 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1018 } CYObjectiveCatch }
1022 /* Bridge: NSNull {{{ */
1023 @implementation NSNull (Cycript)
1025 - (JSType) cy$JSType {
1029 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1030 NSString *value(@"null");
1031 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1034 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1035 return CYJSNull(context);
1036 } CYObjectiveCatch }
1040 /* Bridge: NSObject {{{ */
1041 @implementation NSObject (Cycript)
1047 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1048 return [self cy$valueOfInContext:context];
1051 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1053 } CYObjectiveCatch }
1055 - (JSType) cy$JSType {
1056 return kJSTypeObject;
1059 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1060 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1063 - (bool) cy$hasProperty:(NSString *)name {
1067 - (NSObject *) cy$getProperty:(NSString *)name {
1071 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1072 if (NSObject *value = [self cy$getProperty:name])
1073 return CYCastJSValue(context, value);
1075 } CYObjectiveCatch }
1077 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1081 - (bool) cy$deleteProperty:(NSString *)name {
1085 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1088 + (bool) cy$hasImplicitProperties {
1094 /* Bridge: NSOrderedSet {{{ */
1096 @implementation NSOrderedSet (Cycript)
1098 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1099 _oassert(objects.insert(self).second);
1101 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1102 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1103 [json appendString:CYCastNSCYON([self array], true, objects)];
1104 [json appendString:@"]]"];
1111 /* Bridge: NSProxy {{{ */
1112 @implementation NSProxy (Cycript)
1114 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1115 return [[self description] cy$toCYON:objective inSet:objects];
1120 /* Bridge: NSSet {{{ */
1121 @implementation NSSet (Cycript)
1123 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1124 _oassert(objects.insert(self).second);
1126 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1127 [json appendString:@"[NSSet setWithArray:"];
1128 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1129 [json appendString:@"]]"];
1135 /* Bridge: NSString {{{ */
1136 @implementation NSString (Cycript)
1139 return [[self copy] autorelease];
1142 - (JSType) cy$JSType {
1143 return kJSTypeString;
1146 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1147 std::ostringstream str;
1150 CYUTF8String string(CYCastUTF8String(self));
1151 CYStringify(str, string.data, string.size, true);
1152 std::string value(str.str());
1153 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1156 - (bool) cy$hasProperty:(NSString *)name {
1157 size_t index(CYGetIndex(name));
1158 if (index == _not(size_t) || index >= [self length])
1159 return [super cy$hasProperty:name];
1164 - (NSObject *) cy$getProperty:(NSString *)name {
1165 size_t index(CYGetIndex(name));
1166 if (index == _not(size_t) || index >= [self length])
1167 return [super cy$getProperty:name];
1169 return [self substringWithRange:NSMakeRange(index, 1)];
1172 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1173 [super cy$getPropertyNames:names inContext:context];
1175 for (size_t index(0), length([self length]); index != length; ++index) {
1177 sprintf(name, "%zu", index);
1178 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1182 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1183 return CYCastJSValue(context, CYJSString(context, self));
1184 } CYObjectiveCatch }
1188 /* Bridge: WebUndefined {{{ */
1189 @implementation WebUndefined (Cycript)
1191 - (JSType) cy$JSType {
1192 return kJSTypeUndefined;
1195 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1196 NSString *value(@"undefined");
1197 return value; // XXX: maybe use the below code, adding @undefined?
1198 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1201 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1202 return CYJSUndefined(context);
1203 } CYObjectiveCatch }
1208 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1209 id self(CYCastNSObject(&pool, context, value));
1210 if (CYIsClass(self))
1211 return (Class) self;
1212 throw CYJSError(context, "got something that is not a Class");
1216 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1218 size_t size(JSPropertyNameArrayGetCount(names));
1219 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1220 for (size_t index(0); index != size; ++index)
1221 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1225 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) {
1227 return CYJSNull(context);
1228 return CYMakeInstance(context, value);
1231 @implementation CYJSObject
1233 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1234 if ((self = [super init]) != nil) {
1236 context_ = CYGetJSContext(context);
1237 JSGlobalContextRetain(context_);
1238 JSValueProtect(context_, object_);
1240 } CYObjectiveCatch }
1242 - (void) dealloc { CYObjectiveTry {
1243 JSValueUnprotect(context_, object_);
1244 JSGlobalContextRelease(context_);
1246 } CYObjectiveCatch }
1248 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1250 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1252 return [super cy$toCYON:objective inSet:objects];
1254 return [NSString stringWithUTF8String:cyon];
1255 } CYObjectiveCatch }
1257 - (NSUInteger) count { CYObjectiveTry {
1258 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1259 size_t size(JSPropertyNameArrayGetCount(names));
1260 JSPropertyNameArrayRelease(names);
1262 } CYObjectiveCatch }
1264 - (id) objectForKey:(id)key { CYObjectiveTry {
1265 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1266 if (JSValueIsUndefined(context, value))
1268 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1269 } CYObjectiveCatch }
1271 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1272 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1273 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1274 JSPropertyNameArrayRelease(names);
1276 } CYObjectiveCatch }
1278 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1279 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1280 } CYObjectiveCatch }
1282 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1283 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1284 } CYObjectiveCatch }
1288 @implementation CYJSArray
1290 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1292 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1293 } CYObjectiveCatch }
1295 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1296 if ((self = [super init]) != nil) {
1298 context_ = CYGetJSContext(context);
1299 JSGlobalContextRetain(context_);
1300 JSValueProtect(context_, object_);
1302 } CYObjectiveCatch }
1304 - (void) dealloc { CYObjectiveTry {
1305 JSValueUnprotect(context_, object_);
1306 JSGlobalContextRelease(context_);
1308 } CYObjectiveCatch }
1310 - (NSUInteger) count { CYObjectiveTry {
1311 return CYArrayLength(context, object_);
1312 } CYObjectiveCatch }
1314 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1315 size_t bounds([self count]);
1316 if (index >= bounds)
1317 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1318 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1319 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1320 } CYObjectiveCatch }
1322 - (void) addObject:(id)object { CYObjectiveTry {
1323 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1324 } CYObjectiveCatch }
1326 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1327 size_t bounds([self count] + 1);
1328 if (index >= bounds)
1329 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1330 JSValueRef arguments[3];
1331 arguments[0] = CYCastJSValue(context, index);
1332 arguments[1] = CYCastJSValue(context, 0);
1333 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1334 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1335 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1336 } CYObjectiveCatch }
1338 - (void) removeLastObject { CYObjectiveTry {
1339 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1340 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1341 } CYObjectiveCatch }
1343 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1344 size_t bounds([self count]);
1345 if (index >= bounds)
1346 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1347 JSValueRef arguments[2];
1348 arguments[0] = CYCastJSValue(context, index);
1349 arguments[1] = CYCastJSValue(context, 1);
1350 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1351 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1352 } CYObjectiveCatch }
1354 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1355 size_t bounds([self count]);
1356 if (index >= bounds)
1357 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1358 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1359 } CYObjectiveCatch }
1363 // XXX: inherit from or replace with CYJSObject
1364 @interface CYInternal : NSObject {
1365 JSGlobalContextRef context_;
1366 JSObjectRef object_;
1371 @implementation CYInternal
1373 - (void) dealloc { CYObjectiveTry {
1374 JSValueUnprotect(context_, object_);
1375 JSGlobalContextRelease(context_);
1377 } CYObjectiveCatch }
1379 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1380 if ((self = [super init]) != nil) {
1381 context_ = CYGetJSContext(context);
1382 JSGlobalContextRetain(context_);
1384 } CYObjectiveCatch }
1386 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1387 if (object_ == NULL)
1390 return JSObjectHasProperty(context, object_, name);
1393 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1394 if (object_ == NULL)
1397 return CYGetProperty(context, object_, name);
1400 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1401 @synchronized (self) {
1402 if (object_ == NULL) {
1403 object_ = JSObjectMake(context, NULL, NULL);
1404 JSValueProtect(context, object_);
1408 CYSetProperty(context, object_, name, value);
1411 + (CYInternal *) get:(id)object {
1413 if (&objc_getAssociatedObject == NULL)
1416 @synchronized (object) {
1417 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1425 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1427 if (&objc_getAssociatedObject == NULL)
1430 @synchronized (object) {
1431 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1434 if (&objc_setAssociatedObject == NULL)
1437 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1438 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1448 static JSValueRef CYCastJSValue(JSContextRef context, SEL sel) {
1450 return CYJSNull(context);
1451 return CYPrivate<Selector_privateData>::Make(context, sel);
1454 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1455 if (JSValueIsObjectOfClass(context, value, CYPrivate<Selector_privateData>::Class_)) {
1456 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1457 return reinterpret_cast<SEL>(internal->value_);
1460 return sel_registerName(CYPoolCString(pool, context, value));
1464 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1465 return (void *) [[NSAutoreleasePool alloc] init];
1466 } CYSadCatch(NULL) }
1468 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1469 return [(NSAutoreleasePool *) handle release];
1472 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1473 CYCallFunction(pool, context, cif, function, value, values);
1476 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, const sig::Signature *signature) {
1478 if (JSValueIsNull(context, value))
1480 JSObjectRef object(CYCastJSObject(context, value));
1482 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1483 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_;
1485 if (JSValueIsObjectOfClass(context, object, Instance::Class_)) {
1486 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_ == nil);
1490 _assert(JSObjectIsFunction(context, object));
1492 _assert(signature != NULL);
1493 _assert(signature->count != 0);
1495 sig::Signature modified;
1496 modified.count = signature->count + 1;
1497 modified.elements = new(pool) sig::Element[modified.count];
1499 modified.elements[0] = signature->elements[0];
1500 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1502 modified.elements[1].name = NULL;
1503 modified.elements[1].type = new(pool) sig::Object();
1504 modified.elements[1].offset = _not(size_t);
1506 return CYMakeBlock(context, object, modified);
1514 void Block::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1515 // XXX: this function actually needs to handle null pools as it is an autorelease
1516 _assert(pool != NULL);
1517 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &signature);
1520 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1521 void Object::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1522 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1525 void Meta::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1526 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1529 void Selector::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1530 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1533 JSValueRef Object::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1534 NSObject *value(*reinterpret_cast<NSObject **>(data));
1536 return CYJSNull(context);
1537 JSObjectRef object(CYMakeInstance(context, value));
1540 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1542 if (internal->IsUninitialized()) {
1543 internal->flags_ &= ~Instance::Uninitialized;
1544 if (internal->value_ == nil)
1545 internal->value_ = value;
1547 _assert(internal->value_ == value);
1556 JSValueRef Meta::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1557 if (Class value = *reinterpret_cast<Class *>(data))
1558 return CYMakeInstance(context, value, Instance::Permanent);
1559 return CYJSNull(context);
1562 JSValueRef Selector::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1563 return CYCastJSValue(context, *reinterpret_cast<SEL *>(data));
1566 JSValueRef Block::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1567 return CYCastJSValue(context, *reinterpret_cast<NSObject **>(data));
1572 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1573 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1577 method_getReturnType(method, type, sizeof(type));
1582 // XXX: possibly use a more "awesome" check?
1586 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1587 JSObjectRef _this(CYCastJSObject(context, values[0]));
1588 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1591 JSObjectRef Message_privateData::Make(JSContextRef context, SEL sel, const char *type, IMP value) {
1592 Message_privateData *internal(new Message_privateData(sel, type, value));
1593 return JSObjectMake(context, Message_privateData::Class_, internal);
1596 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1597 JSObjectRef function(CYCastJSObject(context, value));
1599 sig::Signature signature;
1600 sig::Parse(pool, &signature, encoding, &Structor_);
1601 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1602 // XXX: see notes in Library.cpp about needing to leak
1603 return reinterpret_cast<IMP>(internal->value_);
1606 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1607 auto internal(CYPrivate<Messages>::Get(context, object));
1608 Class _class(internal->GetClass());
1611 const char *name(CYPoolCString(pool, context, property));
1613 if (SEL sel = sel_getUid(name))
1614 if (class_getInstanceMethod(_class, sel) != NULL)
1620 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1621 auto internal(CYPrivate<Messages>::Get(context, object));
1622 Class _class(internal->GetClass());
1625 const char *name(CYPoolCString(pool, context, property));
1627 if (SEL sel = sel_getUid(name))
1628 if (objc_method *method = class_getInstanceMethod(_class, sel))
1629 return Message_privateData::Make(context, sel, method_getTypeEncoding(method), method_getImplementation(method));
1634 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1635 auto internal(CYPrivate<Messages>::Get(context, object));
1636 Class _class(internal->GetClass());
1639 const char *name(CYPoolCString(pool, context, property));
1640 SEL sel(sel_registerName(name));
1645 if (JSValueIsObjectOfClass(context, value, Message_privateData::Class_)) {
1646 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1647 type = sig::Unparse(pool, &message->signature_);
1648 imp = reinterpret_cast<IMP>(message->value_);
1649 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1650 type = method_getTypeEncoding(method);
1651 imp = CYMakeMessage(context, value, type);
1652 } else return false;
1654 objc_method *method(NULL);
1656 objc_method **methods(class_copyMethodList(_class, &size));
1657 pool.atexit(free, methods);
1659 for (size_t i(0); i != size; ++i)
1660 if (sel_isEqual(method_getName(methods[i]), sel)) {
1661 method = methods[i];
1666 method_setImplementation(method, imp);
1668 class_addMethod(_class, sel, imp, type);
1673 static JSValueRef Messages_complete_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1675 if (!CYCastBool(context, arguments[1]))
1676 return CYObjectMakeArray(context, 0, NULL);
1680 _assert(count == 1);
1682 CYUTF8String prefix(CYPoolUTF8String(pool, context, CYJSString(context, arguments[0])));
1684 auto internal(CYPrivate<Messages>::Get(context, _this));
1685 Class _class(internal->GetClass());
1688 objc_method **data(class_copyMethodList(_class, &size));
1689 pool.atexit(free, data);
1691 JSObjectRef array(NULL); {
1692 CYArrayBuilder<1024> values(context, array);
1694 for (size_t i(0); i != size; ++i) {
1695 CYUTF8String name(sel_getName(method_getName(data[i])));
1696 if (CYStartsWith(name, prefix))
1697 values(CYCastJSValue(context, CYJSString(name)));
1702 static bool CYHasImplicitProperties(JSContextRef context, Class _class) {
1703 if (!CYCastBool(context, CYGetCachedValue(context, CYJSString("cydget"))))
1705 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1706 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1708 return [_class cy$hasImplicitProperties];
1711 static objc_property_t CYFindProperty(CYPool &pool, Class _class, const char *name) {
1714 if (objc_property_t property = class_getProperty(_class, name))
1718 /* // XXX: I don't think any of this is required
1720 Protocol **protocols(class_copyProtocolList(_class, &count));
1721 // XXX: just implement a scope guard already :/
1722 pool.atexit(free, protocols);
1724 for (unsigned int i(0); i != count; ++i)
1725 if (objc_property_t property = protocol_getProperty(protocols[i], name, true, true))
1728 return CYFindProperty(pool, class_getSuperclass(_class), name); */
1731 static JSValueRef Constructor_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1732 auto internal(CYPrivate<Constructor>::Get(context, object));
1733 return CYPrivate<Interior>::Make(context, internal->value_, context, object);
1736 static bool Constructor_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1737 auto internal(CYPrivate<Constructor>::Get(context, object));
1738 Class _class(object_getClass(internal->value_));
1739 if (!CYHasImplicitProperties(context, _class))
1742 if (SEL sel = sel_getUid(CYPoolCString(pool, context, property)))
1743 if (CYImplements(internal->value_, _class, sel, true))
1748 static JSValueRef Constructor_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1749 auto internal(CYPrivate<Constructor>::Get(context, object));
1750 Class _class(object_getClass(internal->value_));
1751 if (!CYHasImplicitProperties(context, _class))
1754 if (SEL sel = sel_getUid(CYPoolCString(pool, context, property)))
1755 if (CYImplements(internal->value_, _class, sel, true))
1756 return CYSendMessage(pool, context, internal->value_, NULL, sel, 0, NULL, false);
1760 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1761 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1762 id self(internal->value_);
1764 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1768 NSString *name(CYCastNSString(&pool, context, property));
1770 if (CYInternal *internal = [CYInternal get:self])
1771 if ([internal hasProperty:property inContext:context])
1774 Class _class(object_getClass(self));
1777 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1778 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1779 if ([self cy$hasProperty:name])
1781 } CYPoolCatch(false)
1783 const char *string(CYPoolCString(pool, context, name));
1785 if (CYFindProperty(pool, _class, string) != NULL)
1788 if (CYHasImplicitProperties(context, _class))
1789 if (SEL sel = sel_getUid(string))
1790 if (CYImplements(self, _class, sel, true))
1796 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1797 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1798 id self(internal->value_);
1800 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1801 return CYPrivate<Interior>::Make(context, self, context, object);
1804 NSString *name(CYCastNSString(&pool, context, property));
1806 if (CYInternal *internal = [CYInternal get:self])
1807 if (JSValueRef value = [internal getProperty:property inContext:context])
1811 if (JSValueRef value = [self cy$getProperty:name inContext:context])
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 SEL sel(sel_registerName(attributes.Getter()));
1821 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1824 if (CYHasImplicitProperties(context, _class))
1825 if (SEL sel = sel_getUid(string))
1826 if (CYImplements(self, _class, sel, true))
1827 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1832 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1833 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1834 id self(internal->value_);
1838 NSString *name(CYCastNSString(&pool, context, property));
1839 NSObject *data(CYCastNSObject(&pool, context, value));
1842 if ([self cy$setProperty:name to:data])
1844 } CYPoolCatch(false)
1846 const char *string(CYPoolCString(pool, context, name));
1847 Class _class(object_getClass(self));
1849 if (objc_property_t property = CYFindProperty(pool, _class, string)) {
1850 PropertyAttributes attributes(property);
1851 if (const char *setter = attributes.Setter()) {
1852 SEL sel(sel_registerName(setter));
1853 JSValueRef arguments[1] = {value};
1854 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1859 size_t length(strlen(string));
1861 char set[length + 5];
1867 if (string[0] != '\0') {
1868 set[3] = toupper(string[0]);
1869 memcpy(set + 4, string + 1, length - 1);
1872 set[length + 3] = ':';
1873 set[length + 4] = '\0';
1875 if (SEL sel = sel_getUid(set))
1876 if (CYImplements(self, _class, sel)) {
1877 JSValueRef arguments[1] = {value};
1878 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1882 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1883 [internal setProperty:property toValue:value inContext:context];
1890 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1891 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1892 id self(internal->value_);
1895 NSString *name(CYCastNSString(NULL, context, property));
1896 return [self cy$deleteProperty:name];
1897 } CYPoolCatch(false)
1898 } CYCatch(false) return /*XXX*/ false; }
1900 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1901 const char *name(sel_getName(method_getName(method)));
1902 if (strchr(name, ':') != NULL)
1905 const char *type(method_getTypeEncoding(method));
1906 if (type == NULL || *type == '\0' || *type == 'v')
1909 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1912 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1913 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1914 id self(internal->value_);
1917 Class _class(object_getClass(self));
1921 objc_property_t *data(class_copyPropertyList(_class, &size));
1922 pool.atexit(free, data);
1924 for (size_t i(0); i != size; ++i)
1925 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1928 if (CYHasImplicitProperties(context, _class))
1929 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1931 objc_method **data(class_copyMethodList(current, &size));
1932 pool.atexit(free, data);
1934 for (size_t i(0); i != size; ++i)
1935 Instance_getPropertyNames_message(names, data[i]);
1939 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1940 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1941 [self cy$getPropertyNames:names inContext:context];
1945 static JSObjectRef Constructor_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1946 auto internal(CYPrivate<Constructor>::Get(context, object));
1947 JSObjectRef value(CYMakeInstance(context, [internal->value_ alloc], Instance::Uninitialized));
1951 static const char *CYBlockEncoding(NSBlock *self) {
1952 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1953 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1955 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1956 descriptor += sizeof(BlockDescriptor1);
1957 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1958 descriptor += sizeof(BlockDescriptor2);
1959 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1960 return descriptor3->signature;
1963 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature) {
1964 const char *encoding(CYBlockEncoding(self));
1965 if (encoding == NULL)
1968 sig::Parse(pool, &signature, encoding, &Structor_);
1969 _assert(signature.count >= 2);
1971 _assert(dynamic_cast<sig::Object *>(signature.elements[1].type) != NULL);
1972 signature.elements[1] = signature.elements[0];
1974 ++signature.elements;
1980 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1981 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1982 id self(internal->value_);
1984 if (const char *encoding = CYBlockEncoding(self)) {
1990 sig::Signature signature;
1991 sig::Parse(pool, &signature, encoding, &Structor_);
1994 sig::sig_ffi_cif(pool, 0, signature, &cif);
1996 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1997 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1998 return CYCallFunction(pool, context, 1, setup, count, arguments, false, false, signature, &cif, function);
2002 CYThrow("NSBlock without signature field passed arguments");
2006 } CYPoolCatch(NULL);
2011 static bool Constructor_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
2012 auto internal(CYPrivate<Constructor>::Get(context, constructor));
2013 Class _class(internal->value_);
2015 if (CYJSValueIsNSObject(context, instance)) {
2016 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2017 // XXX: this isn't always safe
2018 return [linternal->value_ isKindOfClass:_class];
2024 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2026 throw CYJSError(context, "incorrect number of arguments to Instance");
2028 id value(CYCastNSObject(&pool, context, arguments[0]));
2030 value = [NSNull null];
2031 return CYCastJSValue(context, [value cy$box]);
2034 static bool Interior_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2035 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2038 id self(internal->value_);
2039 const char *name(CYPoolCString(pool, context, property));
2041 if (object_getInstanceVariable(self, name, NULL) != NULL)
2047 static void CYBitField(CYPool &pool, unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2048 length = CYCastDouble(encoding + 1);
2052 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2053 pool.atexit(free, ivars);
2055 for (size_t i(0); i != size; ++i)
2056 if (ivars[i] == ivar)
2058 else if (ivar_getOffset(ivars[i]) == offset) {
2059 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2060 _assert(encoding != NULL);
2061 _assert(encoding[0] == 'b');
2062 shift += CYCastDouble(encoding + 1);
2066 static JSValueRef Interior_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2067 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2070 id self(internal->value_);
2071 const char *name(CYPoolCString(pool, context, property));
2073 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2074 ptrdiff_t offset(ivar_getOffset(ivar));
2075 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2077 const char *encoding(ivar_getTypeEncoding(ivar));
2078 _assert(encoding != NULL);
2079 _assert(encoding[0] != '\0');
2080 if (encoding[0] == 'b') {
2081 unsigned length, shift;
2082 CYBitField(pool, length, shift, self, ivar, encoding, offset);
2083 _assert(shift + length <= sizeof(uintptr_t) * 8);
2084 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2085 uintptr_t mask((1 << length) - 1);
2086 return CYCastJSValue(context, (field >> shift) & mask);
2088 #if defined(__APPLE__) && defined(__LP64__)
2089 // XXX: maybe do even more verifications here
2090 if (strcmp(name, "isa") == 0)
2091 return CYCastJSValue(context, object_getClass(self));
2094 auto type(new(pool) Type_privateData(encoding));
2095 return type->type_->FromFFI(context, type->GetFFI(), data);
2102 static bool Interior_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2103 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2106 id self(internal->value_);
2107 const char *name(CYPoolCString(pool, context, property));
2109 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2110 ptrdiff_t offset(ivar_getOffset(ivar));
2111 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2113 const char *encoding(ivar_getTypeEncoding(ivar));
2114 _assert(encoding != NULL);
2115 if (encoding[0] == 'b') {
2116 unsigned length, shift;
2117 CYBitField(pool, length, shift, self, ivar, encoding, offset);
2118 _assert(shift + length <= sizeof(uintptr_t) * 8);
2119 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2120 uintptr_t mask((1 << length) - 1);
2121 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2123 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2124 type->type_->PoolFFI(&pool, context, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2132 static void Interior_getPropertyNames_(CYPool &pool, Class _class, JSPropertyNameAccumulatorRef names) {
2133 if (Class super = class_getSuperclass(_class))
2134 Interior_getPropertyNames_(pool, super, names);
2137 objc_ivar **data(class_copyIvarList(_class, &size));
2138 pool.atexit(free, data);
2140 for (size_t i(0); i != size; ++i)
2141 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2144 static void Interior_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2145 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2148 id self(internal->value_);
2149 Class _class(object_getClass(self));
2151 Interior_getPropertyNames_(pool, _class, names);
2154 static JSValueRef Interior_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2155 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2156 return internal->owner_;
2159 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2161 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2164 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2166 NSString *name(CYCastNSString(&pool, context, property));
2167 if (Class _class = NSClassFromString(name))
2168 return CYMakeInstance(context, _class, Instance::Permanent);
2172 static Class *CYCopyClassList(size_t &size) {
2173 size = objc_getClassList(NULL, 0);
2174 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2177 size_t writ(objc_getClassList(data, size));
2183 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2194 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2198 if (Class *data = CYCopyClassList(size)) {
2199 pool.atexit(free, data);
2200 for (size_t i(0); i != size; ++i)
2201 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2206 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2207 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2210 const char *name(CYPoolCString(pool, context, property));
2213 const char **data(objc_copyClassNamesForImage(internal, &size));
2214 pool.atexit(free, data);
2217 for (size_t i(0); i != size; ++i)
2218 if (strcmp(name, data[i]) == 0) {
2219 if (Class _class = objc_getClass(name))
2220 return CYMakeInstance(context, _class, Instance::Permanent);
2228 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2229 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2233 const char **data(objc_copyClassNamesForImage(internal, &size));
2234 pool.atexit(free, data);
2236 for (size_t i(0); i != size; ++i)
2237 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2240 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2242 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2245 const char **data(objc_copyImageNames(&size));
2246 pool.atexit(free, data);
2248 for (size_t i(0); i != size; ++i)
2249 if (name == data[i]) {
2250 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2251 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2258 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2262 const char **data(objc_copyImageNames(&size));
2263 pool.atexit(free, data);
2265 for (size_t i(0); i != size; ++i)
2266 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2270 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2272 const char *name(CYPoolCString(pool, context, property));
2273 if (Protocol *protocol = objc_getProtocol(name))
2274 return CYMakeInstance(context, protocol, Instance::Permanent);
2278 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2282 Protocol **data(objc_copyProtocolList(&size));
2283 pool.atexit(free, data);
2285 for (size_t i(0); i != size; ++i)
2286 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2289 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2291 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2293 return CYJSNull(context);
2297 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2298 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2302 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2303 *data = reinterpret_cast<void *>(address);
2304 return KERN_SUCCESS;
2308 std::set<Class> query_;
2309 JSContextRef context_;
2310 JSObjectRef results_;
2313 struct CYObjectStruct {
2317 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2318 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2319 JSContextRef context(choice->context_);
2321 for (unsigned i(0); i != count; ++i) {
2322 vm_range_t &range(ranges[i]);
2323 void *data(reinterpret_cast<void *>(range.address));
2324 size_t size(range.size);
2326 if (size < sizeof(CYObjectStruct))
2329 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2330 #if defined(__APPLE__) && defined(__LP64__)
2331 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2333 Class isa(reinterpret_cast<Class>(pointers[0]));
2336 std::set<Class>::const_iterator result(choice->query_.find(isa));
2337 if (result == choice->query_.end())
2340 size_t needed(class_getInstanceSize(*result));
2341 // XXX: if (size < needed)
2343 size_t boundary(496);
2347 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2349 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2353 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2355 throw CYJSError(context, "choose() takes a class argument");
2357 CYGarbageCollect(context);
2360 id _class(CYCastNSObject(&pool, context, arguments[0]));
2362 vm_address_t *zones(NULL);
2364 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2365 _assert(error == KERN_SUCCESS);
2367 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2368 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2371 choice.context_ = context;
2372 choice.results_ = results;
2375 Class *classes(CYCopyClassList(number));
2376 _assert(classes != NULL);
2377 pool.atexit(free, classes);
2379 for (size_t i(0); i != number; ++i)
2380 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2381 if (current == _class) {
2382 choice.query_.insert(classes[i]);
2386 for (unsigned i(0); i != size; ++i) {
2387 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2388 if (zone == NULL || zone->introspect == NULL)
2391 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2399 #if defined(__i386__) || defined(__x86_64__)
2400 #define OBJC_MAX_STRUCT_BY_VALUE 8
2401 static int struct_forward_array[] = {
2402 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2403 #elif defined(__arm__)
2404 #define OBJC_MAX_STRUCT_BY_VALUE 1
2405 static int struct_forward_array[] = {
2407 #elif defined(__arm64__)
2410 #error missing objc-runtime-info
2414 static bool stret(ffi_type *ffi_type) {
2415 return ffi_type->type == FFI_TYPE_STRUCT && (
2416 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2417 struct_forward_array[ffi_type->size] != 0
2425 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2429 _class = object_getClass(self);
2433 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2434 imp = method_getImplementation(method);
2435 type = method_getTypeEncoding(method);
2440 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2441 type = CYPoolCString(pool, context, [method _typeString]);
2447 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2454 sig::Signature signature;
2455 sig::Parse(pool, &signature, type, &Structor_);
2458 sig::sig_ffi_cif(pool, 0, signature, &cif);
2462 if (stret(cif.rtype))
2463 imp = class_getMethodImplementation_stret(_class, _cmd);
2466 imp = class_getMethodImplementation(_class, _cmd);
2469 void (*function)() = reinterpret_cast<void (*)()>(imp);
2470 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, true, signature, &cif, function);
2473 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2475 throw CYJSError(context, "too few arguments to objc_msgSend");
2485 if (JSValueIsObjectOfClass(context, arguments[0], CYPrivate<cy::Super>::Class_)) {
2486 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2487 self = internal->value_;
2488 _class = internal->class_;;
2489 uninitialized = false;
2490 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2491 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2492 self = internal->value_;
2494 uninitialized = internal->IsUninitialized();
2495 if (uninitialized && [internal->value_ retainCount] != NSUInteger(-1))
2496 internal->value_ = nil;
2498 self = CYCastNSObject(&pool, context, arguments[0]);
2500 uninitialized = false;
2504 return CYJSNull(context);
2506 _cmd = CYCastSEL(context, arguments[1]);
2508 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2511 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2512 return $objc_msgSend(context, object, _this, count, arguments);
2515 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2516 JSValueRef setup[count + 2];
2519 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2520 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2523 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2525 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2527 // XXX: handle Instance::Uninitialized?
2528 id self(CYCastNSObject(&pool, context, _this));
2532 setup[1] = &internal->sel_;
2534 return CYCallFunction(pool, context, 2, setup, count, arguments, false, true, internal->signature_, &internal->cif_, internal->value_);
2537 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2539 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2541 id self(CYCastNSObject(&pool, context, arguments[0]));
2542 Class _class(CYCastClass(pool, context, arguments[1]));
2543 return CYPrivate<cy::Super>::Make(context, self, _class);
2546 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2548 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2550 const char *name(CYPoolCString(pool, context, arguments[0]));
2551 return CYPrivate<Selector_privateData>::Make(context, sel_registerName(name));
2554 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2556 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2557 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2560 static JSValueRef Selector_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2561 return CYMakeType(context, sig::Selector());
2564 static JSValueRef Instance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2565 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2566 id self(internal->value_);
2567 return CYMakeType(context, sig::Object(class_getName(object_getClass(self))));
2570 static JSValueRef FunctionInstance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2571 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2574 if (!CYBlockSignature(pool, internal->value_, type.signature))
2575 return CYJSNull(context);
2576 return CYMakeType(context, type);
2579 static JSValueRef Constructor_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2580 return CYMakeType(context, sig::Meta());
2583 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2584 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2585 return CYMakeInstance(context, object_getClass(internal->value_), Instance::Permanent);
2588 static JSValueRef Constructor_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2589 auto internal(CYPrivate<Constructor>::Get(context, object));
2590 return CYMakeInstance(context, object_getClass(internal->value_), Instance::Permanent);
2593 static JSValueRef Constructor_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2594 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2595 id self(internal->value_);
2596 return CYPrivate<Prototype>::Cache(context, self);
2599 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2600 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2602 if (!CYJSValueIsNSObject(context, _this))
2605 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2606 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->value_, false, objects)));
2609 static JSValueRef Constructor_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2610 auto internal(CYPrivate<Constructor>::Get(context, _this));
2611 return CYCastJSValue(context, CYJSString(class_getName(internal->value_)));
2614 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2615 if (!CYJSValueIsNSObject(context, _this))
2618 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2619 id value(internal->value_);
2626 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2628 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2629 return CYJSUndefined(context);
2630 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2633 return CYCastJSValue(context, CYJSString(context, [value description]));
2635 } CYCatch(NULL) return /*XXX*/ NULL; }
2637 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2638 if (!CYJSValueIsNSObject(context, _this))
2641 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2642 id value(internal->value_);
2643 _assert(value != nil);
2645 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2648 if (JSValueRef result = [value cy$valueOfInContext:context])
2652 } CYCatch(NULL) return /*XXX*/ NULL; }
2654 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2655 if (!CYJSValueIsNSObject(context, _this))
2657 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2658 // XXX: return CYMakePointer(context, internal->value_, sig::Object(class_getName(object_getClass(internal->value_))), NULL, object);
2659 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2660 } CYCatch(NULL) return /*XXX*/ NULL; }
2662 static JSValueRef Constructor_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2663 auto internal(CYPrivate<Constructor>::Get(context, object));
2664 // XXX: return CYMakePointer(context, internal->value_, sig::Meta(), NULL, object);
2665 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2666 } CYCatch(NULL) return /*XXX*/ NULL; }
2668 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2669 if (!CYJSValueIsNSObject(context, _this))
2672 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2673 id value(internal->value_);
2676 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2677 return CYCastJSValue(context, CYJSString(context, [value description]));
2679 } CYCatch(NULL) return /*XXX*/ NULL; }
2681 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2682 if (!CYJSValueIsNSObject(context, _this))
2685 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2686 id value(internal->value_);
2688 if (!CYIsClass(value))
2689 CYThrow("non-Class object cannot be used as Type");
2691 sig::Object type(class_getName(value));
2692 return CYMakeType(context, type);
2693 } CYCatch(NULL) return /*XXX*/ NULL; }
2695 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2696 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2697 return CYCastJSValue(context, sel_getName(internal->value_));
2700 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2701 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2704 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2705 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2706 const char *name(sel_getName(internal->value_));
2709 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2710 return CYCastJSValue(context, CYJSString(context, string));
2712 } CYCatch(NULL) return /*XXX*/ NULL; }
2714 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2716 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2719 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2720 SEL sel(internal->value_);
2722 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2723 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2724 const char *encoding(method_getTypeEncoding(method));
2726 sig::Function type(false);
2727 sig::Parse(pool, &type.signature, encoding, &Structor_);
2728 return CYMakeType(context, type);
2731 static JSStaticValue Selector_staticValues[2] = {
2732 {"$cyt", &Selector_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2733 {NULL, NULL, NULL, 0}
2736 static JSStaticValue Instance_staticValues[3] = {
2737 {"$cyt", &Instance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2738 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2739 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2740 {NULL, NULL, NULL, 0}
2743 static JSStaticValue FunctionInstance_staticValues[3] = {
2744 {"$cyt", &FunctionInstance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2745 // XXX: this is sadly a duplicate of Instance_staticValues
2746 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2747 {NULL, NULL, NULL, 0}
2750 static JSStaticFunction Instance_staticFunctions[6] = {
2751 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2752 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2753 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2754 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2755 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2759 static JSStaticFunction Messages_staticFunctions[2] = {
2760 {"cy$complete", &Messages_complete_callAsFunction, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2764 static JSStaticValue Constructor_staticValues[5] = {
2765 {"$cyi", &Constructor_getProperty_$cyi, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2766 {"$cyt", &Constructor_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2767 {"constructor", &Constructor_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2768 {"prototype", &Constructor_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2769 {NULL, NULL, NULL, 0}
2772 static JSStaticFunction Constructor_staticFunctions[5] = {
2773 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2774 {"toCYON", &Constructor_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2775 {"toPointer", &Constructor_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2779 static JSStaticFunction Interior_staticFunctions[2] = {
2780 {"$cya", &Interior_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2784 static JSStaticFunction Selector_staticFunctions[5] = {
2785 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2786 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2787 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2788 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2793 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2794 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2795 } CYObjectiveCatch }
2798 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2799 NSArray_ = objc_getClass("NSArray");
2800 NSBlock_ = objc_getClass("NSBlock");
2801 NSDictionary_ = objc_getClass("NSDictionary");
2802 NSNumber_ = objc_getClass("NSNumber");
2803 NSString_ = objc_getClass("NSString");
2804 Object_ = objc_getClass("Object");
2807 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2809 // XXX: apparently, iOS now has both of these
2810 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2811 if (NSCFBoolean_ == nil)
2812 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2814 NSCFType_ = objc_getClass("NSCFType");
2816 NSZombie_ = objc_getClass("_NSZombie_");
2818 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2819 NSZombie_ = objc_getClass("NSZombie");
2822 JSClassDefinition definition;
2824 definition = kJSClassDefinitionEmpty;
2825 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2826 definition.className = "Messages";
2827 definition.staticFunctions = Messages_staticFunctions;
2828 definition.hasProperty = &Messages_hasProperty;
2829 definition.getProperty = &Messages_getProperty;
2830 definition.setProperty = &Messages_setProperty;
2831 CYPrivate<Messages>::Class_ = JSClassCreate(&definition);
2833 definition = kJSClassDefinitionEmpty;
2834 definition.className = "Constructor";
2835 definition.parentClass = CYPrivate<Messages>::Class_;
2836 definition.staticValues = Constructor_staticValues;
2837 definition.staticFunctions = Constructor_staticFunctions;
2838 definition.hasInstance = &Constructor_hasInstance;
2839 definition.hasProperty = &Constructor_hasProperty;
2840 definition.getProperty = &Constructor_getProperty;
2841 definition.callAsConstructor = &Constructor_callAsConstructor;
2842 definition.finalize = &CYFinalize;
2843 CYPrivate<Constructor>::Class_ = JSClassCreate(&definition);
2845 definition = kJSClassDefinitionEmpty;
2846 definition.className = "Instance";
2847 definition.staticValues = Instance_staticValues;
2848 definition.staticFunctions = Instance_staticFunctions;
2849 definition.hasProperty = &Instance_hasProperty;
2850 definition.getProperty = &Instance_getProperty;
2851 definition.setProperty = &Instance_setProperty;
2852 definition.deleteProperty = &Instance_deleteProperty;
2853 definition.getPropertyNames = &Instance_getPropertyNames;
2854 definition.finalize = &CYFinalize;
2855 Instance::Class_ = JSClassCreate(&definition);
2857 definition.className = "ArrayInstance";
2858 ArrayInstance_ = JSClassCreate(&definition);
2860 definition.className = "BooleanInstance";
2861 BooleanInstance_ = JSClassCreate(&definition);
2863 definition.className = "NumberInstance";
2864 NumberInstance_ = JSClassCreate(&definition);
2866 definition.className = "ObjectInstance";
2867 ObjectInstance_ = JSClassCreate(&definition);
2869 definition.className = "StringInstance";
2870 StringInstance_ = JSClassCreate(&definition);
2872 definition.className = "FunctionInstance";
2873 definition.staticValues = FunctionInstance_staticValues;
2874 definition.callAsFunction = &FunctionInstance_callAsFunction;
2875 FunctionInstance_ = JSClassCreate(&definition);
2877 definition = kJSClassDefinitionEmpty;
2878 definition.className = "Interior";
2879 definition.staticFunctions = Interior_staticFunctions;
2880 definition.hasProperty = &Interior_hasProperty;
2881 definition.getProperty = &Interior_getProperty;
2882 definition.setProperty = &Interior_setProperty;
2883 definition.getPropertyNames = &Interior_getPropertyNames;
2884 definition.finalize = &CYFinalize;
2885 CYPrivate<Interior>::Class_ = JSClassCreate(&definition);
2887 definition = kJSClassDefinitionEmpty;
2888 definition.className = "Message";
2889 definition.staticFunctions = cy::Functor::StaticFunctions;
2890 definition.staticValues = cy::Functor::StaticValues;
2891 definition.callAsFunction = &Message_callAsFunction;
2892 definition.finalize = &CYFinalize;
2893 Message_privateData::Class_ = JSClassCreate(&definition);
2895 definition = kJSClassDefinitionEmpty;
2896 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2897 definition.className = "Prototype";
2898 definition.parentClass = CYPrivate<Messages>::Class_;
2899 definition.finalize = &CYFinalize;
2900 CYPrivate<Prototype>::Class_ = JSClassCreate(&definition);
2902 definition = kJSClassDefinitionEmpty;
2903 definition.className = "Selector";
2904 definition.staticValues = Selector_staticValues;
2905 definition.staticFunctions = Selector_staticFunctions;
2906 definition.callAsFunction = &Selector_callAsFunction;
2907 definition.finalize = &CYFinalize;
2908 CYPrivate<Selector_privateData>::Class_ = JSClassCreate(&definition);
2910 definition = kJSClassDefinitionEmpty;
2911 definition.className = "Super";
2912 definition.finalize = &CYFinalize;
2913 CYPrivate<cy::Super>::Class_ = JSClassCreate(&definition);
2915 definition = kJSClassDefinitionEmpty;
2916 definition.className = "ObjectiveC::Classes";
2917 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2918 definition.getProperty = &ObjectiveC_Classes_getProperty;
2919 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2920 ObjectiveC_Classes_ = JSClassCreate(&definition);
2922 definition = kJSClassDefinitionEmpty;
2923 definition.className = "ObjectiveC::Constants";
2924 definition.getProperty = &ObjectiveC_Constants_getProperty;
2925 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2926 ObjectiveC_Constants_ = JSClassCreate(&definition);
2929 definition = kJSClassDefinitionEmpty;
2930 definition.className = "ObjectiveC::Images";
2931 definition.getProperty = &ObjectiveC_Images_getProperty;
2932 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2933 ObjectiveC_Images_ = JSClassCreate(&definition);
2935 definition = kJSClassDefinitionEmpty;
2936 definition.className = "ObjectiveC::Image::Classes";
2937 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2938 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2939 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2942 definition = kJSClassDefinitionEmpty;
2943 definition.className = "ObjectiveC::Protocols";
2944 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2945 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2946 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2949 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2950 // XXX: this is horrible; there has to be a better way to do this
2952 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2954 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2960 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2961 JSObjectRef global(CYGetGlobalObject(context));
2962 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2963 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2964 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2965 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2967 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2968 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2970 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2971 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2972 CYArrayPush(context, alls, protocols);
2974 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2975 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2976 CYArrayPush(context, alls, classes);
2978 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2979 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2980 CYArrayPush(context, alls, constants);
2983 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2986 JSObjectRef Message(JSObjectMakeConstructor(context, Message_privateData::Class_, NULL));
2987 JSObjectRef Selector(JSObjectMakeConstructor(context, CYPrivate<Selector_privateData>::Class_, &Selector_new));
2988 JSObjectRef Super(JSObjectMakeConstructor(context, CYPrivate<cy::Super>::Class_, &Super_new));
2990 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance::Class_, &Instance_new));
2991 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2992 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2994 JSObjectRef Constructor(JSObjectMakeConstructor(context, CYPrivate<::Constructor>::Class_, NULL));
2995 JSObjectRef Constructor_prototype(CYCastJSObject(context, CYGetProperty(context, Constructor, prototype_s)));
2996 CYSetProperty(context, cy, CYJSString("Constructor_prototype"), Constructor_prototype);
2998 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2999 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
3000 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
3001 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
3002 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
3004 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
3005 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
3006 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
3007 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
3008 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
3010 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
3011 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
3012 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
3013 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
3014 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
3016 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
3017 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
3018 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
3019 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
3020 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
3022 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3023 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3024 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3025 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3026 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3028 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3029 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3030 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3031 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3032 CYSetPrototype(context, StringInstance_prototype, String_prototype);
3034 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3035 CYSetProperty(context, cycript, CYJSString("Message"), Message);
3036 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3037 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3039 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3040 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3043 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3046 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3048 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3049 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3051 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
3052 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
3053 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
3054 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::Object()), kJSPropertyAttributeDontEnum);
3055 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::Meta()), kJSPropertyAttributeDontEnum);
3056 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::Selector()), kJSPropertyAttributeDontEnum);
3058 CYSetProperty(context, cy, CYJSString("cydget"), CYCastJSValue(context, false));
3061 static void *CYObjectiveC_CastSymbol(const char *name) {
3063 #ifdef __GNU_LIBOBJC__
3064 else if (strcmp(name, "object_getClass") == 0)
3065 return reinterpret_cast<void *>(&object_getClass);
3070 static CYHook CYObjectiveCHook = {
3071 &CYObjectiveC_ExecuteStart,
3072 &CYObjectiveC_ExecuteEnd,
3073 &CYObjectiveC_CallFunction,
3074 &CYObjectiveC_Initialize,
3075 &CYObjectiveC_SetupContext,
3076 &CYObjectiveC_CastSymbol,
3079 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3081 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3082 CYSetupContext(context);
3083 JSObjectRef global(CYGetGlobalObject(context));
3084 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
3085 CYSetProperty(context, cy, CYJSString("cydget"), CYCastJSValue(context, true));
3086 } CYObjectiveCatch }
3088 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3091 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3092 utf8 = CYPoolCode(pool, utf8);
3094 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3095 size_t bytes(utf16.size * sizeof(uint16_t));
3096 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3097 memcpy(copy, utf16.data, bytes);
3101 } catch (const CYException &exception) {
3103 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];