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 ObjectiveC_Classes_;
252 static JSClassRef ObjectiveC_Constants_;
253 static JSClassRef ObjectiveC_Protocols_;
256 static JSClassRef ObjectiveC_Image_Classes_;
257 static JSClassRef ObjectiveC_Images_;
261 static Class __NSMallocBlock__;
262 static Class NSCFBoolean_;
263 static Class NSCFType_;
264 static Class NSGenericDeallocHandler_;
266 static Class NSBoolNumber_;
269 static Class NSArray_;
270 static Class NSBlock_;
271 static Class NSDictionary_;
272 static Class NSNumber_;
273 static Class NSObject_;
274 static Class NSString_;
275 static Class NSZombie_;
276 static Class Object_;
278 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
280 JSValueRef Messages::GetPrototype(JSContextRef context) const {
282 if (value_ == NSCFBoolean_)
284 if (value_ == NSBoolNumber_)
286 return CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
287 if (value_ == NSArray_)
288 return CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
289 if (value_ == NSBlock_)
290 return CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
291 if (value_ == NSNumber_)
292 return CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
293 if (value_ == NSDictionary_)
294 return CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
295 if (value_ == NSString_)
296 return CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
298 if (Class super = class_getSuperclass(value_))
299 if (class_isMetaClass(value_) && !class_isMetaClass(super))
300 return CYGetCachedObject(context, CYJSString("TypeInstance_prototype"));
302 return CYPrivate<Messages>::Cache(context, super);
304 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
307 bool CYIsKindOfClass(id object, Class _class) {
308 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
314 JSValueRef Instance::GetPrototype(JSContextRef context) const {
315 return CYPrivate<Messages>::Cache(context, object_getClass(value_));
318 Instance::Instance(id value, Flags flags) :
323 /*else if ([value retainCount] == NSUInteger(-1))
324 flags_ |= Instance::Permanent;*/
326 value_ = [value_ retain];
329 Instance::~Instance() {
334 struct Message_privateData :
337 static JSClassRef Class_;
341 Message_privateData(SEL sel, const char *type, IMP value) :
342 cy::Functor(reinterpret_cast<void (*)()>(value), type),
347 virtual CYPropertyName *GetName(CYPool &pool) const;
349 static JSObjectRef Make(JSContextRef context, SEL sel, const char *type, IMP value);
352 JSClassRef Message_privateData::Class_;
354 JSObjectRef CYMakeInstance(JSContextRef context, id object, Instance::Flags flags = Instance::None) {
355 _assert(object != nil);
358 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
360 if (weak != NULL && &JSWeakObjectMapGet != NULL)
361 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
365 JSObjectRef instance;
367 else if (CYIsKindOfClass(object, NSBlock_))
368 instance = CYPrivate<Block>::Make(context, object, flags);
369 else if (CYIsClass(object))
370 instance = CYPrivate<Constructor>::Make(context, object, flags);
372 instance = CYPrivate<Instance>::Make(context, object, flags);
375 if (weak != NULL && &JSWeakObjectMapSet != NULL)
376 JSWeakObjectMapSet(context, weak, object, instance);
382 @interface NSMethodSignature (Cycript)
383 - (NSString *) _typeString;
386 @interface NSObject (Cycript)
388 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
389 - (JSType) cy$JSType;
391 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
392 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
394 - (bool) cy$hasProperty:(NSString *)name;
395 - (NSObject *) cy$getProperty:(NSString *)name;
396 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
397 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
398 - (bool) cy$deleteProperty:(NSString *)name;
399 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
401 + (bool) cy$hasImplicitProperties;
407 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
410 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
411 _assert(value != nil);
413 Class _class(object_getClass(value));
415 if (class_isMetaClass(_class)) {
416 const char *name(class_getName(value));
417 if (class_isMetaClass(value))
418 return [NSString stringWithFormat:@"object_getClass(%s)", name];
420 return [NSString stringWithUTF8String:name];
423 if (_class == NSZombie_)
424 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
426 SEL sel(@selector(cy$toCYON:inSet:));
428 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
429 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
430 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
431 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
432 return [value cy$toCYON:objective inSet:objects];
434 return [NSString stringWithFormat:@"%@", value];
437 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
439 return CYCastNSCYON(value, objective, *objects);
441 std::set<void *> objects;
442 return CYCastNSCYON(value, objective, objects);
446 struct PropertyAttributes {
451 const char *variable;
464 PropertyAttributes(objc_property_t property) :
476 name = property_getName(property);
477 const char *attributes(property_getAttributes(property));
479 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
480 if ((next = strchr(token, ',')) != NULL)
483 case 'R': readonly = true; break;
484 case 'C': copy = true; break;
485 case '&': retain = true; break;
486 case 'N': nonatomic = true; break;
487 case 'G': getter_ = token + 1; break;
488 case 'S': setter_ = token + 1; break;
489 case 'V': variable = token + 1; break;
493 /*if (variable == NULL) {
494 variable = property_getName(property);
495 size_t size(strlen(variable));
496 char *name(new(pool_) char[size + 2]);
498 memcpy(name + 1, variable, size);
499 name[size + 1] = '\0';
504 const char *Getter() {
506 getter_ = pool_.strdup(name);
510 const char *Setter() {
511 if (setter_ == NULL && !readonly) {
512 size_t length(strlen(name));
514 char *temp(new(pool_) char[length + 5]);
520 temp[3] = toupper(name[0]);
521 memcpy(temp + 4, name + 1, length - 1);
524 temp[length + 3] = ':';
525 temp[length + 4] = '\0';
534 @interface CYWebUndefined : NSObject {
537 + (CYWebUndefined *) undefined;
541 @implementation CYWebUndefined
543 + (CYWebUndefined *) undefined {
544 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
550 #define WebUndefined CYWebUndefined
552 /* Bridge: CYJSObject {{{ */
553 @interface CYJSObject : NSMutableDictionary {
555 JSGlobalContextRef context_;
558 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
560 - (NSUInteger) count;
561 - (id) objectForKey:(id)key;
562 - (NSEnumerator *) keyEnumerator;
563 - (void) setObject:(id)object forKey:(id)key;
564 - (void) removeObjectForKey:(id)key;
568 /* Bridge: CYJSArray {{{ */
569 @interface CYJSArray : NSMutableArray {
571 JSGlobalContextRef context_;
574 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
576 - (NSUInteger) count;
577 - (id) objectAtIndex:(NSUInteger)index;
579 - (void) addObject:(id)anObject;
580 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
581 - (void) removeLastObject;
582 - (void) removeObjectAtIndex:(NSUInteger)index;
583 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
588 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
589 return JSValueIsObjectOfClass(context, value, CYPrivate<Instance>::Class_);
592 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
593 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
597 struct CYBlockDescriptor {
599 BlockDescriptor1 one_;
600 BlockDescriptor2 two_;
601 BlockDescriptor3 three_;
604 Closure_privateData *internal_;
607 void CYDisposeBlock(BlockLiteral *literal) {
608 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
611 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
612 JSObjectRef _this(CYCastJSObject(context, values[0]));
613 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
616 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
617 _assert(__NSMallocBlock__ != Nil);
618 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
620 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
621 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
623 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockAdapter_);
624 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->value_);
626 literal->isa = __NSMallocBlock__;
627 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
628 literal->reserved = 0;
629 literal->descriptor = descriptor;
631 descriptor->d_.one_.size = sizeof(descriptor->d_);
632 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
633 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
635 return reinterpret_cast<NSBlock *>(literal);
639 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
640 if (CYJSValueIsNSObject(context, object)) {
641 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
642 return internal->value_;
645 if (NSObject *pointer = CYCastPointerEx<NSObject *>(context, object))
648 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
649 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
650 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
653 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
654 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
658 @interface NSBoolNumber : NSNumber {
663 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
667 switch (JSType type = JSValueGetType(context, value)) {
668 case kJSTypeUndefined:
669 object = [WebUndefined undefined];
679 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
682 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
688 object = CYCopyNSNumber(context, value);
693 object = CYCopyNSString(context, value);
698 // XXX: this might could be more efficient
699 object = CYCastNSObject(pool, context, (JSObjectRef) value);
704 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
711 return CYPoolRelease(pool, object);
713 return [object retain];
716 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
717 return CYNSObject(pool, context, value, true);
720 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
721 return CYNSObject(&pool, context, value, false);
724 /* Bridge: NSArray {{{ */
725 @implementation NSArray (Cycript)
728 return [[self mutableCopy] autorelease];
731 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
732 _oassert(objects.insert(self).second);
734 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
735 [json appendString:@"@["];
739 for (id object in self) {
741 for (size_t index(0), count([self count]); index != count; ++index) {
742 id object([self objectAtIndex:index]);
745 [json appendString:@","];
748 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
749 [json appendString:CYCastNSCYON(object, true, objects)];
751 [json appendString:@","];
756 [json appendString:@"]"];
760 - (bool) cy$hasProperty:(NSString *)name {
761 if ([name isEqualToString:@"length"])
764 size_t index(CYGetIndex(name));
765 if (index == _not(size_t) || index >= [self count])
766 return [super cy$hasProperty:name];
771 - (NSObject *) cy$getProperty:(NSString *)name {
772 size_t index(CYGetIndex(name));
773 if (index == _not(size_t) || index >= [self count])
774 return [super cy$getProperty:name];
776 return [self objectAtIndex:index];
779 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
781 if ([name isEqualToString:@"length"])
782 return CYCastJSValue(context, [self count]);
785 return [super cy$getProperty:name inContext:context];
788 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
789 [super cy$getPropertyNames:names inContext:context];
791 for (size_t index(0), count([self count]); index != count; ++index) {
792 id object([self objectAtIndex:index]);
793 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
795 sprintf(name, "%zu", index);
796 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
801 + (bool) cy$hasImplicitProperties {
807 /* Bridge: NSBlock {{{ */
809 @interface NSBlock : NSObject
813 static const char *CYBlockEncoding(NSBlock *self);
814 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature);
816 @implementation NSBlock (Cycript)
818 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
822 if (!CYBlockSignature(pool, self, type.signature))
823 return [super cy$toCYON:objective inSet:objects];
824 _oassert(objects.insert(self).second);
826 CYType *typed((new(pool) CYTypeExpression(CYDecodeType(pool, &type)))->typed_);
827 CYTypeModifier *&modifier(CYGetLast(typed->modifier_));
828 CYTypeBlockWith *with(dynamic_cast<CYTypeBlockWith *>(modifier));
829 _assert(with != NULL);
830 CYObjCBlock *block(new(pool) CYObjCBlock(typed, with->parameters_, NULL));
833 std::ostringstream str;
835 CYOutput out(*str.rdbuf(), options);
836 block->Output(out, CYNoFlags);
838 std::string value(str.str());
839 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
845 /* Bridge: NSBoolNumber {{{ */
847 @implementation NSBoolNumber (Cycript)
849 - (JSType) cy$JSType {
850 return kJSTypeBoolean;
853 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
854 NSString *value([self boolValue] ? @"true" : @"false");
855 return objective ? value : [NSString stringWithFormat:@"@%@", value];
858 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
859 return CYCastJSValue(context, (bool) [self boolValue]);
865 /* Bridge: NSDictionary {{{ */
866 @implementation NSDictionary (Cycript)
869 return [[self mutableCopy] autorelease];
872 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
873 _oassert(objects.insert(self).second);
875 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
876 [json appendString:@"@{"];
880 for (NSObject *key in self) {
882 NSEnumerator *keys([self keyEnumerator]);
883 while (NSObject *key = [keys nextObject]) {
886 [json appendString:@","];
889 [json appendString:CYCastNSCYON(key, true, objects)];
890 [json appendString:@":"];
891 NSObject *object([self objectForKey:key]);
892 [json appendString:CYCastNSCYON(object, true, objects)];
895 [json appendString:@"}"];
899 - (bool) cy$hasProperty:(NSString *)name {
900 return [self objectForKey:name] != nil;
903 - (NSObject *) cy$getProperty:(NSString *)name {
904 return [self objectForKey:name];
907 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
908 [super cy$getPropertyNames:names inContext:context];
911 for (NSObject *key in self) {
913 NSEnumerator *keys([self keyEnumerator]);
914 while (NSObject *key = [keys nextObject]) {
916 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
920 + (bool) cy$hasImplicitProperties {
926 /* Bridge: NSMutableArray {{{ */
927 @implementation NSMutableArray (Cycript)
929 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
930 if ([name isEqualToString:@"length"]) {
931 // XXX: is this not intelligent?
932 NSNumber *number(reinterpret_cast<NSNumber *>(value));
933 NSUInteger size([number unsignedIntegerValue]);
934 NSUInteger count([self count]);
936 [self removeObjectsInRange:NSMakeRange(size, count - size)];
937 else if (size != count) {
938 WebUndefined *undefined([WebUndefined undefined]);
939 for (size_t i(count); i != size; ++i)
940 [self addObject:undefined];
945 size_t index(CYGetIndex(name));
946 if (index == _not(size_t))
947 return [super cy$setProperty:name to:value];
949 id object(value ?: [NSNull null]);
951 size_t count([self count]);
953 [self replaceObjectAtIndex:index withObject:object];
955 if (index != count) {
956 WebUndefined *undefined([WebUndefined undefined]);
957 for (size_t i(count); i != index; ++i)
958 [self addObject:undefined];
961 [self addObject:object];
967 - (bool) cy$deleteProperty:(NSString *)name {
968 size_t index(CYGetIndex(name));
969 if (index == _not(size_t) || index >= [self count])
970 return [super cy$deleteProperty:name];
971 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
977 /* Bridge: NSMutableDictionary {{{ */
978 @implementation NSMutableDictionary (Cycript)
980 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
981 [self setObject:(value ?: [NSNull null]) forKey:name];
985 - (bool) cy$deleteProperty:(NSString *)name {
986 if ([self objectForKey:name] == nil)
989 [self removeObjectForKey:name];
996 /* Bridge: NSNumber {{{ */
997 @implementation NSNumber (Cycript)
999 - (JSType) cy$JSType {
1001 // XXX: this just seems stupid
1002 if ([self class] == NSCFBoolean_)
1003 return kJSTypeBoolean;
1005 return kJSTypeNumber;
1008 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1009 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1010 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1013 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1014 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1015 } CYObjectiveCatch }
1019 /* Bridge: NSNull {{{ */
1020 @implementation NSNull (Cycript)
1022 - (JSType) cy$JSType {
1026 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1027 NSString *value(@"null");
1028 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1031 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1032 return CYJSNull(context);
1033 } CYObjectiveCatch }
1037 /* Bridge: NSObject {{{ */
1038 @implementation NSObject (Cycript)
1044 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1045 return [self cy$valueOfInContext:context];
1048 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1050 } CYObjectiveCatch }
1052 - (JSType) cy$JSType {
1053 return kJSTypeObject;
1056 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1057 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1060 - (bool) cy$hasProperty:(NSString *)name {
1064 - (NSObject *) cy$getProperty:(NSString *)name {
1068 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1069 if (NSObject *value = [self cy$getProperty:name])
1070 return CYCastJSValue(context, value);
1072 } CYObjectiveCatch }
1074 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1078 - (bool) cy$deleteProperty:(NSString *)name {
1082 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1085 + (bool) cy$hasImplicitProperties {
1091 /* Bridge: NSOrderedSet {{{ */
1093 @implementation NSOrderedSet (Cycript)
1095 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1096 _oassert(objects.insert(self).second);
1098 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1099 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1100 [json appendString:CYCastNSCYON([self array], true, objects)];
1101 [json appendString:@"]]"];
1108 /* Bridge: NSProxy {{{ */
1109 @implementation NSProxy (Cycript)
1111 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1112 return [[self description] cy$toCYON:objective inSet:objects];
1117 /* Bridge: NSSet {{{ */
1118 @implementation NSSet (Cycript)
1120 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1121 _oassert(objects.insert(self).second);
1123 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1124 [json appendString:@"[NSSet setWithArray:"];
1125 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1126 [json appendString:@"]]"];
1132 /* Bridge: NSString {{{ */
1133 @implementation NSString (Cycript)
1136 return [[self copy] autorelease];
1139 - (JSType) cy$JSType {
1140 return kJSTypeString;
1143 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1144 std::ostringstream str;
1147 CYUTF8String string(CYCastUTF8String(self));
1148 CYStringify(str, string.data, string.size, CYStringifyModeNative);
1149 std::string value(str.str());
1150 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1153 - (bool) cy$hasProperty:(NSString *)name {
1154 size_t index(CYGetIndex(name));
1155 if (index == _not(size_t) || index >= [self length])
1156 return [super cy$hasProperty:name];
1161 - (NSObject *) cy$getProperty:(NSString *)name {
1162 size_t index(CYGetIndex(name));
1163 if (index == _not(size_t) || index >= [self length])
1164 return [super cy$getProperty:name];
1166 return [self substringWithRange:NSMakeRange(index, 1)];
1169 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1170 [super cy$getPropertyNames:names inContext:context];
1172 for (size_t index(0), length([self length]); index != length; ++index) {
1174 sprintf(name, "%zu", index);
1175 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1179 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1180 return CYCastJSValue(context, CYJSString(context, self));
1181 } CYObjectiveCatch }
1185 /* Bridge: WebUndefined {{{ */
1186 @implementation WebUndefined (Cycript)
1188 - (JSType) cy$JSType {
1189 return kJSTypeUndefined;
1192 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1193 NSString *value(@"undefined");
1194 return value; // XXX: maybe use the below code, adding @undefined?
1195 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1198 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1199 return CYJSUndefined(context);
1200 } CYObjectiveCatch }
1205 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1206 id self(CYCastNSObject(&pool, context, value));
1207 if (CYIsClass(self))
1208 return (Class) self;
1209 throw CYJSError(context, "got something that is not a Class");
1213 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1215 size_t size(JSPropertyNameArrayGetCount(names));
1216 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1217 for (size_t index(0); index != size; ++index)
1218 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1222 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) {
1224 return CYJSNull(context);
1225 return CYMakeInstance(context, value);
1228 @implementation CYJSObject
1230 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1231 if ((self = [super init]) != nil) {
1233 context_ = CYGetJSContext(context);
1234 JSGlobalContextRetain(context_);
1235 JSValueProtect(context_, object_);
1237 } CYObjectiveCatch }
1239 - (void) dealloc { CYObjectiveTry {
1240 JSValueUnprotect(context_, object_);
1241 JSGlobalContextRelease(context_);
1243 } CYObjectiveCatch }
1245 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1247 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1249 return [super cy$toCYON:objective inSet:objects];
1251 return [NSString stringWithUTF8String:cyon];
1252 } CYObjectiveCatch }
1254 - (NSUInteger) count { CYObjectiveTry {
1255 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1256 size_t size(JSPropertyNameArrayGetCount(names));
1257 JSPropertyNameArrayRelease(names);
1259 } CYObjectiveCatch }
1261 - (id) objectForKey:(id)key { CYObjectiveTry {
1262 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1263 if (JSValueIsUndefined(context, value))
1265 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1266 } CYObjectiveCatch }
1268 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1269 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1270 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1271 JSPropertyNameArrayRelease(names);
1273 } CYObjectiveCatch }
1275 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1276 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1277 } CYObjectiveCatch }
1279 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1280 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1281 } CYObjectiveCatch }
1285 @implementation CYJSArray
1287 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1289 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1290 } CYObjectiveCatch }
1292 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1293 if ((self = [super init]) != nil) {
1295 context_ = CYGetJSContext(context);
1296 JSGlobalContextRetain(context_);
1297 JSValueProtect(context_, object_);
1299 } CYObjectiveCatch }
1301 - (void) dealloc { CYObjectiveTry {
1302 JSValueUnprotect(context_, object_);
1303 JSGlobalContextRelease(context_);
1305 } CYObjectiveCatch }
1307 - (NSUInteger) count { CYObjectiveTry {
1308 return CYArrayLength(context, object_);
1309 } CYObjectiveCatch }
1311 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1312 size_t bounds([self count]);
1313 if (index >= bounds)
1314 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1315 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1316 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1317 } CYObjectiveCatch }
1319 - (void) addObject:(id)object { CYObjectiveTry {
1320 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1321 } CYObjectiveCatch }
1323 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1324 size_t bounds([self count] + 1);
1325 if (index >= bounds)
1326 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1327 JSValueRef arguments[3];
1328 arguments[0] = CYCastJSValue(context, index);
1329 arguments[1] = CYCastJSValue(context, 0);
1330 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1331 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1332 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1333 } CYObjectiveCatch }
1335 - (void) removeLastObject { CYObjectiveTry {
1336 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1337 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1338 } CYObjectiveCatch }
1340 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1341 size_t bounds([self count]);
1342 if (index >= bounds)
1343 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1344 JSValueRef arguments[2];
1345 arguments[0] = CYCastJSValue(context, index);
1346 arguments[1] = CYCastJSValue(context, 1);
1347 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1348 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1349 } CYObjectiveCatch }
1351 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1352 size_t bounds([self count]);
1353 if (index >= bounds)
1354 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1355 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1356 } CYObjectiveCatch }
1360 // XXX: inherit from or replace with CYJSObject
1361 @interface CYInternal : NSObject {
1362 JSGlobalContextRef context_;
1363 JSObjectRef object_;
1368 @implementation CYInternal
1370 - (void) dealloc { CYObjectiveTry {
1371 JSValueUnprotect(context_, object_);
1372 JSGlobalContextRelease(context_);
1374 } CYObjectiveCatch }
1376 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1377 if ((self = [super init]) != nil) {
1378 context_ = CYGetJSContext(context);
1379 JSGlobalContextRetain(context_);
1381 } CYObjectiveCatch }
1383 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1384 if (object_ == NULL)
1387 return JSObjectHasProperty(context, object_, name);
1390 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1391 if (object_ == NULL)
1394 return CYGetProperty(context, object_, name);
1397 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1398 @synchronized (self) {
1399 if (object_ == NULL) {
1400 object_ = JSObjectMake(context, NULL, NULL);
1401 JSValueProtect(context, object_);
1405 CYSetProperty(context, object_, name, value);
1408 + (CYInternal *) get:(id)object {
1410 if (&objc_getAssociatedObject == NULL)
1413 @synchronized (object) {
1414 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1422 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1424 if (&objc_getAssociatedObject == NULL)
1427 @synchronized (object) {
1428 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1431 if (&objc_setAssociatedObject == NULL)
1434 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1435 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1445 static JSValueRef CYCastJSValue(JSContextRef context, SEL sel) {
1447 return CYJSNull(context);
1448 return CYPrivate<Selector_privateData>::Make(context, sel);
1451 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1452 if (JSValueIsObjectOfClass(context, value, CYPrivate<Selector_privateData>::Class_)) {
1453 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1454 return reinterpret_cast<SEL>(internal->value_);
1457 return sel_registerName(CYPoolCString(pool, context, value));
1461 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1462 return (void *) [[NSAutoreleasePool alloc] init];
1463 } CYSadCatch(NULL) }
1465 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1466 return [(NSAutoreleasePool *) handle release];
1469 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1470 CYCallFunction(pool, context, cif, function, value, values);
1473 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, const sig::Signature *signature) {
1475 if (JSValueIsNull(context, value))
1477 JSObjectRef object(CYCastJSObject(context, value));
1479 if (JSValueIsObjectOfClass(context, object, CYPrivate<Block>::Class_))
1480 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_;
1482 if (JSValueIsObjectOfClass(context, object, CYPrivate<Instance>::Class_)) {
1483 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_ == nil);
1487 _assert(JSObjectIsFunction(context, object));
1489 _assert(signature != NULL);
1490 _assert(signature->count != 0);
1492 sig::Signature modified;
1493 modified.count = signature->count + 1;
1494 modified.elements = new(pool) sig::Element[modified.count];
1496 modified.elements[0] = signature->elements[0];
1497 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1499 modified.elements[1].name = NULL;
1500 modified.elements[1].type = new(pool) sig::Object();
1501 modified.elements[1].offset = _not(size_t);
1503 return CYMakeBlock(context, object, modified);
1511 void Block::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1512 // XXX: this function actually needs to handle null pools as it is an autorelease
1513 _assert(pool != NULL);
1514 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &signature);
1517 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1518 void Object::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1519 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1522 void Meta::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1523 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1526 void Selector::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1527 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1530 JSValueRef Object::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1531 NSObject *value(*reinterpret_cast<NSObject **>(data));
1533 return CYJSNull(context);
1534 JSObjectRef object(CYMakeInstance(context, value));
1537 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1539 if (internal->IsUninitialized()) {
1540 internal->flags_ &= ~Instance::Uninitialized;
1541 if (internal->value_ == nil)
1542 internal->value_ = value;
1544 _assert(internal->value_ == value);
1553 JSValueRef Meta::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1554 if (Class value = *reinterpret_cast<Class *>(data))
1555 return CYMakeInstance(context, value, Instance::Permanent);
1556 return CYJSNull(context);
1559 JSValueRef Selector::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1560 return CYCastJSValue(context, *reinterpret_cast<SEL *>(data));
1563 JSValueRef Block::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1564 return CYCastJSValue(context, *reinterpret_cast<NSObject **>(data));
1569 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1570 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1574 method_getReturnType(method, type, sizeof(type));
1579 // XXX: possibly use a more "awesome" check?
1583 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1584 JSObjectRef _this(CYCastJSObject(context, values[0]));
1585 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1588 JSObjectRef Message_privateData::Make(JSContextRef context, SEL sel, const char *type, IMP value) {
1589 Message_privateData *internal(new Message_privateData(sel, type, value));
1590 JSObjectRef object(JSObjectMake(context, Message_privateData::Class_, internal));
1591 CYSetPrototype(context, object, CYGetCachedValue(context, CYJSString("Functor_prototype")));
1595 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1596 JSObjectRef function(CYCastJSObject(context, value));
1598 sig::Signature signature;
1599 sig::Parse(pool, &signature, encoding, &Structor_);
1600 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1601 // XXX: see notes in Library.cpp about needing to leak
1602 return reinterpret_cast<IMP>(internal->value_);
1605 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1606 auto internal(CYPrivate<Messages>::Get(context, object));
1607 Class _class(internal->value_);
1610 const char *name(CYPoolCString(pool, context, property));
1612 if (SEL sel = sel_getUid(name))
1613 if (class_getInstanceMethod(_class, sel) != NULL)
1619 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1620 auto internal(CYPrivate<Messages>::Get(context, object));
1621 Class _class(internal->value_);
1624 const char *name(CYPoolCString(pool, context, property));
1626 if (SEL sel = sel_getUid(name))
1627 if (objc_method *method = class_getInstanceMethod(_class, sel))
1628 return Message_privateData::Make(context, sel, method_getTypeEncoding(method), method_getImplementation(method));
1633 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1634 auto internal(CYPrivate<Messages>::Get(context, object));
1635 Class _class(internal->value_);
1638 const char *name(CYPoolCString(pool, context, property));
1639 SEL sel(sel_registerName(name));
1644 if (JSValueIsObjectOfClass(context, value, Message_privateData::Class_)) {
1645 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1646 type = sig::Unparse(pool, &message->signature_);
1647 imp = reinterpret_cast<IMP>(message->value_);
1648 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1649 type = method_getTypeEncoding(method);
1650 imp = CYMakeMessage(context, value, type);
1651 } else return false;
1653 objc_method *method(NULL);
1655 objc_method **methods(class_copyMethodList(_class, &size));
1656 pool.atexit(free, methods);
1658 for (size_t i(0); i != size; ++i)
1659 if (sel_isEqual(method_getName(methods[i]), sel)) {
1660 method = methods[i];
1665 method_setImplementation(method, imp);
1667 class_addMethod(_class, sel, imp, type);
1672 static JSValueRef Messages_complete_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1674 if (!CYCastBool(context, arguments[1]))
1675 return CYObjectMakeArray(context, 0, NULL);
1679 _assert(count == 1);
1681 CYUTF8String prefix(CYPoolUTF8String(pool, context, CYJSString(context, arguments[0])));
1683 auto internal(CYPrivate<Messages>::Get(context, _this));
1684 Class _class(internal->value_);
1687 objc_method **data(class_copyMethodList(_class, &size));
1688 pool.atexit(free, data);
1690 JSObjectRef array(NULL); {
1691 CYArrayBuilder<1024> values(context, array);
1693 for (size_t i(0); i != size; ++i) {
1694 CYUTF8String name(sel_getName(method_getName(data[i])));
1695 if (CYStartsWith(name, prefix))
1696 values(CYCastJSValue(context, CYJSString(name)));
1701 static bool CYHasImplicitProperties(JSContextRef context, Class _class) {
1702 if (!CYCastBool(context, CYGetCachedValue(context, CYJSString("cydget"))))
1703 if (class_getProperty(NSObject_, "description") != NULL)
1705 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1706 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1708 return [_class cy$hasImplicitProperties];
1711 static objc_property_t CYFindProperty(CYPool &pool, Class _class, const char *name) {
1714 if (objc_property_t property = class_getProperty(_class, name))
1718 /* // XXX: I don't think any of this is required
1720 Protocol **protocols(class_copyProtocolList(_class, &count));
1721 // XXX: just implement a scope guard already :/
1722 pool.atexit(free, protocols);
1724 for (unsigned int i(0); i != count; ++i)
1725 if (objc_property_t property = protocol_getProperty(protocols[i], name, true, true))
1728 return CYFindProperty(pool, class_getSuperclass(_class), name); */
1731 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1732 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1733 id self(internal->value_);
1735 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1739 NSString *name(CYCastNSString(&pool, context, property));
1741 if (CYInternal *internal = [CYInternal get:self])
1742 if ([internal hasProperty:property inContext:context])
1745 Class _class(object_getClass(self));
1748 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1749 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1750 if ([self cy$hasProperty:name])
1752 } CYPoolCatch(false)
1754 const char *string(CYPoolCString(pool, context, name));
1756 if (CYFindProperty(pool, _class, string) != NULL)
1759 if (CYHasImplicitProperties(context, _class))
1760 if (SEL sel = sel_getUid(string))
1761 if (CYImplements(self, _class, sel, true))
1767 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1768 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1769 id self(internal->value_);
1771 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1772 return CYPrivate<Interior>::Make(context, self, context, object);
1775 NSString *name(CYCastNSString(&pool, context, property));
1777 if (CYInternal *internal = [CYInternal get:self])
1778 if (JSValueRef value = [internal getProperty:property inContext:context])
1782 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1786 const char *string(CYPoolCString(pool, context, name));
1787 Class _class(object_getClass(self));
1789 if (objc_property_t property = CYFindProperty(pool, _class, string)) {
1790 PropertyAttributes attributes(property);
1791 SEL sel(sel_registerName(attributes.Getter()));
1792 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1795 if (CYHasImplicitProperties(context, _class))
1796 if (SEL sel = sel_getUid(string))
1797 if (CYImplements(self, _class, sel, true))
1798 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1803 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1804 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1805 id self(internal->value_);
1809 NSString *name(CYCastNSString(&pool, context, property));
1810 NSObject *data(CYCastNSObject(&pool, context, value));
1813 if ([self cy$setProperty:name to:data])
1815 } CYPoolCatch(false)
1817 const char *string(CYPoolCString(pool, context, name));
1818 Class _class(object_getClass(self));
1820 if (objc_property_t property = CYFindProperty(pool, _class, string)) {
1821 PropertyAttributes attributes(property);
1822 if (const char *setter = attributes.Setter()) {
1823 SEL sel(sel_registerName(setter));
1824 JSValueRef arguments[1] = {value};
1825 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1830 size_t length(strlen(string));
1832 char set[length + 5];
1838 if (string[0] != '\0') {
1839 set[3] = toupper(string[0]);
1840 memcpy(set + 4, string + 1, length - 1);
1843 set[length + 3] = ':';
1844 set[length + 4] = '\0';
1846 if (SEL sel = sel_getUid(set))
1847 if (CYImplements(self, _class, sel)) {
1848 JSValueRef arguments[1] = {value};
1849 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1853 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1854 [internal setProperty:property toValue:value inContext:context];
1861 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1862 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1863 id self(internal->value_);
1866 NSString *name(CYCastNSString(NULL, context, property));
1867 return [self cy$deleteProperty:name];
1868 } CYPoolCatch(false)
1869 } CYCatch(false) return /*XXX*/ false; }
1871 static void CYForEachProperty(CYPool &pool, Class _class, const Functor<void (objc_method *, const char *)> &code) {
1872 for (; _class != Nil; _class = class_getSuperclass(_class)) {
1874 objc_method **data(class_copyMethodList(_class, &size));
1875 pool.atexit(free, data);
1877 for (size_t i(0); i != size; ++i) {
1878 objc_method *method(data[i]);
1880 const char *name(sel_getName(method_getName(method)));
1881 if (strchr(name, ':') != NULL)
1889 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1890 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1891 id self(internal->value_);
1894 Class _class(object_getClass(self));
1896 for (Class current(_class); current != Nil; current = class_getSuperclass(current)) {
1898 objc_property_t *data(class_copyPropertyList(current, &size));
1899 pool.atexit(free, data);
1901 for (size_t i(0); i != size; ++i)
1902 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1905 if (CYHasImplicitProperties(context, _class))
1906 CYForEachProperty(pool, _class, fun([&](objc_method *method, const char *name) {
1907 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1911 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1912 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1913 [self cy$getPropertyNames:names inContext:context];
1917 static JSValueRef Instance_complete_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1918 if (!CYJSValueIsNSObject(context, _this))
1919 return CYObjectMakeArray(context, 0, NULL);
1921 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
1922 id self(internal->value_);
1924 _assert(count == 1 || count == 2);
1926 Class _class(object_getClass(self));
1928 CYUTF8String prefix(CYPoolUTF8String(pool, context, CYJSString(context, arguments[0])));
1930 JSObjectRef array(NULL); {
1931 CYArrayBuilder<1024> values(context, array);
1933 CYForEachProperty(pool, _class, fun([&](objc_method *method, const char *name) {
1934 if (!CYStartsWith(name, prefix))
1936 const char *type(method_getTypeEncoding(method));
1937 if (type == NULL || *type == '\0' || *type == 'v')
1939 if (class_getProperty(_class, name) != NULL)
1941 values(CYCastJSValue(context, CYJSString(pool.strcat(name, "()", NULL))));
1946 static JSObjectRef Constructor_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1947 auto internal(CYPrivate<Constructor>::Get(context, object));
1948 JSObjectRef value(CYMakeInstance(context, [internal->value_ alloc], Instance::Uninitialized));
1952 static const char *CYBlockEncoding(NSBlock *self) {
1953 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1954 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1956 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1957 descriptor += sizeof(BlockDescriptor1);
1958 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1959 descriptor += sizeof(BlockDescriptor2);
1960 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1961 return descriptor3->signature;
1964 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature) {
1965 const char *encoding(CYBlockEncoding(self));
1966 if (encoding == NULL)
1969 sig::Parse(pool, &signature, encoding, &Structor_);
1970 _assert(signature.count >= 2);
1972 _assert(dynamic_cast<sig::Object *>(signature.elements[1].type) != NULL);
1973 signature.elements[1] = signature.elements[0];
1975 ++signature.elements;
1981 static JSValueRef Block_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1982 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1983 id self(internal->value_);
1985 if (const char *encoding = CYBlockEncoding(self)) {
1991 sig::Signature signature;
1992 sig::Parse(pool, &signature, encoding, &Structor_);
1995 sig::sig_ffi_cif(pool, 0, signature, &cif);
1997 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1998 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1999 return CYCallFunction(pool, context, 1, setup, count, arguments, false, false, signature, &cif, function);
2003 CYThrow("NSBlock without signature field passed arguments");
2007 } CYPoolCatch(NULL);
2012 static bool Constructor_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
2013 auto internal(CYPrivate<Constructor>::Get(context, constructor));
2014 Class _class(internal->value_);
2016 if (CYJSValueIsNSObject(context, instance)) {
2017 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2018 // XXX: this isn't always safe
2019 return [linternal->value_ isKindOfClass:_class];
2025 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2027 throw CYJSError(context, "incorrect number of arguments to Instance");
2029 id value(CYCastNSObject(&pool, context, arguments[0]));
2031 value = [NSNull null];
2032 return CYCastJSValue(context, [value cy$box]);
2035 static bool Interior_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2036 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2039 id self(internal->value_);
2040 const char *name(CYPoolCString(pool, context, property));
2042 if (object_getInstanceVariable(self, name, NULL) != NULL)
2048 static void CYBitField(CYPool &pool, unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2049 length = CYCastDouble(encoding + 1);
2053 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2054 pool.atexit(free, ivars);
2056 for (size_t i(0); i != size; ++i)
2057 if (ivars[i] == ivar)
2059 else if (ivar_getOffset(ivars[i]) == offset) {
2060 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2061 _assert(encoding != NULL);
2062 _assert(encoding[0] == 'b');
2063 shift += CYCastDouble(encoding + 1);
2067 static JSValueRef Interior_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2068 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2071 id self(internal->value_);
2072 const char *name(CYPoolCString(pool, context, property));
2074 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2075 ptrdiff_t offset(ivar_getOffset(ivar));
2076 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2078 const char *encoding(ivar_getTypeEncoding(ivar));
2079 _assert(encoding != NULL);
2080 _assert(encoding[0] != '\0');
2081 if (encoding[0] == 'b') {
2082 unsigned length, shift;
2083 CYBitField(pool, length, shift, self, ivar, encoding, offset);
2084 _assert(shift + length <= sizeof(uintptr_t) * 8);
2085 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2086 uintptr_t mask((1 << length) - 1);
2087 return CYCastJSValue(context, (field >> shift) & mask);
2089 #if defined(__APPLE__) && defined(__LP64__)
2090 // XXX: maybe do even more verifications here
2091 if (strcmp(name, "isa") == 0)
2092 return CYCastJSValue(context, object_getClass(self));
2095 auto type(new(pool) Type_privateData(encoding));
2096 return type->type_->FromFFI(context, type->GetFFI(), data);
2103 static bool Interior_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, 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 if (encoding[0] == 'b') {
2117 unsigned length, shift;
2118 CYBitField(pool, length, shift, self, ivar, encoding, offset);
2119 _assert(shift + length <= sizeof(uintptr_t) * 8);
2120 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2121 uintptr_t mask((1 << length) - 1);
2122 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2124 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2125 type->type_->PoolFFI(&pool, context, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2133 static void Interior_getPropertyNames_(CYPool &pool, Class _class, JSPropertyNameAccumulatorRef names) {
2134 if (Class super = class_getSuperclass(_class))
2135 Interior_getPropertyNames_(pool, super, names);
2138 objc_ivar **data(class_copyIvarList(_class, &size));
2139 pool.atexit(free, data);
2141 for (size_t i(0); i != size; ++i)
2142 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2145 static void Interior_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2146 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2149 id self(internal->value_);
2150 Class _class(object_getClass(self));
2152 Interior_getPropertyNames_(pool, _class, names);
2155 static JSValueRef Interior_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2156 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2157 return internal->owner_;
2160 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2162 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2165 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2167 NSString *name(CYCastNSString(&pool, context, property));
2168 if (Class _class = NSClassFromString(name))
2169 return CYMakeInstance(context, _class, Instance::Permanent);
2173 static Class *CYCopyClassList(size_t &size) {
2174 size = objc_getClassList(NULL, 0);
2175 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2178 size_t writ(objc_getClassList(data, size));
2184 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2195 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2199 if (Class *data = CYCopyClassList(size)) {
2200 pool.atexit(free, data);
2201 for (size_t i(0); i != size; ++i)
2202 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2207 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2208 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2211 const char *name(CYPoolCString(pool, context, property));
2214 const char **data(objc_copyClassNamesForImage(internal, &size));
2215 pool.atexit(free, data);
2218 for (size_t i(0); i != size; ++i)
2219 if (strcmp(name, data[i]) == 0) {
2220 if (Class _class = objc_getClass(name))
2221 return CYMakeInstance(context, _class, Instance::Permanent);
2229 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2230 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2234 const char **data(objc_copyClassNamesForImage(internal, &size));
2235 pool.atexit(free, data);
2237 for (size_t i(0); i != size; ++i)
2238 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2241 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2243 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2246 const char **data(objc_copyImageNames(&size));
2247 pool.atexit(free, data);
2249 for (size_t i(0); i != size; ++i)
2250 if (name == data[i]) {
2251 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2252 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2259 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2263 const char **data(objc_copyImageNames(&size));
2264 pool.atexit(free, data);
2266 for (size_t i(0); i != size; ++i)
2267 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2271 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2273 const char *name(CYPoolCString(pool, context, property));
2274 if (Protocol *protocol = objc_getProtocol(name))
2275 return CYMakeInstance(context, protocol, Instance::Permanent);
2279 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2283 Protocol **data(objc_copyProtocolList(&size));
2284 pool.atexit(free, data);
2286 for (size_t i(0); i != size; ++i)
2287 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2290 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2292 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2294 return CYJSNull(context);
2298 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2299 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2303 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2304 *data = reinterpret_cast<void *>(address);
2305 return KERN_SUCCESS;
2309 std::set<Class> query_;
2310 JSContextRef context_;
2311 JSObjectRef results_;
2314 struct CYObjectStruct {
2318 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2319 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2320 JSContextRef context(choice->context_);
2322 for (unsigned i(0); i != count; ++i) {
2323 vm_range_t &range(ranges[i]);
2324 void *data(reinterpret_cast<void *>(range.address));
2325 size_t size(range.size);
2327 if (size < sizeof(CYObjectStruct))
2330 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2331 #if defined(__APPLE__) && defined(__LP64__)
2332 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2334 Class isa(reinterpret_cast<Class>(pointers[0]));
2337 std::set<Class>::const_iterator result(choice->query_.find(isa));
2338 if (result == choice->query_.end())
2341 size_t needed(class_getInstanceSize(*result));
2342 // XXX: if (size < needed)
2344 size_t boundary(496);
2348 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2350 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2354 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2356 throw CYJSError(context, "choose() takes a class argument");
2358 CYGarbageCollect(context);
2361 id _class(CYCastNSObject(&pool, context, arguments[0]));
2363 vm_address_t *zones(NULL);
2365 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2366 _assert(error == KERN_SUCCESS);
2368 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2369 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2372 choice.context_ = context;
2373 choice.results_ = results;
2376 Class *classes(CYCopyClassList(number));
2377 _assert(classes != NULL);
2378 pool.atexit(free, classes);
2380 for (size_t i(0); i != number; ++i)
2381 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2382 if (current == _class) {
2383 choice.query_.insert(classes[i]);
2387 for (unsigned i(0); i != size; ++i) {
2388 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2389 if (zone == NULL || zone->introspect == NULL)
2392 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2400 #if defined(__i386__) || defined(__x86_64__)
2401 #define OBJC_MAX_STRUCT_BY_VALUE 8
2402 static int struct_forward_array[] = {
2403 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2404 #elif defined(__arm__)
2405 #define OBJC_MAX_STRUCT_BY_VALUE 1
2406 static int struct_forward_array[] = {
2408 #elif defined(__arm64__)
2411 #error missing objc-runtime-info
2415 static bool stret(ffi_type *ffi_type) {
2416 return ffi_type->type == FFI_TYPE_STRUCT && (
2417 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2418 struct_forward_array[ffi_type->size] != 0
2426 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2430 _class = object_getClass(self);
2434 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2435 imp = method_getImplementation(method);
2436 type = method_getTypeEncoding(method);
2441 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2442 type = CYPoolCString(pool, context, [method _typeString]);
2448 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2455 sig::Signature signature;
2456 sig::Parse(pool, &signature, type, &Structor_);
2459 sig::sig_ffi_cif(pool, 0, signature, &cif);
2463 if (stret(cif.rtype))
2464 imp = class_getMethodImplementation_stret(_class, _cmd);
2467 imp = class_getMethodImplementation(_class, _cmd);
2470 void (*function)() = reinterpret_cast<void (*)()>(imp);
2471 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, true, signature, &cif, function);
2474 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2476 throw CYJSError(context, "too few arguments to objc_msgSend");
2486 if (JSValueIsObjectOfClass(context, arguments[0], CYPrivate<cy::Super>::Class_)) {
2487 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2488 self = internal->value_;
2489 _class = internal->class_;;
2490 uninitialized = false;
2491 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2492 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2493 self = internal->value_;
2495 uninitialized = internal->IsUninitialized();
2496 if (uninitialized && [internal->value_ retainCount] != NSUInteger(-1))
2497 internal->value_ = nil;
2499 self = CYCastNSObject(&pool, context, arguments[0]);
2501 uninitialized = false;
2505 return CYJSNull(context);
2507 _cmd = CYCastSEL(context, arguments[1]);
2509 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2512 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2513 return $objc_msgSend(context, object, _this, count, arguments);
2516 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2517 JSValueRef setup[count + 2];
2520 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2521 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2524 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2526 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2528 // XXX: handle Instance::Uninitialized?
2529 id self(CYCastNSObject(&pool, context, _this));
2533 setup[1] = &internal->sel_;
2535 return CYCallFunction(pool, context, 2, setup, count, arguments, false, true, internal->signature_, &internal->cif_, internal->value_);
2538 CYPropertyName *Message_privateData::GetName(CYPool &pool) const {
2539 return new(pool) CYString(pool.strcat(":", sel_getName(sel_), NULL));
2542 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2544 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2546 id self(CYCastNSObject(&pool, context, arguments[0]));
2547 Class _class(CYCastClass(pool, context, arguments[1]));
2548 return CYPrivate<cy::Super>::Make(context, self, _class);
2551 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2553 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2555 const char *name(CYPoolCString(pool, context, arguments[0]));
2556 return CYPrivate<Selector_privateData>::Make(context, sel_registerName(name));
2559 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2561 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2562 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2565 static JSValueRef Selector_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2566 return CYMakeType(context, sig::Selector());
2569 static JSValueRef Instance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2570 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2571 id self(internal->value_);
2572 return CYMakeType(context, sig::Object(class_getName(object_getClass(self))));
2575 static JSValueRef FunctionInstance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2576 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2579 if (!CYBlockSignature(pool, internal->value_, type.signature))
2580 return CYJSNull(context);
2581 return CYMakeType(context, type);
2584 static JSValueRef Constructor_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2585 return CYMakeType(context, sig::Meta());
2588 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2589 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2590 return CYMakeInstance(context, object_getClass(internal->value_), Instance::Permanent);
2593 static JSValueRef Constructor_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2594 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2595 id self(internal->value_);
2596 return CYPrivate<Messages>::Cache(context, self);
2599 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2600 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2602 if (!CYJSValueIsNSObject(context, _this))
2605 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2606 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->value_, false, objects)));
2609 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2610 if (!CYJSValueIsNSObject(context, _this))
2613 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2614 id value(internal->value_);
2621 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2623 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2624 return CYJSUndefined(context);
2625 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2628 return CYCastJSValue(context, CYJSString(context, [value description]));
2630 } CYCatch(NULL) return /*XXX*/ NULL; }
2632 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2633 if (!CYJSValueIsNSObject(context, _this))
2636 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2637 id value(internal->value_);
2638 _assert(value != nil);
2640 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2643 if (JSValueRef result = [value cy$valueOfInContext:context])
2647 } CYCatch(NULL) return /*XXX*/ NULL; }
2649 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2650 if (!CYJSValueIsNSObject(context, _this))
2652 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2653 // XXX: return CYMakePointer(context, internal->value_, sig::Object(class_getName(object_getClass(internal->value_))), NULL, object);
2654 // XXX: return CYMakePointer(context, internal->value_, sig::Meta(), NULL, object);
2655 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2656 } CYCatch(NULL) return /*XXX*/ NULL; }
2658 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2659 if (!CYJSValueIsNSObject(context, _this))
2662 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2663 id value(internal->value_);
2666 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2667 return CYCastJSValue(context, CYJSString(context, [value description]));
2669 } CYCatch(NULL) return /*XXX*/ NULL; }
2671 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2672 if (!CYJSValueIsNSObject(context, _this))
2675 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2676 id value(internal->value_);
2678 if (!CYIsClass(value))
2679 CYThrow("non-Class object cannot be used as Type");
2681 sig::Object type(class_getName(value));
2682 return CYMakeType(context, type);
2683 } CYCatch(NULL) return /*XXX*/ NULL; }
2685 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2686 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2687 return CYCastJSValue(context, sel_getName(internal->value_));
2690 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2691 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2694 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2695 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2696 const char *name(sel_getName(internal->value_));
2699 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2700 return CYCastJSValue(context, CYJSString(context, string));
2702 } CYCatch(NULL) return /*XXX*/ NULL; }
2704 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2706 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2709 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2710 SEL sel(internal->value_);
2712 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2713 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2714 const char *encoding(method_getTypeEncoding(method));
2716 sig::Function type(false);
2717 sig::Parse(pool, &type.signature, encoding, &Structor_);
2718 return CYMakeType(context, type);
2721 static JSStaticValue Selector_staticValues[2] = {
2722 {"$cyt", &Selector_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2723 {NULL, NULL, NULL, 0}
2726 static JSStaticValue Instance_staticValues[3] = {
2727 {"$cyt", &Instance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2728 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2729 {NULL, NULL, NULL, 0}
2732 static JSStaticValue Block_staticValues[3] = {
2733 {"$cyt", &FunctionInstance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2734 {NULL, NULL, NULL, 0}
2737 static JSStaticFunction Instance_staticFunctions[7] = {
2738 {"cy$complete", &Instance_complete_callAsFunction, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2742 static JSStaticFunction Prototype_staticFunctions[6] = {
2743 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2744 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2745 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2746 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2747 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2751 static JSStaticFunction Messages_staticFunctions[2] = {
2752 {"cy$complete", &Messages_complete_callAsFunction, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2756 static JSStaticValue Constructor_staticValues[3] = {
2757 {"$cyt", &Constructor_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2758 {"prototype", &Constructor_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2759 {NULL, NULL, NULL, 0}
2762 static JSStaticFunction Constructor_staticFunctions[2] = {
2763 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2767 static JSStaticFunction Interior_staticFunctions[2] = {
2768 {"$cya", &Interior_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2772 static JSStaticFunction Selector_staticFunctions[5] = {
2773 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2774 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2775 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2776 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2781 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2782 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2783 } CYObjectiveCatch }
2786 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2787 NSArray_ = objc_getClass("NSArray");
2788 NSBlock_ = objc_getClass("NSBlock");
2789 NSDictionary_ = objc_getClass("NSDictionary");
2790 NSNumber_ = objc_getClass("NSNumber");
2791 NSObject_ = objc_getClass("NSObject");
2792 NSString_ = objc_getClass("NSString");
2793 Object_ = objc_getClass("Object");
2796 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2798 // XXX: apparently, iOS now has both of these
2799 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2800 if (NSCFBoolean_ == nil)
2801 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2803 NSCFType_ = objc_getClass("NSCFType");
2805 NSZombie_ = objc_getClass("_NSZombie_");
2807 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2808 NSZombie_ = objc_getClass("NSZombie");
2811 JSClassDefinition definition;
2813 definition = kJSClassDefinitionEmpty;
2814 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2815 definition.className = "Messages";
2816 definition.staticFunctions = Messages_staticFunctions;
2817 definition.hasProperty = &Messages_hasProperty;
2818 definition.getProperty = &Messages_getProperty;
2819 definition.setProperty = &Messages_setProperty;
2820 CYPrivate<Messages>::Class_ = JSClassCreate(&definition);
2822 definition = kJSClassDefinitionEmpty;
2823 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2824 definition.className = "Instance";
2825 definition.staticValues = Instance_staticValues;
2826 definition.staticFunctions = Instance_staticFunctions;
2827 definition.hasProperty = &Instance_hasProperty;
2828 definition.getProperty = &Instance_getProperty;
2829 definition.setProperty = &Instance_setProperty;
2830 definition.deleteProperty = &Instance_deleteProperty;
2831 definition.getPropertyNames = &Instance_getPropertyNames;
2832 definition.finalize = &CYFinalize;
2833 CYPrivate<Instance>::Class_ = JSClassCreate(&definition);
2835 definition = kJSClassDefinitionEmpty;
2836 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2837 definition.className = "Block";
2838 definition.parentClass = CYPrivate<Instance>::Class_;
2839 definition.staticValues = Block_staticValues;
2840 definition.callAsFunction = &Block_callAsFunction;
2841 CYPrivate<Block>::Class_ = JSClassCreate(&definition);
2843 definition = kJSClassDefinitionEmpty;
2844 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2845 definition.className = "Constructor";
2846 definition.parentClass = CYPrivate<Instance>::Class_;
2847 definition.staticValues = Constructor_staticValues;
2848 definition.staticFunctions = Constructor_staticFunctions;
2849 definition.hasInstance = &Constructor_hasInstance;
2850 definition.callAsConstructor = &Constructor_callAsConstructor;
2851 CYPrivate<Constructor>::Class_ = JSClassCreate(&definition);
2853 definition = kJSClassDefinitionEmpty;
2854 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2855 definition.className = "Interior";
2856 definition.staticFunctions = Interior_staticFunctions;
2857 definition.hasProperty = &Interior_hasProperty;
2858 definition.getProperty = &Interior_getProperty;
2859 definition.setProperty = &Interior_setProperty;
2860 definition.getPropertyNames = &Interior_getPropertyNames;
2861 definition.finalize = &CYFinalize;
2862 CYPrivate<Interior>::Class_ = JSClassCreate(&definition);
2864 definition = kJSClassDefinitionEmpty;
2865 definition.className = "Message";
2866 definition.parentClass = cy::Functor::Class_;
2867 definition.callAsFunction = &Message_callAsFunction;
2868 definition.finalize = &CYFinalize;
2869 Message_privateData::Class_ = JSClassCreate(&definition);
2871 definition = kJSClassDefinitionEmpty;
2872 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2873 definition.className = "Prototype";
2874 definition.staticFunctions = Prototype_staticFunctions;
2875 definition.finalize = &CYFinalize;
2876 CYPrivate<Prototype>::Class_ = JSClassCreate(&definition);
2878 definition = kJSClassDefinitionEmpty;
2879 definition.className = "Selector";
2880 definition.staticValues = Selector_staticValues;
2881 definition.staticFunctions = Selector_staticFunctions;
2882 definition.callAsFunction = &Selector_callAsFunction;
2883 definition.finalize = &CYFinalize;
2884 CYPrivate<Selector_privateData>::Class_ = JSClassCreate(&definition);
2886 definition = kJSClassDefinitionEmpty;
2887 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2888 definition.className = "Super";
2889 definition.finalize = &CYFinalize;
2890 CYPrivate<cy::Super>::Class_ = JSClassCreate(&definition);
2892 definition = kJSClassDefinitionEmpty;
2893 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2894 definition.className = "ObjectiveC::Classes";
2895 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2896 definition.getProperty = &ObjectiveC_Classes_getProperty;
2897 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2898 ObjectiveC_Classes_ = JSClassCreate(&definition);
2900 definition = kJSClassDefinitionEmpty;
2901 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2902 definition.className = "ObjectiveC::Constants";
2903 definition.getProperty = &ObjectiveC_Constants_getProperty;
2904 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2905 ObjectiveC_Constants_ = JSClassCreate(&definition);
2908 definition = kJSClassDefinitionEmpty;
2909 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2910 definition.className = "ObjectiveC::Images";
2911 definition.getProperty = &ObjectiveC_Images_getProperty;
2912 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2913 ObjectiveC_Images_ = JSClassCreate(&definition);
2915 definition = kJSClassDefinitionEmpty;
2916 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2917 definition.className = "ObjectiveC::Image::Classes";
2918 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2919 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2920 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2923 definition = kJSClassDefinitionEmpty;
2924 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
2925 definition.className = "ObjectiveC::Protocols";
2926 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2927 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2928 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2931 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2932 // XXX: this is horrible; there has to be a better way to do this
2934 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2936 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2942 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2943 JSObjectRef global(CYGetGlobalObject(context));
2944 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2945 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2946 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2947 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2949 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2950 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2952 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2953 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2954 CYArrayPush(context, alls, protocols);
2956 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2957 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2958 CYArrayPush(context, alls, classes);
2960 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2961 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2962 CYArrayPush(context, alls, constants);
2965 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2968 JSObjectRef Message(JSObjectMakeConstructor(context, Message_privateData::Class_, NULL));
2969 JSObjectRef Selector(JSObjectMakeConstructor(context, CYPrivate<Selector_privateData>::Class_, &Selector_new));
2970 JSObjectRef Super(JSObjectMakeConstructor(context, CYPrivate<cy::Super>::Class_, &Super_new));
2972 JSObjectRef Instance(JSObjectMakeConstructor(context, CYPrivate<::Instance>::Class_, &Instance_new));
2973 JSObjectRef Instance_prototype(JSObjectMake(context, CYPrivate<Prototype>::Class_, NULL));
2974 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2975 CYSetProperty(context, Instance, prototype_s, Instance_prototype);
2977 JSObjectRef ArrayInstance_prototype(JSObjectMake(context, CYPrivate<Prototype>::Class_, NULL));
2978 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2979 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2980 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2982 JSObjectRef BooleanInstance_prototype(JSObjectMake(context, CYPrivate<Prototype>::Class_, NULL));
2983 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2984 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2985 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2987 JSObjectRef FunctionInstance_prototype(JSObjectMake(context, CYPrivate<Prototype>::Class_, NULL));
2988 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2989 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2990 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2992 JSObjectRef NumberInstance_prototype(JSObjectMake(context, CYPrivate<Prototype>::Class_, NULL));
2993 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2994 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2995 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2997 JSObjectRef ObjectInstance_prototype(JSObjectMake(context, CYPrivate<Prototype>::Class_, NULL));
2998 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2999 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3000 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3002 JSObjectRef StringInstance_prototype(JSObjectMake(context, CYPrivate<Prototype>::Class_, NULL));
3003 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3004 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3005 CYSetPrototype(context, StringInstance_prototype, String_prototype);
3007 JSObjectRef TypeInstance_prototype(JSObjectMake(context, CYPrivate<Prototype>::Class_, NULL));
3008 CYSetProperty(context, cy, CYJSString("TypeInstance_prototype"), TypeInstance_prototype);
3009 // XXX: maybe TypeInstance should have Type as its prototype? FWIW, that's why I named it like this ;P
3011 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3012 CYSetProperty(context, cycript, CYJSString("Message"), Message);
3013 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3014 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3016 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3017 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3020 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3023 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3025 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3026 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3028 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
3029 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
3030 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
3031 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::Object()), kJSPropertyAttributeDontEnum);
3032 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::Meta()), kJSPropertyAttributeDontEnum);
3033 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::Selector()), kJSPropertyAttributeDontEnum);
3035 CYSetProperty(context, cy, CYJSString("cydget"), CYCastJSValue(context, false));
3038 static void *CYObjectiveC_CastSymbol(const char *name) {
3040 #ifdef __GNU_LIBOBJC__
3041 else if (strcmp(name, "object_getClass") == 0)
3042 return reinterpret_cast<void *>(&object_getClass);
3047 static CYHook CYObjectiveCHook = {
3048 &CYObjectiveC_ExecuteStart,
3049 &CYObjectiveC_ExecuteEnd,
3050 &CYObjectiveC_CallFunction,
3051 &CYObjectiveC_Initialize,
3052 &CYObjectiveC_SetupContext,
3053 &CYObjectiveC_CastSymbol,
3056 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3058 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3059 CYSetupContext(context);
3060 JSObjectRef global(CYGetGlobalObject(context));
3061 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
3062 CYSetProperty(context, cy, CYJSString("cydget"), CYCastJSValue(context, true));
3063 } CYObjectiveCatch }
3065 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3068 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3069 utf8 = CYPoolCode(pool, utf8);
3071 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3072 size_t bytes(utf16.size * sizeof(uint16_t));
3073 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3074 memcpy(copy, utf16.data, bytes);
3078 } catch (const CYException &exception) {
3080 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];