1 /* Cycript - The Truly Universal Scripting Language
2 * Copyright (C) 2009-2016 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "cycript.hpp"
32 #include <malloc/malloc.h>
33 #include <mach/mach.h>
36 #include <objc/message.h>
37 #include <objc/runtime.h>
40 #include <CoreFoundation/CoreFoundation.h>
41 #include <JavaScriptCore/JSStringRefCF.h>
44 #include <Foundation/Foundation.h>
49 #include "Functor.hpp"
50 #include "JavaScript.hpp"
52 #include "Execute.hpp"
54 #include "ObjectiveC/Internal.hpp"
55 #include "ObjectiveC/Syntax.hpp"
57 #define CYObjectiveTry_ { \
59 #define CYObjectiveTry { \
60 JSContextRef context(context_); \
62 #define CYObjectiveCatch \
63 catch (const CYException &error) { \
64 @throw CYCastNSObject(NULL, context, error.CastJSValue(context, "Error")); \
70 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
72 #define CYPoolCatch(value) \
73 @catch (NSException *error) { \
74 _saved = [error retain]; \
75 throw CYJSError(context, CYCastJSValue(context, error)); \
80 [_saved autorelease]; \
86 #define CYSadCatch(value) \
87 @catch (NSException *error ) { \
88 throw CYJSError(context, CYCastJSValue(context, error)); \
92 #define _oassert(test) \
94 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"_assert(" #test ")" userInfo:nil];
102 void (*invoke)(void *, ...);
106 struct BlockDescriptor1 {
107 unsigned long int reserved;
108 unsigned long int size;
111 struct BlockDescriptor2 {
112 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
113 void (*dispose_helper)(BlockLiteral *src);
116 struct BlockDescriptor3 {
117 const char *signature;
122 BLOCK_DEALLOCATING = 0x0001,
123 BLOCK_REFCOUNT_MASK = 0xfffe,
124 BLOCK_NEEDS_FREE = 1 << 24,
125 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
126 BLOCK_HAS_CTOR = 1 << 26,
127 BLOCK_IS_GC = 1 << 27,
128 BLOCK_IS_GLOBAL = 1 << 28,
129 BLOCK_HAS_STRET = 1 << 29,
130 BLOCK_HAS_SIGNATURE = 1 << 30,
133 static bool CYIsClass(id self) {
134 return class_isMetaClass(object_getClass(self));
137 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
139 /* Objective-C Pool Release {{{ */
140 void CYPoolRelease_(void *data) {
141 id object(reinterpret_cast<id>(data));
145 id CYPoolRelease_(CYPool *pool, id object) {
148 else if (pool == NULL)
149 return [object autorelease];
151 pool->atexit(CYPoolRelease_);
156 template <typename Type_>
157 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
158 return (Type_) CYPoolRelease_(pool, (id) object);
161 /* Objective-C Strings {{{ */
162 CYUTF8String CYPoolUTF8String(CYPool &pool, JSContextRef context, NSString *value) {
163 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
164 char *string(new(pool) char[size + 1]);
165 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
166 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
167 return CYUTF8String(string, [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
170 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
171 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
172 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
177 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
178 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
182 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
185 // XXX: this definition scares me; is anyone using this?!
186 NSString *string([value description]);
188 return CYCopyJSString(context, string);
191 return CYCopyJSString(CYPoolUTF8String(pool, context, string));
195 NSString *CYCopyNSString(const CYUTF8String &value) {
197 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
199 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
203 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
205 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
208 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
212 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
213 return CYCopyNSString(context, CYJSString(context, value));
216 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
217 return CYPoolRelease(pool, CYCopyNSString(value));
220 NSString *CYCastNSString(CYPool *pool, SEL sel) {
221 const char *name(sel_getName(sel));
222 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
225 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
226 return CYPoolRelease(pool, CYCopyNSString(context, value));
229 CYUTF8String CYCastUTF8String(NSString *value) {
230 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
231 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
235 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
237 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
238 if (exception == NULL)
240 *exception = CYCastJSValue(context, error);
243 size_t CYGetIndex(NSString *value) {
244 return CYGetIndex(CYCastUTF8String(value));
247 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
248 return CYGetOffset(CYPoolCString(pool, context, value), index);
251 static JSClassRef ArrayInstance_;
252 static JSClassRef BooleanInstance_;
253 static JSClassRef FunctionInstance_;
254 static JSClassRef NumberInstance_;
255 static JSClassRef ObjectInstance_;
256 static JSClassRef StringInstance_;
258 static JSClassRef ObjectiveC_Classes_;
259 static JSClassRef ObjectiveC_Constants_;
260 static JSClassRef ObjectiveC_Protocols_;
263 static JSClassRef ObjectiveC_Image_Classes_;
264 static JSClassRef ObjectiveC_Images_;
268 static Class __NSMallocBlock__;
269 static Class NSCFBoolean_;
270 static Class NSCFType_;
271 static Class NSGenericDeallocHandler_;
273 static Class NSBoolNumber_;
276 static Class NSArray_;
277 static Class NSBlock_;
278 static Class NSDictionary_;
279 static Class NSNumber_;
280 static Class NSObject_;
281 static Class NSString_;
282 static Class NSZombie_;
283 static Class Object_;
285 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
287 JSValueRef Prototype::GetPrototype(JSContextRef context) const {
289 if (value_ == NSCFBoolean_)
291 if (value_ == NSBoolNumber_)
293 return CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
294 if (value_ == NSArray_)
295 return CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
296 if (value_ == NSBlock_)
297 return CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
298 if (value_ == NSNumber_)
299 return CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
300 if (value_ == NSDictionary_)
301 return CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
302 if (value_ == NSString_)
303 return CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
305 if (Class super = class_getSuperclass(value_))
306 return CYPrivate<Prototype>::Cache(context, super);
307 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
310 JSValueRef Constructor::GetPrototype(JSContextRef context) const {
311 if (Class super = class_getSuperclass(value_))
312 return CYPrivate<Constructor>::Cache(context, super);
313 return CYGetCachedObject(context, CYJSString("Constructor_prototype"));
316 bool CYIsKindOfClass(id object, Class _class) {
317 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
323 JSValueRef Instance::GetPrototype(JSContextRef context) const {
324 return CYPrivate<Prototype>::Cache(context, object_getClass(value_));
327 JSClassRef Instance::GetClass(id object, Flags flags) {
328 return CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance::Class_;
331 Instance::Instance(id value, Flags flags) :
336 /*else if ([value retainCount] == NSUInteger(-1))
337 flags_ |= Instance::Permanent;*/
339 value_ = [value_ retain];
342 Instance::~Instance() {
347 struct Message_privateData :
350 static JSClassRef Class_;
354 Message_privateData(SEL sel, const char *type, IMP value) :
355 cy::Functor(reinterpret_cast<void (*)()>(value), type),
360 virtual CYPropertyName *GetName(CYPool &pool) const;
362 static JSObjectRef Make(JSContextRef context, SEL sel, const char *type, IMP value);
365 JSClassRef Message_privateData::Class_;
367 JSObjectRef CYMakeInstance(JSContextRef context, id object, Instance::Flags flags = Instance::None) {
368 _assert(object != nil);
371 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
373 if (weak != NULL && &JSWeakObjectMapGet != NULL)
374 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
378 JSObjectRef instance;
379 if (CYIsClass(object) && !class_isMetaClass(object))
380 instance = CYPrivate<Constructor>::Cache(context, object);
382 instance = Instance::Make(context, object, flags);
385 if (weak != NULL && &JSWeakObjectMapSet != NULL)
386 JSWeakObjectMapSet(context, weak, object, instance);
392 @interface NSMethodSignature (Cycript)
393 - (NSString *) _typeString;
396 @interface NSObject (Cycript)
398 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
399 - (JSType) cy$JSType;
401 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
402 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
404 - (bool) cy$hasProperty:(NSString *)name;
405 - (NSObject *) cy$getProperty:(NSString *)name;
406 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
407 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
408 - (bool) cy$deleteProperty:(NSString *)name;
409 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
411 + (bool) cy$hasImplicitProperties;
417 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
420 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
421 _assert(value != nil);
423 Class _class(object_getClass(value));
425 if (class_isMetaClass(_class)) {
426 const char *name(class_getName(value));
427 if (class_isMetaClass(value))
428 return [NSString stringWithFormat:@"object_getClass(%s)", name];
430 return [NSString stringWithUTF8String:name];
433 if (_class == NSZombie_)
434 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
436 SEL sel(@selector(cy$toCYON:inSet:));
438 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
439 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
440 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
441 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
442 return [value cy$toCYON:objective inSet:objects];
444 return [NSString stringWithFormat:@"%@", value];
447 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
449 return CYCastNSCYON(value, objective, *objects);
451 std::set<void *> objects;
452 return CYCastNSCYON(value, objective, objects);
456 struct PropertyAttributes {
461 const char *variable;
474 PropertyAttributes(objc_property_t property) :
486 name = property_getName(property);
487 const char *attributes(property_getAttributes(property));
489 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
490 if ((next = strchr(token, ',')) != NULL)
493 case 'R': readonly = true; break;
494 case 'C': copy = true; break;
495 case '&': retain = true; break;
496 case 'N': nonatomic = true; break;
497 case 'G': getter_ = token + 1; break;
498 case 'S': setter_ = token + 1; break;
499 case 'V': variable = token + 1; break;
503 /*if (variable == NULL) {
504 variable = property_getName(property);
505 size_t size(strlen(variable));
506 char *name(new(pool_) char[size + 2]);
508 memcpy(name + 1, variable, size);
509 name[size + 1] = '\0';
514 const char *Getter() {
516 getter_ = pool_.strdup(name);
520 const char *Setter() {
521 if (setter_ == NULL && !readonly) {
522 size_t length(strlen(name));
524 char *temp(new(pool_) char[length + 5]);
530 temp[3] = toupper(name[0]);
531 memcpy(temp + 4, name + 1, length - 1);
534 temp[length + 3] = ':';
535 temp[length + 4] = '\0';
544 @interface CYWebUndefined : NSObject {
547 + (CYWebUndefined *) undefined;
551 @implementation CYWebUndefined
553 + (CYWebUndefined *) undefined {
554 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
560 #define WebUndefined CYWebUndefined
562 /* Bridge: CYJSObject {{{ */
563 @interface CYJSObject : NSMutableDictionary {
565 JSGlobalContextRef context_;
568 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
570 - (NSUInteger) count;
571 - (id) objectForKey:(id)key;
572 - (NSEnumerator *) keyEnumerator;
573 - (void) setObject:(id)object forKey:(id)key;
574 - (void) removeObjectForKey:(id)key;
578 /* Bridge: CYJSArray {{{ */
579 @interface CYJSArray : NSMutableArray {
581 JSGlobalContextRef context_;
584 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
586 - (NSUInteger) count;
587 - (id) objectAtIndex:(NSUInteger)index;
589 - (void) addObject:(id)anObject;
590 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
591 - (void) removeLastObject;
592 - (void) removeObjectAtIndex:(NSUInteger)index;
593 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
598 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
599 return JSValueIsObjectOfClass(context, value, Instance::Class_) || JSValueIsObjectOfClass(context, value, FunctionInstance_) || JSValueIsObjectOfClass(context, value, CYPrivate<Constructor>::Class_);
602 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
603 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
607 struct CYBlockDescriptor {
609 BlockDescriptor1 one_;
610 BlockDescriptor2 two_;
611 BlockDescriptor3 three_;
614 Closure_privateData *internal_;
617 void CYDisposeBlock(BlockLiteral *literal) {
618 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
621 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
622 JSObjectRef _this(CYCastJSObject(context, values[0]));
623 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
626 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
627 _assert(__NSMallocBlock__ != Nil);
628 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
630 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
631 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
633 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockAdapter_);
634 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->value_);
636 literal->isa = __NSMallocBlock__;
637 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
638 literal->reserved = 0;
639 literal->descriptor = descriptor;
641 descriptor->d_.one_.size = sizeof(descriptor->d_);
642 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
643 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
645 return reinterpret_cast<NSBlock *>(literal);
649 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
650 if (CYJSValueIsNSObject(context, object)) {
651 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
652 return internal->value_;
655 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
656 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
657 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
660 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
661 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
665 @interface NSBoolNumber : NSNumber {
670 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
674 switch (JSType type = JSValueGetType(context, value)) {
675 case kJSTypeUndefined:
676 object = [WebUndefined undefined];
686 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
689 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
695 object = CYCopyNSNumber(context, value);
700 object = CYCopyNSString(context, value);
705 // XXX: this might could be more efficient
706 object = CYCastNSObject(pool, context, (JSObjectRef) value);
711 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
718 return CYPoolRelease(pool, object);
720 return [object retain];
723 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
724 return CYNSObject(pool, context, value, true);
727 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
728 return CYNSObject(&pool, context, value, false);
731 /* Bridge: NSArray {{{ */
732 @implementation NSArray (Cycript)
735 return [[self mutableCopy] autorelease];
738 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
739 _oassert(objects.insert(self).second);
741 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
742 [json appendString:@"@["];
746 for (id object in self) {
748 for (size_t index(0), count([self count]); index != count; ++index) {
749 id object([self objectAtIndex:index]);
752 [json appendString:@","];
755 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
756 [json appendString:CYCastNSCYON(object, true, objects)];
758 [json appendString:@","];
763 [json appendString:@"]"];
767 - (bool) cy$hasProperty:(NSString *)name {
768 if ([name isEqualToString:@"length"])
771 size_t index(CYGetIndex(name));
772 if (index == _not(size_t) || index >= [self count])
773 return [super cy$hasProperty:name];
778 - (NSObject *) cy$getProperty:(NSString *)name {
779 size_t index(CYGetIndex(name));
780 if (index == _not(size_t) || index >= [self count])
781 return [super cy$getProperty:name];
783 return [self objectAtIndex:index];
786 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
788 if ([name isEqualToString:@"length"])
789 return CYCastJSValue(context, [self count]);
792 return [super cy$getProperty:name inContext:context];
795 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
796 [super cy$getPropertyNames:names inContext:context];
798 for (size_t index(0), count([self count]); index != count; ++index) {
799 id object([self objectAtIndex:index]);
800 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
802 sprintf(name, "%zu", index);
803 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
808 + (bool) cy$hasImplicitProperties {
814 /* Bridge: NSBlock {{{ */
816 @interface NSBlock : NSObject
820 static const char *CYBlockEncoding(NSBlock *self);
821 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature);
823 @implementation NSBlock (Cycript)
825 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
829 if (!CYBlockSignature(pool, self, type.signature))
830 return [super cy$toCYON:objective inSet:objects];
831 _oassert(objects.insert(self).second);
833 CYType *typed((new(pool) CYTypeExpression(CYDecodeType(pool, &type)))->typed_);
834 CYTypeModifier *&modifier(CYGetLast(typed->modifier_));
835 CYTypeBlockWith *with(dynamic_cast<CYTypeBlockWith *>(modifier));
836 _assert(with != NULL);
837 CYObjCBlock *block(new(pool) CYObjCBlock(typed, with->parameters_, NULL));
840 std::ostringstream str;
842 CYOutput out(*str.rdbuf(), options);
843 block->Output(out, CYNoFlags);
845 std::string value(str.str());
846 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
852 /* Bridge: NSBoolNumber {{{ */
854 @implementation NSBoolNumber (Cycript)
856 - (JSType) cy$JSType {
857 return kJSTypeBoolean;
860 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
861 NSString *value([self boolValue] ? @"true" : @"false");
862 return objective ? value : [NSString stringWithFormat:@"@%@", value];
865 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
866 return CYCastJSValue(context, (bool) [self boolValue]);
872 /* Bridge: NSDictionary {{{ */
873 @implementation NSDictionary (Cycript)
876 return [[self mutableCopy] autorelease];
879 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
880 _oassert(objects.insert(self).second);
882 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
883 [json appendString:@"@{"];
887 for (NSObject *key in self) {
889 NSEnumerator *keys([self keyEnumerator]);
890 while (NSObject *key = [keys nextObject]) {
893 [json appendString:@","];
896 [json appendString:CYCastNSCYON(key, true, objects)];
897 [json appendString:@":"];
898 NSObject *object([self objectForKey:key]);
899 [json appendString:CYCastNSCYON(object, true, objects)];
902 [json appendString:@"}"];
906 - (bool) cy$hasProperty:(NSString *)name {
907 return [self objectForKey:name] != nil;
910 - (NSObject *) cy$getProperty:(NSString *)name {
911 return [self objectForKey:name];
914 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
915 [super cy$getPropertyNames:names inContext:context];
918 for (NSObject *key in self) {
920 NSEnumerator *keys([self keyEnumerator]);
921 while (NSObject *key = [keys nextObject]) {
923 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
927 + (bool) cy$hasImplicitProperties {
933 /* Bridge: NSMutableArray {{{ */
934 @implementation NSMutableArray (Cycript)
936 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
937 if ([name isEqualToString:@"length"]) {
938 // XXX: is this not intelligent?
939 NSNumber *number(reinterpret_cast<NSNumber *>(value));
940 NSUInteger size([number unsignedIntegerValue]);
941 NSUInteger count([self count]);
943 [self removeObjectsInRange:NSMakeRange(size, count - size)];
944 else if (size != count) {
945 WebUndefined *undefined([WebUndefined undefined]);
946 for (size_t i(count); i != size; ++i)
947 [self addObject:undefined];
952 size_t index(CYGetIndex(name));
953 if (index == _not(size_t))
954 return [super cy$setProperty:name to:value];
956 id object(value ?: [NSNull null]);
958 size_t count([self count]);
960 [self replaceObjectAtIndex:index withObject:object];
962 if (index != count) {
963 WebUndefined *undefined([WebUndefined undefined]);
964 for (size_t i(count); i != index; ++i)
965 [self addObject:undefined];
968 [self addObject:object];
974 - (bool) cy$deleteProperty:(NSString *)name {
975 size_t index(CYGetIndex(name));
976 if (index == _not(size_t) || index >= [self count])
977 return [super cy$deleteProperty:name];
978 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
984 /* Bridge: NSMutableDictionary {{{ */
985 @implementation NSMutableDictionary (Cycript)
987 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
988 [self setObject:(value ?: [NSNull null]) forKey:name];
992 - (bool) cy$deleteProperty:(NSString *)name {
993 if ([self objectForKey:name] == nil)
996 [self removeObjectForKey:name];
1003 /* Bridge: NSNumber {{{ */
1004 @implementation NSNumber (Cycript)
1006 - (JSType) cy$JSType {
1008 // XXX: this just seems stupid
1009 if ([self class] == NSCFBoolean_)
1010 return kJSTypeBoolean;
1012 return kJSTypeNumber;
1015 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1016 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1017 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1020 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1021 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1022 } CYObjectiveCatch }
1026 /* Bridge: NSNull {{{ */
1027 @implementation NSNull (Cycript)
1029 - (JSType) cy$JSType {
1033 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1034 NSString *value(@"null");
1035 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1038 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1039 return CYJSNull(context);
1040 } CYObjectiveCatch }
1044 /* Bridge: NSObject {{{ */
1045 @implementation NSObject (Cycript)
1051 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1052 return [self cy$valueOfInContext:context];
1055 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1057 } CYObjectiveCatch }
1059 - (JSType) cy$JSType {
1060 return kJSTypeObject;
1063 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1064 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1067 - (bool) cy$hasProperty:(NSString *)name {
1071 - (NSObject *) cy$getProperty:(NSString *)name {
1075 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1076 if (NSObject *value = [self cy$getProperty:name])
1077 return CYCastJSValue(context, value);
1079 } CYObjectiveCatch }
1081 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1085 - (bool) cy$deleteProperty:(NSString *)name {
1089 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1092 + (bool) cy$hasImplicitProperties {
1098 /* Bridge: NSOrderedSet {{{ */
1100 @implementation NSOrderedSet (Cycript)
1102 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1103 _oassert(objects.insert(self).second);
1105 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1106 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1107 [json appendString:CYCastNSCYON([self array], true, objects)];
1108 [json appendString:@"]]"];
1115 /* Bridge: NSProxy {{{ */
1116 @implementation NSProxy (Cycript)
1118 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1119 return [[self description] cy$toCYON:objective inSet:objects];
1124 /* Bridge: NSSet {{{ */
1125 @implementation NSSet (Cycript)
1127 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1128 _oassert(objects.insert(self).second);
1130 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1131 [json appendString:@"[NSSet setWithArray:"];
1132 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1133 [json appendString:@"]]"];
1139 /* Bridge: NSString {{{ */
1140 @implementation NSString (Cycript)
1143 return [[self copy] autorelease];
1146 - (JSType) cy$JSType {
1147 return kJSTypeString;
1150 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1151 std::ostringstream str;
1154 CYUTF8String string(CYCastUTF8String(self));
1155 CYStringify(str, string.data, string.size, CYStringifyModeNative);
1156 std::string value(str.str());
1157 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1160 - (bool) cy$hasProperty:(NSString *)name {
1161 size_t index(CYGetIndex(name));
1162 if (index == _not(size_t) || index >= [self length])
1163 return [super cy$hasProperty:name];
1168 - (NSObject *) cy$getProperty:(NSString *)name {
1169 size_t index(CYGetIndex(name));
1170 if (index == _not(size_t) || index >= [self length])
1171 return [super cy$getProperty:name];
1173 return [self substringWithRange:NSMakeRange(index, 1)];
1176 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1177 [super cy$getPropertyNames:names inContext:context];
1179 for (size_t index(0), length([self length]); index != length; ++index) {
1181 sprintf(name, "%zu", index);
1182 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1186 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1187 return CYCastJSValue(context, CYJSString(context, self));
1188 } CYObjectiveCatch }
1192 /* Bridge: WebUndefined {{{ */
1193 @implementation WebUndefined (Cycript)
1195 - (JSType) cy$JSType {
1196 return kJSTypeUndefined;
1199 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1200 NSString *value(@"undefined");
1201 return value; // XXX: maybe use the below code, adding @undefined?
1202 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1205 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1206 return CYJSUndefined(context);
1207 } CYObjectiveCatch }
1212 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1213 id self(CYCastNSObject(&pool, context, value));
1214 if (CYIsClass(self))
1215 return (Class) self;
1216 throw CYJSError(context, "got something that is not a Class");
1220 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1222 size_t size(JSPropertyNameArrayGetCount(names));
1223 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1224 for (size_t index(0); index != size; ++index)
1225 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1229 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) {
1231 return CYJSNull(context);
1232 return CYMakeInstance(context, value);
1235 @implementation CYJSObject
1237 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1238 if ((self = [super init]) != nil) {
1240 context_ = CYGetJSContext(context);
1241 JSGlobalContextRetain(context_);
1242 JSValueProtect(context_, object_);
1244 } CYObjectiveCatch }
1246 - (void) dealloc { CYObjectiveTry {
1247 JSValueUnprotect(context_, object_);
1248 JSGlobalContextRelease(context_);
1250 } CYObjectiveCatch }
1252 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1254 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1256 return [super cy$toCYON:objective inSet:objects];
1258 return [NSString stringWithUTF8String:cyon];
1259 } CYObjectiveCatch }
1261 - (NSUInteger) count { CYObjectiveTry {
1262 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1263 size_t size(JSPropertyNameArrayGetCount(names));
1264 JSPropertyNameArrayRelease(names);
1266 } CYObjectiveCatch }
1268 - (id) objectForKey:(id)key { CYObjectiveTry {
1269 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1270 if (JSValueIsUndefined(context, value))
1272 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1273 } CYObjectiveCatch }
1275 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1276 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1277 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1278 JSPropertyNameArrayRelease(names);
1280 } CYObjectiveCatch }
1282 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1283 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1284 } CYObjectiveCatch }
1286 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1287 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1288 } CYObjectiveCatch }
1292 @implementation CYJSArray
1294 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1296 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1297 } CYObjectiveCatch }
1299 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1300 if ((self = [super init]) != nil) {
1302 context_ = CYGetJSContext(context);
1303 JSGlobalContextRetain(context_);
1304 JSValueProtect(context_, object_);
1306 } CYObjectiveCatch }
1308 - (void) dealloc { CYObjectiveTry {
1309 JSValueUnprotect(context_, object_);
1310 JSGlobalContextRelease(context_);
1312 } CYObjectiveCatch }
1314 - (NSUInteger) count { CYObjectiveTry {
1315 return CYArrayLength(context, object_);
1316 } CYObjectiveCatch }
1318 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1319 size_t bounds([self count]);
1320 if (index >= bounds)
1321 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1322 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1323 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1324 } CYObjectiveCatch }
1326 - (void) addObject:(id)object { CYObjectiveTry {
1327 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1328 } CYObjectiveCatch }
1330 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1331 size_t bounds([self count] + 1);
1332 if (index >= bounds)
1333 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1334 JSValueRef arguments[3];
1335 arguments[0] = CYCastJSValue(context, index);
1336 arguments[1] = CYCastJSValue(context, 0);
1337 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1338 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1339 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1340 } CYObjectiveCatch }
1342 - (void) removeLastObject { CYObjectiveTry {
1343 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1344 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1345 } CYObjectiveCatch }
1347 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1348 size_t bounds([self count]);
1349 if (index >= bounds)
1350 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1351 JSValueRef arguments[2];
1352 arguments[0] = CYCastJSValue(context, index);
1353 arguments[1] = CYCastJSValue(context, 1);
1354 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1355 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1356 } CYObjectiveCatch }
1358 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1359 size_t bounds([self count]);
1360 if (index >= bounds)
1361 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1362 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1363 } CYObjectiveCatch }
1367 // XXX: inherit from or replace with CYJSObject
1368 @interface CYInternal : NSObject {
1369 JSGlobalContextRef context_;
1370 JSObjectRef object_;
1375 @implementation CYInternal
1377 - (void) dealloc { CYObjectiveTry {
1378 JSValueUnprotect(context_, object_);
1379 JSGlobalContextRelease(context_);
1381 } CYObjectiveCatch }
1383 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1384 if ((self = [super init]) != nil) {
1385 context_ = CYGetJSContext(context);
1386 JSGlobalContextRetain(context_);
1388 } CYObjectiveCatch }
1390 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1391 if (object_ == NULL)
1394 return JSObjectHasProperty(context, object_, name);
1397 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1398 if (object_ == NULL)
1401 return CYGetProperty(context, object_, name);
1404 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1405 @synchronized (self) {
1406 if (object_ == NULL) {
1407 object_ = JSObjectMake(context, NULL, NULL);
1408 JSValueProtect(context, object_);
1412 CYSetProperty(context, object_, name, value);
1415 + (CYInternal *) get:(id)object {
1417 if (&objc_getAssociatedObject == NULL)
1420 @synchronized (object) {
1421 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1429 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1431 if (&objc_getAssociatedObject == NULL)
1434 @synchronized (object) {
1435 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1438 if (&objc_setAssociatedObject == NULL)
1441 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1442 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1452 static JSValueRef CYCastJSValue(JSContextRef context, SEL sel) {
1454 return CYJSNull(context);
1455 return CYPrivate<Selector_privateData>::Make(context, sel);
1458 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1459 if (JSValueIsObjectOfClass(context, value, CYPrivate<Selector_privateData>::Class_)) {
1460 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1461 return reinterpret_cast<SEL>(internal->value_);
1464 return sel_registerName(CYPoolCString(pool, context, value));
1468 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1469 return (void *) [[NSAutoreleasePool alloc] init];
1470 } CYSadCatch(NULL) }
1472 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1473 return [(NSAutoreleasePool *) handle release];
1476 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1477 CYCallFunction(pool, context, cif, function, value, values);
1480 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, const sig::Signature *signature) {
1482 if (JSValueIsNull(context, value))
1484 JSObjectRef object(CYCastJSObject(context, value));
1486 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1487 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_;
1489 if (JSValueIsObjectOfClass(context, object, Instance::Class_)) {
1490 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_ == nil);
1494 _assert(JSObjectIsFunction(context, object));
1496 _assert(signature != NULL);
1497 _assert(signature->count != 0);
1499 sig::Signature modified;
1500 modified.count = signature->count + 1;
1501 modified.elements = new(pool) sig::Element[modified.count];
1503 modified.elements[0] = signature->elements[0];
1504 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1506 modified.elements[1].name = NULL;
1507 modified.elements[1].type = new(pool) sig::Object();
1508 modified.elements[1].offset = _not(size_t);
1510 return CYMakeBlock(context, object, modified);
1518 void Block::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1519 // XXX: this function actually needs to handle null pools as it is an autorelease
1520 _assert(pool != NULL);
1521 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &signature);
1524 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1525 void Object::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1526 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1529 void Meta::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1530 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1533 void Selector::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1534 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1537 JSValueRef Object::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1538 NSObject *value(*reinterpret_cast<NSObject **>(data));
1540 return CYJSNull(context);
1541 JSObjectRef object(CYMakeInstance(context, value));
1544 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1546 if (internal->IsUninitialized()) {
1547 internal->flags_ &= ~Instance::Uninitialized;
1548 if (internal->value_ == nil)
1549 internal->value_ = value;
1551 _assert(internal->value_ == value);
1560 JSValueRef Meta::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1561 if (Class value = *reinterpret_cast<Class *>(data))
1562 return CYMakeInstance(context, value, Instance::Permanent);
1563 return CYJSNull(context);
1566 JSValueRef Selector::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1567 return CYCastJSValue(context, *reinterpret_cast<SEL *>(data));
1570 JSValueRef Block::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1571 return CYCastJSValue(context, *reinterpret_cast<NSObject **>(data));
1576 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1577 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1581 method_getReturnType(method, type, sizeof(type));
1586 // XXX: possibly use a more "awesome" check?
1590 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1591 JSObjectRef _this(CYCastJSObject(context, values[0]));
1592 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1595 JSObjectRef Message_privateData::Make(JSContextRef context, SEL sel, const char *type, IMP value) {
1596 Message_privateData *internal(new Message_privateData(sel, type, value));
1597 JSObjectRef object(JSObjectMake(context, Message_privateData::Class_, internal));
1598 CYSetPrototype(context, object, CYGetCachedValue(context, CYJSString("Functor_prototype")));
1602 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1603 JSObjectRef function(CYCastJSObject(context, value));
1605 sig::Signature signature;
1606 sig::Parse(pool, &signature, encoding, &Structor_);
1607 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1608 // XXX: see notes in Library.cpp about needing to leak
1609 return reinterpret_cast<IMP>(internal->value_);
1612 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1613 auto internal(CYPrivate<Messages>::Get(context, object));
1614 Class _class(internal->GetClass());
1617 const char *name(CYPoolCString(pool, context, property));
1619 if (SEL sel = sel_getUid(name))
1620 if (class_getInstanceMethod(_class, sel) != NULL)
1626 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1627 auto internal(CYPrivate<Messages>::Get(context, object));
1628 Class _class(internal->GetClass());
1631 const char *name(CYPoolCString(pool, context, property));
1633 if (SEL sel = sel_getUid(name))
1634 if (objc_method *method = class_getInstanceMethod(_class, sel))
1635 return Message_privateData::Make(context, sel, method_getTypeEncoding(method), method_getImplementation(method));
1640 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1641 auto internal(CYPrivate<Messages>::Get(context, object));
1642 Class _class(internal->GetClass());
1645 const char *name(CYPoolCString(pool, context, property));
1646 SEL sel(sel_registerName(name));
1651 if (JSValueIsObjectOfClass(context, value, Message_privateData::Class_)) {
1652 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1653 type = sig::Unparse(pool, &message->signature_);
1654 imp = reinterpret_cast<IMP>(message->value_);
1655 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1656 type = method_getTypeEncoding(method);
1657 imp = CYMakeMessage(context, value, type);
1658 } else return false;
1660 objc_method *method(NULL);
1662 objc_method **methods(class_copyMethodList(_class, &size));
1663 pool.atexit(free, methods);
1665 for (size_t i(0); i != size; ++i)
1666 if (sel_isEqual(method_getName(methods[i]), sel)) {
1667 method = methods[i];
1672 method_setImplementation(method, imp);
1674 class_addMethod(_class, sel, imp, type);
1679 static JSValueRef Messages_complete_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1681 if (!CYCastBool(context, arguments[1]))
1682 return CYObjectMakeArray(context, 0, NULL);
1686 _assert(count == 1);
1688 CYUTF8String prefix(CYPoolUTF8String(pool, context, CYJSString(context, arguments[0])));
1690 auto internal(CYPrivate<Messages>::Get(context, _this));
1691 Class _class(internal->GetClass());
1694 objc_method **data(class_copyMethodList(_class, &size));
1695 pool.atexit(free, data);
1697 JSObjectRef array(NULL); {
1698 CYArrayBuilder<1024> values(context, array);
1700 for (size_t i(0); i != size; ++i) {
1701 CYUTF8String name(sel_getName(method_getName(data[i])));
1702 if (CYStartsWith(name, prefix))
1703 values(CYCastJSValue(context, CYJSString(name)));
1708 static bool CYHasImplicitProperties(JSContextRef context, Class _class) {
1709 if (!CYCastBool(context, CYGetCachedValue(context, CYJSString("cydget"))))
1710 if (class_getProperty(NSObject_, "description") != NULL)
1712 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1713 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1715 return [_class cy$hasImplicitProperties];
1718 static objc_property_t CYFindProperty(CYPool &pool, Class _class, const char *name) {
1721 if (objc_property_t property = class_getProperty(_class, name))
1725 /* // XXX: I don't think any of this is required
1727 Protocol **protocols(class_copyProtocolList(_class, &count));
1728 // XXX: just implement a scope guard already :/
1729 pool.atexit(free, protocols);
1731 for (unsigned int i(0); i != count; ++i)
1732 if (objc_property_t property = protocol_getProperty(protocols[i], name, true, true))
1735 return CYFindProperty(pool, class_getSuperclass(_class), name); */
1738 static JSValueRef Constructor_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1739 auto internal(CYPrivate<Constructor>::Get(context, object));
1740 return CYPrivate<Interior>::Make(context, internal->value_, context, object);
1743 static bool Constructor_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1744 auto internal(CYPrivate<Constructor>::Get(context, object));
1745 Class _class(object_getClass(internal->value_));
1746 if (!CYHasImplicitProperties(context, _class))
1749 if (SEL sel = sel_getUid(CYPoolCString(pool, context, property)))
1750 if (CYImplements(internal->value_, _class, sel, true))
1755 static JSValueRef Constructor_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1756 auto internal(CYPrivate<Constructor>::Get(context, object));
1757 Class _class(object_getClass(internal->value_));
1758 if (!CYHasImplicitProperties(context, _class))
1761 if (SEL sel = sel_getUid(CYPoolCString(pool, context, property)))
1762 if (CYImplements(internal->value_, _class, sel, true))
1763 return CYSendMessage(pool, context, internal->value_, NULL, sel, 0, NULL, false);
1767 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1768 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1769 id self(internal->value_);
1771 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1775 NSString *name(CYCastNSString(&pool, context, property));
1777 if (CYInternal *internal = [CYInternal get:self])
1778 if ([internal hasProperty:property inContext:context])
1781 Class _class(object_getClass(self));
1784 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1785 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1786 if ([self cy$hasProperty:name])
1788 } CYPoolCatch(false)
1790 const char *string(CYPoolCString(pool, context, name));
1792 if (CYFindProperty(pool, _class, string) != NULL)
1795 if (CYHasImplicitProperties(context, _class))
1796 if (SEL sel = sel_getUid(string))
1797 if (CYImplements(self, _class, sel, true))
1803 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1804 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1805 id self(internal->value_);
1807 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1808 return CYPrivate<Interior>::Make(context, self, context, object);
1811 NSString *name(CYCastNSString(&pool, context, property));
1813 if (CYInternal *internal = [CYInternal get:self])
1814 if (JSValueRef value = [internal getProperty:property inContext:context])
1818 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1822 const char *string(CYPoolCString(pool, context, name));
1823 Class _class(object_getClass(self));
1825 if (objc_property_t property = CYFindProperty(pool, _class, string)) {
1826 PropertyAttributes attributes(property);
1827 SEL sel(sel_registerName(attributes.Getter()));
1828 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1831 if (CYHasImplicitProperties(context, _class))
1832 if (SEL sel = sel_getUid(string))
1833 if (CYImplements(self, _class, sel, true))
1834 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1839 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1840 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1841 id self(internal->value_);
1845 NSString *name(CYCastNSString(&pool, context, property));
1846 NSObject *data(CYCastNSObject(&pool, context, value));
1849 if ([self cy$setProperty:name to:data])
1851 } CYPoolCatch(false)
1853 const char *string(CYPoolCString(pool, context, name));
1854 Class _class(object_getClass(self));
1856 if (objc_property_t property = CYFindProperty(pool, _class, string)) {
1857 PropertyAttributes attributes(property);
1858 if (const char *setter = attributes.Setter()) {
1859 SEL sel(sel_registerName(setter));
1860 JSValueRef arguments[1] = {value};
1861 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1866 size_t length(strlen(string));
1868 char set[length + 5];
1874 if (string[0] != '\0') {
1875 set[3] = toupper(string[0]);
1876 memcpy(set + 4, string + 1, length - 1);
1879 set[length + 3] = ':';
1880 set[length + 4] = '\0';
1882 if (SEL sel = sel_getUid(set))
1883 if (CYImplements(self, _class, sel)) {
1884 JSValueRef arguments[1] = {value};
1885 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1889 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1890 [internal setProperty:property toValue:value inContext:context];
1897 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1898 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1899 id self(internal->value_);
1902 NSString *name(CYCastNSString(NULL, context, property));
1903 return [self cy$deleteProperty:name];
1904 } CYPoolCatch(false)
1905 } CYCatch(false) return /*XXX*/ false; }
1907 static void CYForEachProperty(CYPool &pool, Class _class, const Functor<void (objc_method *, const char *)> &code) {
1908 for (; _class != Nil; _class = class_getSuperclass(_class)) {
1910 objc_method **data(class_copyMethodList(_class, &size));
1911 pool.atexit(free, data);
1913 for (size_t i(0); i != size; ++i) {
1914 objc_method *method(data[i]);
1916 const char *name(sel_getName(method_getName(method)));
1917 if (strchr(name, ':') != NULL)
1925 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1926 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1927 id self(internal->value_);
1930 Class _class(object_getClass(self));
1932 for (Class current(_class); current != Nil; current = class_getSuperclass(current)) {
1934 objc_property_t *data(class_copyPropertyList(current, &size));
1935 pool.atexit(free, data);
1937 for (size_t i(0); i != size; ++i)
1938 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1941 if (CYHasImplicitProperties(context, _class))
1942 CYForEachProperty(pool, _class, fun([&](objc_method *method, const char *name) {
1943 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1947 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1948 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1949 [self cy$getPropertyNames:names inContext:context];
1953 static JSValueRef Instance_complete_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1954 if (!CYJSValueIsNSObject(context, _this))
1955 return CYObjectMakeArray(context, 0, NULL);
1957 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
1958 id self(internal->value_);
1960 _assert(count == 1 || count == 2);
1962 Class _class(object_getClass(self));
1964 CYUTF8String prefix(CYPoolUTF8String(pool, context, CYJSString(context, arguments[0])));
1966 JSObjectRef array(NULL); {
1967 CYArrayBuilder<1024> values(context, array);
1969 CYForEachProperty(pool, _class, fun([&](objc_method *method, const char *name) {
1970 if (!CYStartsWith(name, prefix))
1972 const char *type(method_getTypeEncoding(method));
1973 if (type == NULL || *type == '\0' || *type == 'v')
1975 if (class_getProperty(_class, name) != NULL)
1977 values(CYCastJSValue(context, CYJSString(pool.strcat(name, "()", NULL))));
1982 static JSObjectRef Constructor_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1983 auto internal(CYPrivate<Constructor>::Get(context, object));
1984 JSObjectRef value(CYMakeInstance(context, [internal->value_ alloc], Instance::Uninitialized));
1988 static const char *CYBlockEncoding(NSBlock *self) {
1989 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1990 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1992 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1993 descriptor += sizeof(BlockDescriptor1);
1994 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1995 descriptor += sizeof(BlockDescriptor2);
1996 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1997 return descriptor3->signature;
2000 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature) {
2001 const char *encoding(CYBlockEncoding(self));
2002 if (encoding == NULL)
2005 sig::Parse(pool, &signature, encoding, &Structor_);
2006 _assert(signature.count >= 2);
2008 _assert(dynamic_cast<sig::Object *>(signature.elements[1].type) != NULL);
2009 signature.elements[1] = signature.elements[0];
2011 ++signature.elements;
2017 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2018 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2019 id self(internal->value_);
2021 if (const char *encoding = CYBlockEncoding(self)) {
2027 sig::Signature signature;
2028 sig::Parse(pool, &signature, encoding, &Structor_);
2031 sig::sig_ffi_cif(pool, 0, signature, &cif);
2033 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
2034 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
2035 return CYCallFunction(pool, context, 1, setup, count, arguments, false, false, signature, &cif, function);
2039 CYThrow("NSBlock without signature field passed arguments");
2043 } CYPoolCatch(NULL);
2048 static bool Constructor_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
2049 auto internal(CYPrivate<Constructor>::Get(context, constructor));
2050 Class _class(internal->value_);
2052 if (CYJSValueIsNSObject(context, instance)) {
2053 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2054 // XXX: this isn't always safe
2055 return [linternal->value_ isKindOfClass:_class];
2061 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2063 throw CYJSError(context, "incorrect number of arguments to Instance");
2065 id value(CYCastNSObject(&pool, context, arguments[0]));
2067 value = [NSNull null];
2068 return CYCastJSValue(context, [value cy$box]);
2071 static bool Interior_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2072 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2075 id self(internal->value_);
2076 const char *name(CYPoolCString(pool, context, property));
2078 if (object_getInstanceVariable(self, name, NULL) != NULL)
2084 static void CYBitField(CYPool &pool, unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2085 length = CYCastDouble(encoding + 1);
2089 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2090 pool.atexit(free, ivars);
2092 for (size_t i(0); i != size; ++i)
2093 if (ivars[i] == ivar)
2095 else if (ivar_getOffset(ivars[i]) == offset) {
2096 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2097 _assert(encoding != NULL);
2098 _assert(encoding[0] == 'b');
2099 shift += CYCastDouble(encoding + 1);
2103 static JSValueRef Interior_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2104 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2107 id self(internal->value_);
2108 const char *name(CYPoolCString(pool, context, property));
2110 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2111 ptrdiff_t offset(ivar_getOffset(ivar));
2112 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2114 const char *encoding(ivar_getTypeEncoding(ivar));
2115 _assert(encoding != NULL);
2116 _assert(encoding[0] != '\0');
2117 if (encoding[0] == 'b') {
2118 unsigned length, shift;
2119 CYBitField(pool, length, shift, self, ivar, encoding, offset);
2120 _assert(shift + length <= sizeof(uintptr_t) * 8);
2121 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2122 uintptr_t mask((1 << length) - 1);
2123 return CYCastJSValue(context, (field >> shift) & mask);
2125 #if defined(__APPLE__) && defined(__LP64__)
2126 // XXX: maybe do even more verifications here
2127 if (strcmp(name, "isa") == 0)
2128 return CYCastJSValue(context, object_getClass(self));
2131 auto type(new(pool) Type_privateData(encoding));
2132 return type->type_->FromFFI(context, type->GetFFI(), data);
2139 static bool Interior_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2140 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2143 id self(internal->value_);
2144 const char *name(CYPoolCString(pool, context, property));
2146 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2147 ptrdiff_t offset(ivar_getOffset(ivar));
2148 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2150 const char *encoding(ivar_getTypeEncoding(ivar));
2151 _assert(encoding != NULL);
2152 if (encoding[0] == 'b') {
2153 unsigned length, shift;
2154 CYBitField(pool, length, shift, self, ivar, encoding, offset);
2155 _assert(shift + length <= sizeof(uintptr_t) * 8);
2156 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2157 uintptr_t mask((1 << length) - 1);
2158 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2160 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2161 type->type_->PoolFFI(&pool, context, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2169 static void Interior_getPropertyNames_(CYPool &pool, Class _class, JSPropertyNameAccumulatorRef names) {
2170 if (Class super = class_getSuperclass(_class))
2171 Interior_getPropertyNames_(pool, super, names);
2174 objc_ivar **data(class_copyIvarList(_class, &size));
2175 pool.atexit(free, data);
2177 for (size_t i(0); i != size; ++i)
2178 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2181 static void Interior_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2182 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2185 id self(internal->value_);
2186 Class _class(object_getClass(self));
2188 Interior_getPropertyNames_(pool, _class, names);
2191 static JSValueRef Interior_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2192 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2193 return internal->owner_;
2196 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2198 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2201 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2203 NSString *name(CYCastNSString(&pool, context, property));
2204 if (Class _class = NSClassFromString(name))
2205 return CYMakeInstance(context, _class, Instance::Permanent);
2209 static Class *CYCopyClassList(size_t &size) {
2210 size = objc_getClassList(NULL, 0);
2211 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2214 size_t writ(objc_getClassList(data, size));
2220 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2231 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2235 if (Class *data = CYCopyClassList(size)) {
2236 pool.atexit(free, data);
2237 for (size_t i(0); i != size; ++i)
2238 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2243 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2244 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2247 const char *name(CYPoolCString(pool, context, property));
2250 const char **data(objc_copyClassNamesForImage(internal, &size));
2251 pool.atexit(free, data);
2254 for (size_t i(0); i != size; ++i)
2255 if (strcmp(name, data[i]) == 0) {
2256 if (Class _class = objc_getClass(name))
2257 return CYMakeInstance(context, _class, Instance::Permanent);
2265 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2266 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2270 const char **data(objc_copyClassNamesForImage(internal, &size));
2271 pool.atexit(free, data);
2273 for (size_t i(0); i != size; ++i)
2274 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2277 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2279 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2282 const char **data(objc_copyImageNames(&size));
2283 pool.atexit(free, data);
2285 for (size_t i(0); i != size; ++i)
2286 if (name == data[i]) {
2287 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2288 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2295 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2299 const char **data(objc_copyImageNames(&size));
2300 pool.atexit(free, data);
2302 for (size_t i(0); i != size; ++i)
2303 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2307 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2309 const char *name(CYPoolCString(pool, context, property));
2310 if (Protocol *protocol = objc_getProtocol(name))
2311 return CYMakeInstance(context, protocol, Instance::Permanent);
2315 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2319 Protocol **data(objc_copyProtocolList(&size));
2320 pool.atexit(free, data);
2322 for (size_t i(0); i != size; ++i)
2323 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2326 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2328 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2330 return CYJSNull(context);
2334 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2335 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2339 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2340 *data = reinterpret_cast<void *>(address);
2341 return KERN_SUCCESS;
2345 std::set<Class> query_;
2346 JSContextRef context_;
2347 JSObjectRef results_;
2350 struct CYObjectStruct {
2354 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2355 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2356 JSContextRef context(choice->context_);
2358 for (unsigned i(0); i != count; ++i) {
2359 vm_range_t &range(ranges[i]);
2360 void *data(reinterpret_cast<void *>(range.address));
2361 size_t size(range.size);
2363 if (size < sizeof(CYObjectStruct))
2366 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2367 #if defined(__APPLE__) && defined(__LP64__)
2368 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2370 Class isa(reinterpret_cast<Class>(pointers[0]));
2373 std::set<Class>::const_iterator result(choice->query_.find(isa));
2374 if (result == choice->query_.end())
2377 size_t needed(class_getInstanceSize(*result));
2378 // XXX: if (size < needed)
2380 size_t boundary(496);
2384 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2386 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2390 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2392 throw CYJSError(context, "choose() takes a class argument");
2394 CYGarbageCollect(context);
2397 id _class(CYCastNSObject(&pool, context, arguments[0]));
2399 vm_address_t *zones(NULL);
2401 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2402 _assert(error == KERN_SUCCESS);
2404 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2405 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2408 choice.context_ = context;
2409 choice.results_ = results;
2412 Class *classes(CYCopyClassList(number));
2413 _assert(classes != NULL);
2414 pool.atexit(free, classes);
2416 for (size_t i(0); i != number; ++i)
2417 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2418 if (current == _class) {
2419 choice.query_.insert(classes[i]);
2423 for (unsigned i(0); i != size; ++i) {
2424 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2425 if (zone == NULL || zone->introspect == NULL)
2428 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2436 #if defined(__i386__) || defined(__x86_64__)
2437 #define OBJC_MAX_STRUCT_BY_VALUE 8
2438 static int struct_forward_array[] = {
2439 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2440 #elif defined(__arm__)
2441 #define OBJC_MAX_STRUCT_BY_VALUE 1
2442 static int struct_forward_array[] = {
2444 #elif defined(__arm64__)
2447 #error missing objc-runtime-info
2451 static bool stret(ffi_type *ffi_type) {
2452 return ffi_type->type == FFI_TYPE_STRUCT && (
2453 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2454 struct_forward_array[ffi_type->size] != 0
2462 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2466 _class = object_getClass(self);
2470 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2471 imp = method_getImplementation(method);
2472 type = method_getTypeEncoding(method);
2477 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2478 type = CYPoolCString(pool, context, [method _typeString]);
2484 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2491 sig::Signature signature;
2492 sig::Parse(pool, &signature, type, &Structor_);
2495 sig::sig_ffi_cif(pool, 0, signature, &cif);
2499 if (stret(cif.rtype))
2500 imp = class_getMethodImplementation_stret(_class, _cmd);
2503 imp = class_getMethodImplementation(_class, _cmd);
2506 void (*function)() = reinterpret_cast<void (*)()>(imp);
2507 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, true, signature, &cif, function);
2510 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2512 throw CYJSError(context, "too few arguments to objc_msgSend");
2522 if (JSValueIsObjectOfClass(context, arguments[0], CYPrivate<cy::Super>::Class_)) {
2523 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2524 self = internal->value_;
2525 _class = internal->class_;;
2526 uninitialized = false;
2527 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2528 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2529 self = internal->value_;
2531 uninitialized = internal->IsUninitialized();
2532 if (uninitialized && [internal->value_ retainCount] != NSUInteger(-1))
2533 internal->value_ = nil;
2535 self = CYCastNSObject(&pool, context, arguments[0]);
2537 uninitialized = false;
2541 return CYJSNull(context);
2543 _cmd = CYCastSEL(context, arguments[1]);
2545 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2548 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2549 return $objc_msgSend(context, object, _this, count, arguments);
2552 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2553 JSValueRef setup[count + 2];
2556 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2557 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2560 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2562 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2564 // XXX: handle Instance::Uninitialized?
2565 id self(CYCastNSObject(&pool, context, _this));
2569 setup[1] = &internal->sel_;
2571 return CYCallFunction(pool, context, 2, setup, count, arguments, false, true, internal->signature_, &internal->cif_, internal->value_);
2574 CYPropertyName *Message_privateData::GetName(CYPool &pool) const {
2575 return new(pool) CYString(pool.strcat(":", sel_getName(sel_), NULL));
2578 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2580 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2582 id self(CYCastNSObject(&pool, context, arguments[0]));
2583 Class _class(CYCastClass(pool, context, arguments[1]));
2584 return CYPrivate<cy::Super>::Make(context, self, _class);
2587 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2589 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2591 const char *name(CYPoolCString(pool, context, arguments[0]));
2592 return CYPrivate<Selector_privateData>::Make(context, sel_registerName(name));
2595 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2597 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2598 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2601 static JSValueRef Selector_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2602 return CYMakeType(context, sig::Selector());
2605 static JSValueRef Instance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2606 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2607 id self(internal->value_);
2608 return CYMakeType(context, sig::Object(class_getName(object_getClass(self))));
2611 static JSValueRef FunctionInstance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2612 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2615 if (!CYBlockSignature(pool, internal->value_, type.signature))
2616 return CYJSNull(context);
2617 return CYMakeType(context, type);
2620 static JSValueRef Constructor_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2621 return CYMakeType(context, sig::Meta());
2624 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2625 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2626 return CYMakeInstance(context, object_getClass(internal->value_), Instance::Permanent);
2629 static JSValueRef Constructor_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2630 auto internal(CYPrivate<Constructor>::Get(context, object));
2631 return CYMakeInstance(context, object_getClass(internal->value_), Instance::Permanent);
2634 static JSValueRef Constructor_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2635 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2636 id self(internal->value_);
2637 return CYPrivate<Prototype>::Cache(context, self);
2640 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2641 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2643 if (!CYJSValueIsNSObject(context, _this))
2646 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2647 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->value_, false, objects)));
2650 static JSValueRef Constructor_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2651 auto internal(CYPrivate<Constructor>::Get(context, _this));
2652 return CYCastJSValue(context, CYJSString(class_getName(internal->value_)));
2655 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2656 if (!CYJSValueIsNSObject(context, _this))
2659 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2660 id value(internal->value_);
2667 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2669 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2670 return CYJSUndefined(context);
2671 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2674 return CYCastJSValue(context, CYJSString(context, [value description]));
2676 } CYCatch(NULL) return /*XXX*/ NULL; }
2678 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2679 if (!CYJSValueIsNSObject(context, _this))
2682 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2683 id value(internal->value_);
2684 _assert(value != nil);
2686 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2689 if (JSValueRef result = [value cy$valueOfInContext:context])
2693 } CYCatch(NULL) return /*XXX*/ NULL; }
2695 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2696 if (!CYJSValueIsNSObject(context, _this))
2698 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2699 // XXX: return CYMakePointer(context, internal->value_, sig::Object(class_getName(object_getClass(internal->value_))), NULL, object);
2700 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2701 } CYCatch(NULL) return /*XXX*/ NULL; }
2703 static JSValueRef Constructor_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2704 auto internal(CYPrivate<Constructor>::Get(context, object));
2705 // XXX: return CYMakePointer(context, internal->value_, sig::Meta(), NULL, object);
2706 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2707 } CYCatch(NULL) return /*XXX*/ NULL; }
2709 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2710 if (!CYJSValueIsNSObject(context, _this))
2713 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2714 id value(internal->value_);
2717 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2718 return CYCastJSValue(context, CYJSString(context, [value description]));
2720 } CYCatch(NULL) return /*XXX*/ NULL; }
2722 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2723 if (!CYJSValueIsNSObject(context, _this))
2726 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2727 id value(internal->value_);
2729 if (!CYIsClass(value))
2730 CYThrow("non-Class object cannot be used as Type");
2732 sig::Object type(class_getName(value));
2733 return CYMakeType(context, type);
2734 } CYCatch(NULL) return /*XXX*/ NULL; }
2736 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2737 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2738 return CYCastJSValue(context, sel_getName(internal->value_));
2741 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2742 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2745 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2746 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2747 const char *name(sel_getName(internal->value_));
2750 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2751 return CYCastJSValue(context, CYJSString(context, string));
2753 } CYCatch(NULL) return /*XXX*/ NULL; }
2755 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2757 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2760 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2761 SEL sel(internal->value_);
2763 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2764 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2765 const char *encoding(method_getTypeEncoding(method));
2767 sig::Function type(false);
2768 sig::Parse(pool, &type.signature, encoding, &Structor_);
2769 return CYMakeType(context, type);
2772 static JSStaticValue Selector_staticValues[2] = {
2773 {"$cyt", &Selector_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2774 {NULL, NULL, NULL, 0}
2777 static JSStaticValue Instance_staticValues[3] = {
2778 {"$cyt", &Instance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2779 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2780 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2781 {NULL, NULL, NULL, 0}
2784 static JSStaticValue FunctionInstance_staticValues[3] = {
2785 {"$cyt", &FunctionInstance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2786 // XXX: this is sadly a duplicate of Instance_staticValues
2787 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2788 {NULL, NULL, NULL, 0}
2791 static JSStaticFunction Instance_staticFunctions[7] = {
2792 {"cy$complete", &Instance_complete_callAsFunction, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2793 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2794 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2795 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2796 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2797 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2801 static JSStaticFunction Messages_staticFunctions[2] = {
2802 {"cy$complete", &Messages_complete_callAsFunction, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2806 static JSStaticValue Constructor_staticValues[5] = {
2807 {"$cyi", &Constructor_getProperty_$cyi, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2808 {"$cyt", &Constructor_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2809 {"constructor", &Constructor_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2810 {"prototype", &Constructor_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2811 {NULL, NULL, NULL, 0}
2814 static JSStaticFunction Constructor_staticFunctions[5] = {
2815 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2816 {"toCYON", &Constructor_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2817 {"toPointer", &Constructor_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2821 static JSStaticFunction Interior_staticFunctions[2] = {
2822 {"$cya", &Interior_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2826 static JSStaticFunction Selector_staticFunctions[5] = {
2827 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2828 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2829 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2830 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2835 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2836 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2837 } CYObjectiveCatch }
2840 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2841 NSArray_ = objc_getClass("NSArray");
2842 NSBlock_ = objc_getClass("NSBlock");
2843 NSDictionary_ = objc_getClass("NSDictionary");
2844 NSNumber_ = objc_getClass("NSNumber");
2845 NSObject_ = objc_getClass("NSObject");
2846 NSString_ = objc_getClass("NSString");
2847 Object_ = objc_getClass("Object");
2850 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2852 // XXX: apparently, iOS now has both of these
2853 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2854 if (NSCFBoolean_ == nil)
2855 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2857 NSCFType_ = objc_getClass("NSCFType");
2859 NSZombie_ = objc_getClass("_NSZombie_");
2861 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2862 NSZombie_ = objc_getClass("NSZombie");
2865 JSClassDefinition definition;
2867 definition = kJSClassDefinitionEmpty;
2868 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2869 definition.className = "Messages";
2870 definition.staticFunctions = Messages_staticFunctions;
2871 definition.hasProperty = &Messages_hasProperty;
2872 definition.getProperty = &Messages_getProperty;
2873 definition.setProperty = &Messages_setProperty;
2874 CYPrivate<Messages>::Class_ = JSClassCreate(&definition);
2876 definition = kJSClassDefinitionEmpty;
2877 definition.className = "Constructor";
2878 definition.parentClass = CYPrivate<Messages>::Class_;
2879 definition.staticValues = Constructor_staticValues;
2880 definition.staticFunctions = Constructor_staticFunctions;
2881 definition.hasInstance = &Constructor_hasInstance;
2882 definition.hasProperty = &Constructor_hasProperty;
2883 definition.getProperty = &Constructor_getProperty;
2884 definition.callAsConstructor = &Constructor_callAsConstructor;
2885 definition.finalize = &CYFinalize;
2886 CYPrivate<Constructor>::Class_ = JSClassCreate(&definition);
2888 definition = kJSClassDefinitionEmpty;
2889 definition.className = "Instance";
2890 definition.staticValues = Instance_staticValues;
2891 definition.staticFunctions = Instance_staticFunctions;
2892 definition.hasProperty = &Instance_hasProperty;
2893 definition.getProperty = &Instance_getProperty;
2894 definition.setProperty = &Instance_setProperty;
2895 definition.deleteProperty = &Instance_deleteProperty;
2896 definition.getPropertyNames = &Instance_getPropertyNames;
2897 definition.finalize = &CYFinalize;
2898 Instance::Class_ = JSClassCreate(&definition);
2900 definition.className = "ArrayInstance";
2901 ArrayInstance_ = JSClassCreate(&definition);
2903 definition.className = "BooleanInstance";
2904 BooleanInstance_ = JSClassCreate(&definition);
2906 definition.className = "NumberInstance";
2907 NumberInstance_ = JSClassCreate(&definition);
2909 definition.className = "ObjectInstance";
2910 ObjectInstance_ = JSClassCreate(&definition);
2912 definition.className = "StringInstance";
2913 StringInstance_ = JSClassCreate(&definition);
2915 definition.className = "FunctionInstance";
2916 definition.staticValues = FunctionInstance_staticValues;
2917 definition.callAsFunction = &FunctionInstance_callAsFunction;
2918 FunctionInstance_ = JSClassCreate(&definition);
2920 definition = kJSClassDefinitionEmpty;
2921 definition.className = "Interior";
2922 definition.staticFunctions = Interior_staticFunctions;
2923 definition.hasProperty = &Interior_hasProperty;
2924 definition.getProperty = &Interior_getProperty;
2925 definition.setProperty = &Interior_setProperty;
2926 definition.getPropertyNames = &Interior_getPropertyNames;
2927 definition.finalize = &CYFinalize;
2928 CYPrivate<Interior>::Class_ = JSClassCreate(&definition);
2930 definition = kJSClassDefinitionEmpty;
2931 definition.className = "Message";
2932 definition.parentClass = cy::Functor::Class_;
2933 definition.callAsFunction = &Message_callAsFunction;
2934 definition.finalize = &CYFinalize;
2935 Message_privateData::Class_ = JSClassCreate(&definition);
2937 definition = kJSClassDefinitionEmpty;
2938 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2939 definition.className = "Prototype";
2940 definition.parentClass = CYPrivate<Messages>::Class_;
2941 definition.finalize = &CYFinalize;
2942 CYPrivate<Prototype>::Class_ = JSClassCreate(&definition);
2944 definition = kJSClassDefinitionEmpty;
2945 definition.className = "Selector";
2946 definition.staticValues = Selector_staticValues;
2947 definition.staticFunctions = Selector_staticFunctions;
2948 definition.callAsFunction = &Selector_callAsFunction;
2949 definition.finalize = &CYFinalize;
2950 CYPrivate<Selector_privateData>::Class_ = JSClassCreate(&definition);
2952 definition = kJSClassDefinitionEmpty;
2953 definition.className = "Super";
2954 definition.finalize = &CYFinalize;
2955 CYPrivate<cy::Super>::Class_ = JSClassCreate(&definition);
2957 definition = kJSClassDefinitionEmpty;
2958 definition.className = "ObjectiveC::Classes";
2959 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2960 definition.getProperty = &ObjectiveC_Classes_getProperty;
2961 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2962 ObjectiveC_Classes_ = JSClassCreate(&definition);
2964 definition = kJSClassDefinitionEmpty;
2965 definition.className = "ObjectiveC::Constants";
2966 definition.getProperty = &ObjectiveC_Constants_getProperty;
2967 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2968 ObjectiveC_Constants_ = JSClassCreate(&definition);
2971 definition = kJSClassDefinitionEmpty;
2972 definition.className = "ObjectiveC::Images";
2973 definition.getProperty = &ObjectiveC_Images_getProperty;
2974 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2975 ObjectiveC_Images_ = JSClassCreate(&definition);
2977 definition = kJSClassDefinitionEmpty;
2978 definition.className = "ObjectiveC::Image::Classes";
2979 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2980 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2981 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2984 definition = kJSClassDefinitionEmpty;
2985 definition.className = "ObjectiveC::Protocols";
2986 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2987 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2988 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2991 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2992 // XXX: this is horrible; there has to be a better way to do this
2994 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2996 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
3002 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
3003 JSObjectRef global(CYGetGlobalObject(context));
3004 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
3005 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
3006 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
3007 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
3009 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
3010 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
3012 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3013 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
3014 CYArrayPush(context, alls, protocols);
3016 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
3017 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
3018 CYArrayPush(context, alls, classes);
3020 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
3021 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
3022 CYArrayPush(context, alls, constants);
3025 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3028 JSObjectRef Message(JSObjectMakeConstructor(context, Message_privateData::Class_, NULL));
3029 JSObjectRef Selector(JSObjectMakeConstructor(context, CYPrivate<Selector_privateData>::Class_, &Selector_new));
3030 JSObjectRef Super(JSObjectMakeConstructor(context, CYPrivate<cy::Super>::Class_, &Super_new));
3032 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance::Class_, &Instance_new));
3033 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
3034 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3036 JSObjectRef Constructor(JSObjectMakeConstructor(context, CYPrivate<::Constructor>::Class_, NULL));
3037 JSObjectRef Constructor_prototype(CYCastJSObject(context, CYGetProperty(context, Constructor, prototype_s)));
3038 CYSetProperty(context, cy, CYJSString("Constructor_prototype"), Constructor_prototype);
3040 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
3041 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
3042 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
3043 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
3044 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
3046 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
3047 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
3048 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
3049 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
3050 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
3052 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
3053 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
3054 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
3055 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
3056 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
3058 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
3059 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
3060 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
3061 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
3062 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
3064 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3065 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3066 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3067 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3068 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3070 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3071 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3072 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3073 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3074 CYSetPrototype(context, StringInstance_prototype, String_prototype);
3076 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3077 CYSetProperty(context, cycript, CYJSString("Message"), Message);
3078 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3079 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3081 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3082 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3085 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3088 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3090 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3091 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3093 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
3094 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
3095 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
3096 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::Object()), kJSPropertyAttributeDontEnum);
3097 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::Meta()), kJSPropertyAttributeDontEnum);
3098 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::Selector()), kJSPropertyAttributeDontEnum);
3100 CYSetProperty(context, cy, CYJSString("cydget"), CYCastJSValue(context, false));
3103 static void *CYObjectiveC_CastSymbol(const char *name) {
3105 #ifdef __GNU_LIBOBJC__
3106 else if (strcmp(name, "object_getClass") == 0)
3107 return reinterpret_cast<void *>(&object_getClass);
3112 static CYHook CYObjectiveCHook = {
3113 &CYObjectiveC_ExecuteStart,
3114 &CYObjectiveC_ExecuteEnd,
3115 &CYObjectiveC_CallFunction,
3116 &CYObjectiveC_Initialize,
3117 &CYObjectiveC_SetupContext,
3118 &CYObjectiveC_CastSymbol,
3121 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3123 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3124 CYSetupContext(context);
3125 JSObjectRef global(CYGetGlobalObject(context));
3126 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
3127 CYSetProperty(context, cy, CYJSString("cydget"), CYCastJSValue(context, true));
3128 } CYObjectiveCatch }
3130 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3133 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3134 utf8 = CYPoolCode(pool, utf8);
3136 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3137 size_t bytes(utf16.size * sizeof(uint16_t));
3138 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3139 memcpy(copy, utf16.data, bytes);
3143 } catch (const CYException &exception) {
3145 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];