1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2014 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 <Foundation/Foundation.h>
24 #include "ObjectiveC/Internal.hpp"
26 #include <objc/objc-api.h>
28 #include "cycript.hpp"
30 #include "ObjectiveC/Internal.hpp"
33 #include <CoreFoundation/CoreFoundation.h>
34 #include <JavaScriptCore/JSStringRefCF.h>
35 #include <objc/runtime.h>
39 #include <malloc/malloc.h>
40 #include <mach/mach.h>
45 #include "JavaScript.hpp"
47 #include "Execute.hpp"
55 #define CYObjectiveTry_ { \
57 #define CYObjectiveTry { \
58 JSContextRef context(context_); \
60 #define CYObjectiveCatch \
61 catch (const CYException &error) { \
62 @throw CYCastNSObject(NULL, context, error.CastJSValue(context)); \
68 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
70 #define CYPoolCatch(value) \
71 @catch (NSException *error) { \
72 _saved = [error retain]; \
73 throw CYJSError(context, CYCastJSValue(context, error)); \
78 [_saved autorelease]; \
84 #define CYSadCatch(value) \
85 @catch (NSException *error ) { \
86 throw CYJSError(context, CYCastJSValue(context, error)); \
90 #define _oassert(test) \
92 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"_assert(" #test ")" userInfo:nil];
95 #define class_getSuperclass GSObjCSuper
96 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
97 #define class_getName GSNameFromClass
99 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
101 #define ivar_getName(ivar) ((ivar)->ivar_name)
102 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
103 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
105 #define method_getName(method) ((method)->method_name)
106 #define method_getImplementation(method) ((method)->method_imp)
107 #define method_getTypeEncoding(method) ((method)->method_types)
108 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
111 #define objc_getClass GSClassFromName
113 #define objc_getProtocol GSProtocolFromName
115 #define object_getClass GSObjCClass
117 #define object_getInstanceVariable(object, name, value) ({ \
118 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
119 _assert(value != NULL); \
121 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
125 #define object_setIvar(object, ivar, value) ({ \
126 void *data = (value); \
127 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
130 #define protocol_getName(protocol) [(protocol) name]
135 struct BlockLiteral {
139 void (*invoke)(void *, ...);
143 struct BlockDescriptor1 {
144 unsigned long int reserved;
145 unsigned long int size;
148 struct BlockDescriptor2 {
149 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
150 void (*dispose_helper)(BlockLiteral *src);
153 struct BlockDescriptor3 {
154 const char *signature;
159 BLOCK_DEALLOCATING = 0x0001,
160 BLOCK_REFCOUNT_MASK = 0xfffe,
161 BLOCK_NEEDS_FREE = 1 << 24,
162 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
163 BLOCK_HAS_CTOR = 1 << 26,
164 BLOCK_IS_GC = 1 << 27,
165 BLOCK_IS_GLOBAL = 1 << 28,
166 BLOCK_HAS_STRET = 1 << 29,
167 BLOCK_HAS_SIGNATURE = 1 << 30,
170 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
172 /* Objective-C Pool Release {{{ */
173 void CYPoolRelease_(void *data) {
174 id object(reinterpret_cast<id>(data));
178 id CYPoolRelease_(CYPool *pool, id object) {
181 else if (pool == NULL)
182 return [object autorelease];
184 pool->atexit(CYPoolRelease_);
189 template <typename Type_>
190 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
191 return (Type_) CYPoolRelease_(pool, (id) object);
194 /* Objective-C Strings {{{ */
195 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
196 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
197 char *string(new(pool) char[size]);
198 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
199 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
203 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
205 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
208 return CYCopyJSString(CYPoolCString(pool, context, value));
212 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
215 // XXX: this definition scares me; is anyone using this?!
216 NSString *string([value description]);
217 return CYCopyJSString(context, string);
220 NSString *CYCopyNSString(const CYUTF8String &value) {
222 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
224 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
228 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
230 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
233 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
237 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
238 return CYCopyNSString(context, CYJSString(context, value));
241 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
242 return CYPoolRelease(pool, CYCopyNSString(value));
245 NSString *CYCastNSString(CYPool *pool, SEL sel) {
246 const char *name(sel_getName(sel));
247 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
250 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
251 return CYPoolRelease(pool, CYCopyNSString(context, value));
254 CYUTF8String CYCastUTF8String(NSString *value) {
255 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
256 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
260 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
262 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
263 if (exception == NULL)
265 *exception = CYCastJSValue(context, error);
268 size_t CYGetIndex(NSString *value) {
269 return CYGetIndex(CYCastUTF8String(value));
272 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
273 return CYGetOffset(CYPoolCString(pool, context, value), index);
276 static JSClassRef Instance_;
278 static JSClassRef ArrayInstance_;
279 static JSClassRef BooleanInstance_;
280 static JSClassRef FunctionInstance_;
281 static JSClassRef NumberInstance_;
282 static JSClassRef ObjectInstance_;
283 static JSClassRef StringInstance_;
285 static JSClassRef Class_;
286 static JSClassRef Internal_;
287 static JSClassRef Message_;
288 static JSClassRef Messages_;
289 static JSClassRef Selector_;
290 static JSClassRef Super_;
292 static JSClassRef ObjectiveC_Classes_;
293 static JSClassRef ObjectiveC_Constants_;
294 static JSClassRef ObjectiveC_Protocols_;
297 static JSClassRef ObjectiveC_Image_Classes_;
298 static JSClassRef ObjectiveC_Images_;
302 static Class __NSMallocBlock__;
303 static Class NSCFBoolean_;
304 static Class NSCFType_;
305 static Class NSGenericDeallocHandler_;
306 static Class NSZombie_;
308 static Class NSBoolNumber_;
311 static Class NSArray_;
312 static Class NSBlock_;
313 static Class NSDictionary_;
314 static Class NSNumber_;
315 static Class NSString_;
316 static Class Object_;
318 static Type_privateData *Object_type;
319 static Type_privateData *Selector_type;
321 Type_privateData *Instance::GetType() const {
325 Type_privateData *Selector_privateData::GetType() const {
326 return Selector_type;
329 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
331 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
333 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
334 else if (meta && !class_isMetaClass(self))
335 return CYGetCachedObject(context, CYJSString("Class_prototype"));
337 JSObjectRef global(CYGetGlobalObject(context));
338 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
341 sprintf(label, "i%p", self);
342 CYJSString name(label);
344 JSValueRef value(CYGetProperty(context, cy, name));
345 if (!JSValueIsUndefined(context, value))
348 JSClassRef _class(NULL);
349 JSValueRef prototype;
352 if (self == NSCFBoolean_)
354 if (self == NSBoolNumber_)
356 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
357 else if (self == NSArray_)
358 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
359 else if (self == NSBlock_)
360 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
361 else if (self == NSNumber_)
362 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
363 else if (self == NSDictionary_)
364 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
365 else if (self == NSString_)
366 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
368 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
370 JSObjectRef object(JSObjectMake(context, _class, NULL));
371 CYSetPrototype(context, object, prototype);
372 CYSetProperty(context, cy, name, object);
377 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
378 return CYGetClassPrototype(context, self, class_isMetaClass(self));
381 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
382 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
383 if (Class super = class_getSuperclass(_class))
384 CYSetPrototype(context, value, Messages::Make(context, super));
388 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
389 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
393 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
394 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
398 bool CYIsKindOfClass(id object, Class _class) {
399 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
405 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
406 JSObjectRef value(JSObjectMake(context, CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance_, new Instance(object, flags)));
407 CYSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
411 Instance::~Instance() {
412 if ((flags_ & Permanent) == 0)
413 [GetValue() release];
416 struct Message_privateData :
421 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
422 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
428 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool permanent) {
429 Instance::Flags flags;
432 flags = Instance::Permanent;
434 flags = Instance::None;
435 object = [object retain];
438 return Instance::Make(context, object, flags);
441 @interface NSMethodSignature (Cycript)
442 - (NSString *) _typeString;
445 @interface NSObject (Cycript)
447 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
448 - (JSType) cy$JSType;
450 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
451 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
453 - (bool) cy$hasProperty:(NSString *)name;
454 - (NSObject *) cy$getProperty:(NSString *)name;
455 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
456 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
457 - (bool) cy$deleteProperty:(NSString *)name;
458 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
460 + (bool) cy$hasImplicitProperties;
466 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
469 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
475 Class _class(object_getClass(value));
476 SEL sel(@selector(cy$toCYON:inSet:));
478 if (class_isMetaClass(_class)) {
479 const char *name(class_getName(value));
480 if (class_isMetaClass(value))
481 string = [NSString stringWithFormat:@"object_getClass(%s)", name];
483 string = [NSString stringWithUTF8String:name];
484 } else if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
485 string = reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
486 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
487 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
488 string = [value cy$toCYON:objective inSet:objects];
493 else if (_class == NSZombie_)
494 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
497 string = [NSString stringWithFormat:@"%@", value];
502 string = @"undefined";
508 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
510 return CYCastNSCYON(value, objective, *objects);
512 std::set<void *> objects;
513 return CYCastNSCYON(value, objective, objects);
518 struct PropertyAttributes {
523 const char *variable;
536 PropertyAttributes(objc_property_t property) :
548 name = property_getName(property);
549 const char *attributes(property_getAttributes(property));
551 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
552 if ((next = strchr(token, ',')) != NULL)
555 case 'R': readonly = true; break;
556 case 'C': copy = true; break;
557 case '&': retain = true; break;
558 case 'N': nonatomic = true; break;
559 case 'G': getter_ = token + 1; break;
560 case 'S': setter_ = token + 1; break;
561 case 'V': variable = token + 1; break;
565 /*if (variable == NULL) {
566 variable = property_getName(property);
567 size_t size(strlen(variable));
568 char *name(new(pool_) char[size + 2]);
570 memcpy(name + 1, variable, size);
571 name[size + 1] = '\0';
576 const char *Getter() {
578 getter_ = pool_.strdup(name);
582 const char *Setter() {
583 if (setter_ == NULL && !readonly) {
584 size_t length(strlen(name));
586 char *temp(new(pool_) char[length + 5]);
592 temp[3] = toupper(name[0]);
593 memcpy(temp + 4, name + 1, length - 1);
596 temp[length + 3] = ':';
597 temp[length + 4] = '\0';
607 @interface CYWebUndefined : NSObject {
610 + (CYWebUndefined *) undefined;
614 @implementation CYWebUndefined
616 + (CYWebUndefined *) undefined {
617 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
623 #define WebUndefined CYWebUndefined
625 /* Bridge: CYJSObject {{{ */
626 @interface CYJSObject : NSMutableDictionary {
628 JSGlobalContextRef context_;
631 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
633 - (NSUInteger) count;
634 - (id) objectForKey:(id)key;
635 - (NSEnumerator *) keyEnumerator;
636 - (void) setObject:(id)object forKey:(id)key;
637 - (void) removeObjectForKey:(id)key;
641 /* Bridge: CYJSArray {{{ */
642 @interface CYJSArray : NSMutableArray {
644 JSGlobalContextRef context_;
647 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
649 - (NSUInteger) count;
650 - (id) objectAtIndex:(NSUInteger)index;
652 - (void) addObject:(id)anObject;
653 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
654 - (void) removeLastObject;
655 - (void) removeObjectAtIndex:(NSUInteger)index;
656 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
661 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
662 return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
665 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
666 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
669 struct CYBlockDescriptor {
671 BlockDescriptor1 one_;
672 BlockDescriptor2 two_;
673 BlockDescriptor3 three_;
676 Closure_privateData *internal_;
679 void CYDisposeBlock(BlockLiteral *literal) {
680 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
683 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
684 JSObjectRef _this(CYCastJSObject(context, values[0]));
685 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
688 static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
689 CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
692 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
693 _assert(__NSMallocBlock__ != Nil);
694 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
696 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
697 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
699 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
700 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
702 literal->isa = __NSMallocBlock__;
703 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
704 literal->reserved = 0;
705 literal->descriptor = descriptor;
707 descriptor->d_.one_.size = sizeof(descriptor->d_);
708 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
709 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
711 return reinterpret_cast<NSBlock *>(literal);
714 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
715 if (CYJSValueIsNSObject(context, object)) {
716 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
717 return internal->GetValue();
720 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
721 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
722 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
725 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
726 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
730 @interface NSBoolNumber : NSNumber {
735 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
739 switch (JSType type = JSValueGetType(context, value)) {
740 case kJSTypeUndefined:
741 object = [WebUndefined undefined];
751 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
754 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
760 object = CYCopyNSNumber(context, value);
765 object = CYCopyNSString(context, value);
770 // XXX: this might could be more efficient
771 object = CYCastNSObject(pool, context, (JSObjectRef) value);
776 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
783 return CYPoolRelease(pool, object);
785 return [object retain];
788 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
789 return CYNSObject(pool, context, value, true);
792 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
793 return CYNSObject(&pool, context, value, false);
796 /* Bridge: NSArray {{{ */
797 @implementation NSArray (Cycript)
800 return [[self mutableCopy] autorelease];
803 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
804 _oassert(objects.insert(self).second);
806 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
807 [json appendString:@"@["];
811 for (id object in self) {
813 for (size_t index(0), count([self count]); index != count; ++index) {
814 id object([self objectAtIndex:index]);
817 [json appendString:@","];
820 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
821 [json appendString:CYCastNSCYON(object, true, objects)];
823 [json appendString:@","];
828 [json appendString:@"]"];
832 - (bool) cy$hasProperty:(NSString *)name {
833 if ([name isEqualToString:@"length"])
836 size_t index(CYGetIndex(name));
837 if (index == _not(size_t) || index >= [self count])
838 return [super cy$hasProperty:name];
843 - (NSObject *) cy$getProperty:(NSString *)name {
844 size_t index(CYGetIndex(name));
845 if (index == _not(size_t) || index >= [self count])
846 return [super cy$getProperty:name];
848 return [self objectAtIndex:index];
851 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
853 if ([name isEqualToString:@"length"])
854 return CYCastJSValue(context, [self count]);
857 return [super cy$getProperty:name inContext:context];
860 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
861 [super cy$getPropertyNames:names inContext:context];
863 for (size_t index(0), count([self count]); index != count; ++index) {
864 id object([self objectAtIndex:index]);
865 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
867 sprintf(name, "%zu", index);
868 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
873 + (bool) cy$hasImplicitProperties {
879 /* Bridge: NSBlock {{{ */
886 /* Bridge: NSBoolNumber {{{ */
888 @implementation NSBoolNumber (Cycript)
890 - (JSType) cy$JSType {
891 return kJSTypeBoolean;
894 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
895 NSString *value([self boolValue] ? @"true" : @"false");
896 return objective ? value : [NSString stringWithFormat:@"@%@", value];
899 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
900 return CYCastJSValue(context, (bool) [self boolValue]);
906 /* Bridge: NSDictionary {{{ */
907 @implementation NSDictionary (Cycript)
910 return [[self mutableCopy] autorelease];
913 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
914 _oassert(objects.insert(self).second);
916 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
917 [json appendString:@"@{"];
921 for (NSObject *key in self) {
923 NSEnumerator *keys([self keyEnumerator]);
924 while (NSObject *key = [keys nextObject]) {
927 [json appendString:@","];
930 [json appendString:CYCastNSCYON(key, true, objects)];
931 [json appendString:@":"];
932 NSObject *object([self objectForKey:key]);
933 [json appendString:CYCastNSCYON(object, true, objects)];
936 [json appendString:@"}"];
940 - (bool) cy$hasProperty:(NSString *)name {
941 return [self objectForKey:name] != nil;
944 - (NSObject *) cy$getProperty:(NSString *)name {
945 return [self objectForKey:name];
948 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
949 [super cy$getPropertyNames:names inContext:context];
952 for (NSObject *key in self) {
954 NSEnumerator *keys([self keyEnumerator]);
955 while (NSObject *key = [keys nextObject]) {
957 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
961 + (bool) cy$hasImplicitProperties {
967 /* Bridge: NSMutableArray {{{ */
968 @implementation NSMutableArray (Cycript)
970 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
971 if ([name isEqualToString:@"length"]) {
972 // XXX: is this not intelligent?
973 NSNumber *number(reinterpret_cast<NSNumber *>(value));
975 NSUInteger size([number unsignedIntegerValue]);
977 NSUInteger size([number unsignedIntValue]);
979 NSUInteger count([self count]);
981 [self removeObjectsInRange:NSMakeRange(size, count - size)];
982 else if (size != count) {
983 WebUndefined *undefined([WebUndefined undefined]);
984 for (size_t i(count); i != size; ++i)
985 [self addObject:undefined];
990 size_t index(CYGetIndex(name));
991 if (index == _not(size_t))
992 return [super cy$setProperty:name to:value];
994 id object(value ?: [NSNull null]);
996 size_t count([self count]);
998 [self replaceObjectAtIndex:index withObject:object];
1000 if (index != count) {
1001 WebUndefined *undefined([WebUndefined undefined]);
1002 for (size_t i(count); i != index; ++i)
1003 [self addObject:undefined];
1006 [self addObject:object];
1012 - (bool) cy$deleteProperty:(NSString *)name {
1013 size_t index(CYGetIndex(name));
1014 if (index == _not(size_t) || index >= [self count])
1015 return [super cy$deleteProperty:name];
1016 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1022 /* Bridge: NSMutableDictionary {{{ */
1023 @implementation NSMutableDictionary (Cycript)
1025 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1026 [self setObject:(value ?: [NSNull null]) forKey:name];
1030 - (bool) cy$deleteProperty:(NSString *)name {
1031 if ([self objectForKey:name] == nil)
1034 [self removeObjectForKey:name];
1041 /* Bridge: NSNumber {{{ */
1042 @implementation NSNumber (Cycript)
1044 - (JSType) cy$JSType {
1046 // XXX: this just seems stupid
1047 if ([self class] == NSCFBoolean_)
1048 return kJSTypeBoolean;
1050 return kJSTypeNumber;
1053 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1054 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1055 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1058 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1059 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1060 } CYObjectiveCatch }
1064 /* Bridge: NSNull {{{ */
1065 @implementation NSNull (Cycript)
1067 - (JSType) cy$JSType {
1071 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1072 NSString *value(@"null");
1073 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1076 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1077 return CYJSNull(context);
1078 } CYObjectiveCatch }
1082 /* Bridge: NSObject {{{ */
1083 @implementation NSObject (Cycript)
1089 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1090 return [self cy$valueOfInContext:context];
1093 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1095 } CYObjectiveCatch }
1097 - (JSType) cy$JSType {
1098 return kJSTypeObject;
1101 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1102 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1105 - (bool) cy$hasProperty:(NSString *)name {
1109 - (NSObject *) cy$getProperty:(NSString *)name {
1113 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1114 if (NSObject *value = [self cy$getProperty:name])
1115 return CYCastJSValue(context, value);
1117 } CYObjectiveCatch }
1119 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1123 - (bool) cy$deleteProperty:(NSString *)name {
1127 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1130 + (bool) cy$hasImplicitProperties {
1136 /* Bridge: NSProxy {{{ */
1137 @implementation NSProxy (Cycript)
1139 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1140 return [[self description] cy$toCYON:objective inSet:objects];
1145 /* Bridge: NSSet {{{ */
1146 @implementation NSSet (Cycript)
1148 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1149 _oassert(objects.insert(self).second);
1151 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1152 [json appendString:@"[NSSet setWithArray:"];
1153 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1154 [json appendString:@"]]"];
1160 /* Bridge: NSString {{{ */
1161 @implementation NSString (Cycript)
1164 return [[self copy] autorelease];
1167 - (JSType) cy$JSType {
1168 return kJSTypeString;
1171 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1172 std::ostringstream str;
1175 CYUTF8String string(CYCastUTF8String(self));
1176 CYStringify(str, string.data, string.size);
1177 std::string value(str.str());
1178 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1181 - (bool) cy$hasProperty:(NSString *)name {
1182 size_t index(CYGetIndex(name));
1183 if (index == _not(size_t) || index >= [self length])
1184 return [super cy$hasProperty:name];
1189 - (NSObject *) cy$getProperty:(NSString *)name {
1190 size_t index(CYGetIndex(name));
1191 if (index == _not(size_t) || index >= [self length])
1192 return [super cy$getProperty:name];
1194 return [self substringWithRange:NSMakeRange(index, 1)];
1197 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1198 [super cy$getPropertyNames:names inContext:context];
1200 for (size_t index(0), length([self length]); index != length; ++index) {
1202 sprintf(name, "%zu", index);
1203 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1207 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1208 return CYCastJSValue(context, CYJSString(context, self));
1209 } CYObjectiveCatch }
1213 /* Bridge: WebUndefined {{{ */
1214 @implementation WebUndefined (Cycript)
1216 - (JSType) cy$JSType {
1217 return kJSTypeUndefined;
1220 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1221 NSString *value(@"undefined");
1222 return value; // XXX: maybe use the below code, adding @undefined?
1223 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1226 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1227 return CYJSUndefined(context);
1228 } CYObjectiveCatch }
1233 static bool CYIsClass(id self) {
1235 return class_isMetaClass(object_getClass(self));
1237 return GSObjCIsClass(self);
1241 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1242 id self(CYCastNSObject(&pool, context, value));
1243 if (CYIsClass(self))
1244 return (Class) self;
1245 throw CYJSError(context, "got something that is not a Class");
1249 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1251 size_t size(JSPropertyNameArrayGetCount(names));
1252 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1253 for (size_t index(0); index != size; ++index)
1254 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1258 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1260 return CYJSNull(context);
1262 return CYMakeInstance(context, value, false);
1263 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1265 @implementation CYJSObject
1267 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1268 if ((self = [super init]) != nil) {
1270 context_ = CYGetJSContext(context);
1271 JSGlobalContextRetain(context_);
1272 JSValueProtect(context_, object_);
1274 } CYObjectiveCatch }
1276 - (void) dealloc { CYObjectiveTry {
1277 JSValueUnprotect(context_, object_);
1278 JSGlobalContextRelease(context_);
1280 } CYObjectiveCatch }
1282 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1284 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1286 return [super cy$toCYON:objective inSet:objects];
1288 return [NSString stringWithUTF8String:cyon];
1289 } CYObjectiveCatch }
1291 - (NSUInteger) count { CYObjectiveTry {
1292 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1293 size_t size(JSPropertyNameArrayGetCount(names));
1294 JSPropertyNameArrayRelease(names);
1296 } CYObjectiveCatch }
1298 - (id) objectForKey:(id)key { CYObjectiveTry {
1299 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1300 if (JSValueIsUndefined(context, value))
1302 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1303 } CYObjectiveCatch }
1305 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1306 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1307 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1308 JSPropertyNameArrayRelease(names);
1310 } CYObjectiveCatch }
1312 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1313 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1314 } CYObjectiveCatch }
1316 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1317 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1318 } CYObjectiveCatch }
1322 @implementation CYJSArray
1324 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1326 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1327 } CYObjectiveCatch }
1329 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1330 if ((self = [super init]) != nil) {
1332 context_ = CYGetJSContext(context);
1333 JSGlobalContextRetain(context_);
1334 JSValueProtect(context_, object_);
1336 } CYObjectiveCatch }
1338 - (void) dealloc { CYObjectiveTry {
1339 JSValueUnprotect(context_, object_);
1340 JSGlobalContextRelease(context_);
1342 } CYObjectiveCatch }
1344 - (NSUInteger) count { CYObjectiveTry {
1345 return CYArrayLength(context, object_);
1346 } CYObjectiveCatch }
1348 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1349 size_t bounds([self count]);
1350 if (index >= bounds)
1351 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1352 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1353 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1354 } CYObjectiveCatch }
1356 - (void) addObject:(id)object { CYObjectiveTry {
1357 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1358 } CYObjectiveCatch }
1360 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1361 size_t bounds([self count] + 1);
1362 if (index >= bounds)
1363 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1364 JSValueRef arguments[3];
1365 arguments[0] = CYCastJSValue(context, index);
1366 arguments[1] = CYCastJSValue(context, 0);
1367 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1368 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1369 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1370 } CYObjectiveCatch }
1372 - (void) removeLastObject { CYObjectiveTry {
1373 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1374 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1375 } CYObjectiveCatch }
1377 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1378 size_t bounds([self count]);
1379 if (index >= bounds)
1380 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1381 JSValueRef arguments[2];
1382 arguments[0] = CYCastJSValue(context, index);
1383 arguments[1] = CYCastJSValue(context, 1);
1384 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1385 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1386 } CYObjectiveCatch }
1388 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1389 size_t bounds([self count]);
1390 if (index >= bounds)
1391 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1392 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1393 } CYObjectiveCatch }
1397 // XXX: inherit from or replace with CYJSObject
1398 @interface CYInternal : NSObject {
1399 JSGlobalContextRef context_;
1400 JSObjectRef object_;
1405 @implementation CYInternal
1407 - (void) dealloc { CYObjectiveTry {
1408 JSValueUnprotect(context_, object_);
1409 JSGlobalContextRelease(context_);
1411 } CYObjectiveCatch }
1413 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1414 if ((self = [super init]) != nil) {
1415 context_ = CYGetJSContext(context);
1416 JSGlobalContextRetain(context_);
1418 } CYObjectiveCatch }
1420 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1421 if (object_ == NULL)
1424 return JSObjectHasProperty(context, object_, name);
1427 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1428 if (object_ == NULL)
1431 return CYGetProperty(context, object_, name);
1434 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1435 @synchronized (self) {
1436 if (object_ == NULL) {
1437 object_ = JSObjectMake(context, NULL, NULL);
1438 JSValueProtect(context, object_);
1442 CYSetProperty(context, object_, name, value);
1445 + (CYInternal *) get:(id)object {
1446 if (&objc_getAssociatedObject == NULL)
1449 @synchronized (object) {
1450 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1457 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1458 if (&objc_getAssociatedObject == NULL)
1461 @synchronized (object) {
1462 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1465 if (&objc_setAssociatedObject == NULL)
1468 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1469 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1478 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1479 Selector_privateData *internal(new Selector_privateData(sel));
1480 return JSObjectMake(context, Selector_, internal);
1483 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1484 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1485 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1486 return reinterpret_cast<SEL>(internal->value_);
1489 return sel_registerName(CYPoolCString(pool, context, value));
1493 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1494 return (void *) [[NSAutoreleasePool alloc] init];
1495 } CYSadCatch(NULL) }
1497 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1498 return [(NSAutoreleasePool *) handle release];
1501 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1502 ffi_call(cif, function, value, values);
1505 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, sig::Signature *signature) {
1506 if (JSValueIsNull(context, value))
1508 JSObjectRef object(CYCastJSObject(context, value));
1510 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1511 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1513 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1514 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1518 _assert(JSObjectIsFunction(context, object));
1520 _assert(signature != NULL);
1521 _assert(signature->count != 0);
1523 sig::Signature modified;
1524 modified.count = signature->count + 1;
1525 modified.elements = new(pool) sig::Element[modified.count];
1527 modified.elements[0] = signature->elements[0];
1528 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1530 modified.elements[1].name = NULL;
1531 modified.elements[1].type = new(pool) sig::Type();
1532 modified.elements[1].offset = _not(size_t);
1534 memset(modified.elements[1].type, 0, sizeof(sig::Type));
1535 modified.elements[1].type->primitive = sig::object_P;
1537 return CYMakeBlock(context, object, modified);
1540 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1541 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1543 switch (type->primitive) {
1545 // XXX: this function might not handle the idea of a null pool
1546 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &type->data.signature);
1550 case sig::typename_P:
1551 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1554 case sig::selector_P:
1555 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1563 } CYSadCatch(false) }
1565 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1566 switch (type->primitive) {
1567 // XXX: do something epic about blocks
1570 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1571 JSValueRef value(CYCastJSValue(context, object));
1577 case sig::typename_P:
1578 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1580 case sig::selector_P:
1581 if (SEL sel = *reinterpret_cast<SEL *>(data))
1582 return CYMakeSelector(context, sel);
1586 return CYJSNull(context);
1590 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1592 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1593 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1596 #if OBJC_API_VERSION >= 2
1598 method_getReturnType(method, type, sizeof(type));
1600 const char *type(method_getTypeEncoding(method));
1606 // XXX: possibly use a more "awesome" check?
1610 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1611 JSObjectRef _this(CYCastJSObject(context, values[0]));
1612 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1615 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1616 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1619 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1620 Message_privateData *internal(new Message_privateData(sel, type, imp));
1621 return JSObjectMake(context, Message_, internal);
1624 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1625 JSObjectRef function(CYCastJSObject(context, value));
1627 sig::Signature signature;
1628 sig::Parse(pool, &signature, encoding, &Structor_);
1629 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageClosure_));
1630 // XXX: see notes in Library.cpp about needing to leak
1631 return reinterpret_cast<IMP>(internal->GetValue());
1634 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1635 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1636 Class _class(internal->GetValue());
1639 const char *name(CYPoolCString(pool, context, property));
1641 if (SEL sel = sel_getUid(name))
1642 if (class_getInstanceMethod(_class, sel) != NULL)
1648 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1649 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1650 Class _class(internal->GetValue());
1653 const char *name(CYPoolCString(pool, context, property));
1655 if (SEL sel = sel_getUid(name))
1656 if (objc_method *method = class_getInstanceMethod(_class, sel))
1657 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1662 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1663 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1664 Class _class(internal->GetValue());
1667 const char *name(CYPoolCString(pool, context, property));
1668 SEL sel(sel_registerName(name));
1673 if (JSValueIsObjectOfClass(context, value, Message_)) {
1674 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1675 type = sig::Unparse(pool, &message->signature_);
1676 imp = reinterpret_cast<IMP>(message->GetValue());
1677 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1678 type = method_getTypeEncoding(method);
1679 imp = CYMakeMessage(context, value, type);
1680 } else _assert(false);
1682 objc_method *method(NULL);
1683 #if OBJC_API_VERSION >= 2
1685 objc_method **methods(class_copyMethodList(_class, &size));
1686 for (size_t i(0); i != size; ++i)
1687 if (sel_isEqual(method_getName(methods[i]), sel)) {
1688 method = methods[i];
1693 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1694 for (int i(0); i != methods->method_count; ++i)
1695 if (sel_isEqual(method_getName(&methods->method_list[i]), sel)) {
1696 method = &methods->method_list[i];
1702 method_setImplementation(method, imp);
1705 GSMethodList list(GSAllocMethodList(1));
1706 GSAppendMethodToList(list, sel, type, imp, YES);
1707 GSAddMethodList(_class, list, YES);
1708 GSFlushMethodCacheForClass(_class);
1710 class_addMethod(_class, sel, imp, type);
1717 #if 0 && OBJC_API_VERSION < 2
1718 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1719 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1720 Class _class(internal->GetValue());
1723 const char *name(CYPoolCString(pool, context, property));
1725 if (SEL sel = sel_getUid(name))
1726 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1727 objc_method_list list = {NULL, 1, {method}};
1728 class_removeMethods(_class, &list);
1736 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1737 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1738 Class _class(internal->GetValue());
1740 #if OBJC_API_VERSION >= 2
1742 objc_method **data(class_copyMethodList(_class, &size));
1743 for (size_t i(0); i != size; ++i)
1744 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1747 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1748 for (int i(0); i != methods->method_count; ++i)
1749 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1753 static bool CYHasImplicitProperties(Class _class) {
1754 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1755 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1757 return [_class cy$hasImplicitProperties];
1760 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1761 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1762 id self(internal->GetValue());
1764 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1768 NSString *name(CYCastNSString(&pool, context, property));
1770 if (CYInternal *internal = [CYInternal get:self])
1771 if ([internal hasProperty:property inContext:context])
1774 Class _class(object_getClass(self));
1777 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1778 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1779 if ([self cy$hasProperty:name])
1781 } CYPoolCatch(false)
1783 const char *string(CYPoolCString(pool, context, name));
1786 if (class_getProperty(_class, string) != NULL)
1790 if (CYHasImplicitProperties(_class))
1791 if (SEL sel = sel_getUid(string))
1792 if (CYImplements(self, _class, sel, true))
1798 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1799 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1800 id self(internal->GetValue());
1802 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1803 return Internal::Make(context, self, object);
1806 NSString *name(CYCastNSString(&pool, context, property));
1808 if (CYInternal *internal = [CYInternal get:self])
1809 if (JSValueRef value = [internal getProperty:property inContext:context])
1813 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1817 const char *string(CYPoolCString(pool, context, name));
1818 Class _class(object_getClass(self));
1821 if (objc_property_t property = class_getProperty(_class, string)) {
1822 PropertyAttributes attributes(property);
1823 SEL sel(sel_registerName(attributes.Getter()));
1824 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1828 if (CYHasImplicitProperties(_class))
1829 if (SEL sel = sel_getUid(string))
1830 if (CYImplements(self, _class, sel, true))
1831 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1836 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1837 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1838 id self(internal->GetValue());
1842 NSString *name(CYCastNSString(&pool, context, property));
1843 NSObject *data(CYCastNSObject(&pool, context, value));
1846 if ([self cy$setProperty:name to:data])
1848 } CYPoolCatch(false)
1850 const char *string(CYPoolCString(pool, context, name));
1851 Class _class(object_getClass(self));
1854 if (objc_property_t property = class_getProperty(_class, string)) {
1855 PropertyAttributes attributes(property);
1856 if (const char *setter = attributes.Setter()) {
1857 SEL sel(sel_registerName(setter));
1858 JSValueRef arguments[1] = {value};
1859 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1865 size_t length(strlen(string));
1867 char set[length + 5];
1873 if (string[0] != '\0') {
1874 set[3] = toupper(string[0]);
1875 memcpy(set + 4, string + 1, length - 1);
1878 set[length + 3] = ':';
1879 set[length + 4] = '\0';
1881 if (SEL sel = sel_getUid(set))
1882 if (CYImplements(self, _class, sel)) {
1883 JSValueRef arguments[1] = {value};
1884 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1888 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1889 [internal setProperty:property toValue:value inContext:context];
1896 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1897 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1898 id self(internal->GetValue());
1901 NSString *name(CYCastNSString(NULL, context, property));
1902 return [self cy$deleteProperty:name];
1903 } CYPoolCatch(false)
1904 } CYCatch(false) return /*XXX*/ false; }
1906 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1907 const char *name(sel_getName(method_getName(method)));
1908 if (strchr(name, ':') != NULL)
1911 const char *type(method_getTypeEncoding(method));
1912 if (type == NULL || *type == '\0' || *type == 'v')
1915 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1918 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1919 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1920 id self(internal->GetValue());
1923 Class _class(object_getClass(self));
1928 objc_property_t *data(class_copyPropertyList(_class, &size));
1929 for (size_t i(0); i != size; ++i)
1930 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1935 if (CYHasImplicitProperties(_class))
1936 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1937 #if OBJC_API_VERSION >= 2
1939 objc_method **data(class_copyMethodList(current, &size));
1940 for (size_t i(0); i != size; ++i)
1941 Instance_getPropertyNames_message(names, data[i]);
1944 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1945 for (int i(0); i != methods->method_count; ++i)
1946 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1951 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1952 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1953 [self cy$getPropertyNames:names inContext:context];
1957 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1958 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1959 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1963 static const char *CYBlockEncoding(NSBlock *self) {
1964 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1965 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1967 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1968 descriptor += sizeof(BlockDescriptor1);
1969 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1970 descriptor += sizeof(BlockDescriptor2);
1971 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1972 return descriptor3->signature;
1975 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1976 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1977 id self(internal->GetValue());
1979 if (const char *encoding = CYBlockEncoding(self)) {
1985 sig::Signature signature;
1986 sig::Parse(pool, &signature, encoding, &Structor_);
1989 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1991 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1992 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1993 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1997 CYThrow("NSBlock without signature field passed arguments");
2001 } CYPoolCatch(NULL);
2006 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
2007 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2008 Class _class(internal->GetValue());
2009 if (!CYIsClass(_class))
2012 if (CYJSValueIsNSObject(context, instance)) {
2013 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2014 // XXX: this isn't always safe
2015 return [linternal->GetValue() isKindOfClass:_class];
2021 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2023 throw CYJSError(context, "incorrect number of arguments to Instance");
2025 id value(CYCastNSObject(&pool, context, arguments[0]));
2027 value = [NSNull null];
2028 return CYCastJSValue(context, [value cy$box]);
2031 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2032 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2035 id self(internal->GetValue());
2036 const char *name(CYPoolCString(pool, context, property));
2038 if (object_getInstanceVariable(self, name, NULL) != NULL)
2044 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2045 length = CYCastDouble(encoding + 1);
2049 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2050 for (size_t i(0); i != size; ++i)
2051 if (ivars[i] == ivar)
2053 else if (ivar_getOffset(ivars[i]) == offset) {
2054 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2055 _assert(encoding != NULL);
2056 _assert(encoding[0] == 'b');
2057 shift += CYCastDouble(encoding + 1);
2062 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2063 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2066 id self(internal->GetValue());
2067 const char *name(CYPoolCString(pool, context, property));
2070 if (strcmp(name, "isa") == 0)
2071 return CYCastJSValue(context, object_getClass(self));
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(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 auto type(new(pool) Type_privateData(encoding));
2090 return CYFromFFI(context, type->type_, type->GetFFI(), data);
2097 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2098 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2101 id self(internal->GetValue());
2102 const char *name(CYPoolCString(pool, context, property));
2104 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2105 ptrdiff_t offset(ivar_getOffset(ivar));
2106 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2108 const char *encoding(ivar_getTypeEncoding(ivar));
2109 _assert(encoding != NULL);
2110 if (encoding[0] == 'b') {
2111 unsigned length, shift;
2112 CYBitField(length, shift, self, ivar, encoding, offset);
2113 _assert(shift + length <= sizeof(uintptr_t) * 8);
2114 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2115 uintptr_t mask((1 << length) - 1);
2116 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2118 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2119 CYPoolFFI(&pool, context, type->type_, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2127 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2128 if (Class super = class_getSuperclass(_class))
2129 Internal_getPropertyNames_(super, names);
2131 #if OBJC_API_VERSION >= 2
2133 objc_ivar **data(class_copyIvarList(_class, &size));
2134 for (size_t i(0); i != size; ++i)
2135 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2138 if (objc_ivar_list *ivars = _class->ivars)
2139 for (int i(0); i != ivars->ivar_count; ++i)
2140 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2144 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2145 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2148 id self(internal->GetValue());
2149 Class _class(object_getClass(self));
2151 Internal_getPropertyNames_(_class, names);
2154 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2155 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2156 return internal->GetOwner();
2159 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2161 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2164 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2166 NSString *name(CYCastNSString(&pool, context, property));
2167 if (Class _class = NSClassFromString(name))
2168 return CYMakeInstance(context, _class, true);
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)));
2196 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2199 if (Class *data = CYCopyClassList(size)) {
2200 for (size_t i(0); i != size; ++i)
2201 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2206 while (Class _class = objc_next_class(&state))
2207 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2211 #if OBJC_API_VERSION >= 2
2212 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2213 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2216 const char *name(CYPoolCString(pool, context, property));
2218 const char **data(objc_copyClassNamesForImage(internal, &size));
2220 for (size_t i(0); i != size; ++i)
2221 if (strcmp(name, data[i]) == 0) {
2222 if (Class _class = objc_getClass(name)) {
2223 value = CYMakeInstance(context, _class, true);
2234 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2235 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2237 const char **data(objc_copyClassNamesForImage(internal, &size));
2238 for (size_t i(0); i != size; ++i)
2239 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2243 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2245 const char *name(CYPoolCString(pool, context, property));
2247 const char **data(objc_copyImageNames(&size));
2248 for (size_t i(0); i != size; ++i)
2249 if (strcmp(name, data[i]) == 0) {
2258 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2259 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2263 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2265 const char **data(objc_copyImageNames(&size));
2266 for (size_t i(0); i != size; ++i)
2267 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2272 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2274 const char *name(CYPoolCString(pool, context, property));
2275 if (Protocol *protocol = objc_getProtocol(name))
2276 return CYMakeInstance(context, protocol, true);
2280 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2281 #if OBJC_API_VERSION >= 2
2283 Protocol **data(objc_copyProtocolList(&size));
2284 for (size_t i(0); i != size; ++i)
2285 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2292 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2294 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2296 return Instance::Make(context, nil);
2300 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2301 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2305 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2306 *data = reinterpret_cast<void *>(address);
2307 return KERN_SUCCESS;
2311 std::set<Class> query_;
2312 JSContextRef context_;
2313 JSObjectRef results_;
2316 struct CYObjectStruct {
2320 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2321 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2322 JSContextRef context(choice->context_);
2324 for (unsigned i(0); i != count; ++i) {
2325 vm_range_t &range(ranges[i]);
2326 void *data(reinterpret_cast<void *>(range.address));
2327 size_t size(range.size);
2329 if (size < sizeof(CYObjectStruct))
2332 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2334 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2336 Class isa(reinterpret_cast<Class>(pointers[0]));
2339 std::set<Class>::const_iterator result(choice->query_.find(isa));
2340 if (result == choice->query_.end())
2343 size_t needed(class_getInstanceSize(*result));
2344 // XXX: if (size < needed)
2346 size_t boundary(496);
2350 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2352 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2356 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2358 throw CYJSError(context, "choose() takes a class argument");
2360 CYGarbageCollect(context);
2363 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2365 vm_address_t *zones(NULL);
2367 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2368 _assert(error == KERN_SUCCESS);
2370 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2371 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2374 choice.context_ = context;
2375 choice.results_ = results;
2378 Class *classes(CYCopyClassList(number));
2379 _assert(classes != NULL);
2381 for (size_t i(0); i != number; ++i)
2382 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2383 if (current == _class) {
2384 choice.query_.insert(classes[i]);
2390 for (unsigned i(0); i != size; ++i) {
2391 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2392 if (zone == NULL || zone->introspect == NULL)
2395 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2403 #if defined(__i386__) || defined(__x86_64__)
2404 #define OBJC_MAX_STRUCT_BY_VALUE 8
2405 static int struct_forward_array[] = {
2406 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2407 #elif defined(__arm__)
2408 #define OBJC_MAX_STRUCT_BY_VALUE 1
2409 static int struct_forward_array[] = {
2411 #elif defined(__arm64__)
2414 #error missing objc-runtime-info
2418 static bool stret(ffi_type *ffi_type) {
2419 return ffi_type->type == FFI_TYPE_STRUCT && (
2420 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2421 struct_forward_array[ffi_type->size] != 0
2427 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2431 _class = object_getClass(self);
2435 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2436 imp = method_getImplementation(method);
2437 type = method_getTypeEncoding(method);
2442 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2444 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2445 type = CYPoolCString(pool, context, [method _typeString]);
2453 sig::Signature signature;
2454 sig::Parse(pool, &signature, type, &Structor_);
2456 size_t used(count + 3);
2457 if (used > signature.count) {
2458 sig::Element *elements(new (pool) sig::Element[used]);
2459 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2461 for (size_t index(signature.count); index != used; ++index) {
2462 sig::Element *element(&elements[index]);
2463 element->name = NULL;
2464 element->offset = _not(size_t);
2466 sig::Type *type(new (pool) sig::Type);
2467 memset(type, 0, sizeof(*type));
2468 type->primitive = sig::object_P;
2469 element->type = type;
2472 signature.elements = elements;
2473 signature.count = used;
2477 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2482 if (stret(cif.rtype))
2483 imp = class_getMethodImplementation_stret(_class, _cmd);
2486 imp = class_getMethodImplementation(_class, _cmd);
2488 objc_super super = {self, _class};
2489 imp = objc_msg_lookup_super(&super, _cmd);
2493 void (*function)() = reinterpret_cast<void (*)()>(imp);
2494 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2497 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2499 throw CYJSError(context, "too few arguments to objc_msgSend");
2509 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2510 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2511 self = internal->GetValue();
2512 _class = internal->class_;;
2513 uninitialized = false;
2514 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2515 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2516 self = internal->GetValue();
2518 uninitialized = internal->IsUninitialized();
2520 internal->value_ = nil;
2522 self = CYCastNSObject(&pool, context, arguments[0]);
2524 uninitialized = false;
2528 return CYJSNull(context);
2530 _cmd = CYCastSEL(context, arguments[1]);
2532 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2535 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2536 return $objc_msgSend(context, object, _this, count, arguments);
2539 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2540 JSValueRef setup[count + 2];
2543 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2544 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2547 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2549 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2551 // XXX: handle Instance::Uninitialized?
2552 id self(CYCastNSObject(&pool, context, _this));
2556 setup[1] = &internal->sel_;
2558 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2561 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2563 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2565 id self(CYCastNSObject(&pool, context, arguments[0]));
2566 Class _class(CYCastClass(pool, context, arguments[1]));
2567 return cy::Super::Make(context, self, _class);
2570 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2572 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2574 const char *name(CYPoolCString(pool, context, arguments[0]));
2575 return CYMakeSelector(context, sel_registerName(name));
2578 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2580 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2581 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2582 return CYMakeInstance(context, self, false);
2585 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2586 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2587 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2590 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2591 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2592 Type_privateData *typical(internal->GetType());
2597 if (typical == NULL) {
2601 type = typical->type_;
2602 ffi = typical->ffi_;
2605 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2608 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2609 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2610 const char *encoding(CYBlockEncoding(internal->GetValue()));
2611 if (encoding == NULL)
2612 return CYJSNull(context);
2613 // XXX: this should be stored on a FunctionInstance private value subclass
2615 sig::Signature signature;
2616 sig::Parse(pool, &signature, encoding, &Structor_);
2617 return CYMakeType(context, &signature);
2620 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2621 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2622 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2625 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2626 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2627 id self(internal->GetValue());
2628 if (!CYIsClass(self))
2629 return CYJSUndefined(context);
2630 return CYGetClassPrototype(context, self);
2633 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2634 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2635 id self(internal->GetValue());
2636 if (!CYIsClass(self))
2637 return CYJSUndefined(context);
2638 return Messages::Make(context, (Class) self);
2641 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2642 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2644 if (!CYJSValueIsNSObject(context, _this))
2647 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2648 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2651 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2652 if (!CYJSValueIsNSObject(context, _this))
2655 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2656 id value(internal->GetValue());
2663 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2665 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2666 return CYJSUndefined(context);
2667 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2670 return CYCastJSValue(context, CYJSString(context, [value description]));
2672 } CYCatch(NULL) return /*XXX*/ NULL; }
2674 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2675 if (!CYJSValueIsNSObject(context, _this))
2678 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2679 id value(internal->GetValue());
2681 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2684 if (JSValueRef result = [value cy$valueOfInContext:context])
2688 } CYCatch(NULL) return /*XXX*/ NULL; }
2690 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2691 if (!CYJSValueIsNSObject(context, _this))
2694 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2695 // XXX: but... but... THIS ISN'T A POINTER! :(
2696 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2697 } CYCatch(NULL) return /*XXX*/ NULL; }
2699 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2700 if (!CYJSValueIsNSObject(context, _this))
2703 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2704 id value(internal->GetValue());
2707 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2708 return CYCastJSValue(context, CYJSString(context, [value description]));
2710 } CYCatch(NULL) return /*XXX*/ NULL; }
2712 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2713 if (!CYJSValueIsNSObject(context, _this))
2716 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2717 id value(internal->GetValue());
2719 if (!CYIsClass(value))
2720 CYThrow("non-Class object cannot be used as Type");
2723 memset(&type, 0, sizeof(type));
2724 type.primitive = sig::object_P;
2725 type.name = class_getName(value);
2726 return CYMakeType(context, &type);
2727 } CYCatch(NULL) return /*XXX*/ NULL; }
2729 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2730 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2731 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2734 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2735 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2738 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2739 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2740 const char *name(sel_getName(internal->GetValue()));
2743 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2744 return CYCastJSValue(context, CYJSString(context, string));
2746 } CYCatch(NULL) return /*XXX*/ NULL; }
2748 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2750 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2753 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2754 SEL sel(internal->GetValue());
2756 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2757 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2758 const char *encoding(method_getTypeEncoding(method));
2760 sig::Signature signature;
2761 sig::Parse(pool, &signature, encoding, &Structor_);
2762 return CYMakeType(context, &signature);
2765 static JSStaticValue Selector_staticValues[2] = {
2766 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2767 {NULL, NULL, NULL, 0}
2770 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2771 static JSStaticValue Instance_staticValues[5] = {
2772 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2773 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2774 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2775 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2776 {NULL, NULL, NULL, 0}
2779 static JSStaticValue FunctionInstance_staticValues[6] = {
2780 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2781 // XXX: this is sadly a duplicate of Instance_staticValues
2782 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2783 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2784 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2785 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2786 {NULL, NULL, NULL, 0}
2789 static JSStaticFunction Instance_staticFunctions[7] = {
2790 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2791 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2792 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2793 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2794 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2795 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2799 static JSStaticFunction Class_staticFunctions[2] = {
2800 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2804 static JSStaticFunction Internal_staticFunctions[2] = {
2805 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2809 static JSStaticFunction Selector_staticFunctions[5] = {
2810 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2811 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2812 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2813 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2818 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2819 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2820 } CYObjectiveCatch }
2823 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2824 CYPool &pool(CYGetGlobalPool());
2826 Object_type = new(pool) Type_privateData(sig::object_P);
2827 Selector_type = new(pool) Type_privateData(sig::selector_P);
2829 NSArray_ = objc_getClass("NSArray");
2830 NSBlock_ = objc_getClass("NSBlock");
2831 NSDictionary_ = objc_getClass("NSDictionary");
2832 NSNumber_ = objc_getClass("NSNumber");
2833 NSString_ = objc_getClass("NSString");
2834 Object_ = objc_getClass("Object");
2837 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2839 // XXX: apparently, iOS now has both of these
2840 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2841 if (NSCFBoolean_ == nil)
2842 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2844 NSCFType_ = objc_getClass("NSCFType");
2846 NSZombie_ = objc_getClass("_NSZombie_");
2848 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2851 JSClassDefinition definition;
2853 definition = kJSClassDefinitionEmpty;
2854 definition.className = "Instance";
2855 definition.staticValues = Instance_staticValues;
2856 definition.staticFunctions = Instance_staticFunctions;
2857 definition.hasProperty = &Instance_hasProperty;
2858 definition.getProperty = &Instance_getProperty;
2859 definition.setProperty = &Instance_setProperty;
2860 definition.deleteProperty = &Instance_deleteProperty;
2861 definition.getPropertyNames = &Instance_getPropertyNames;
2862 definition.callAsConstructor = &Instance_callAsConstructor;
2863 definition.hasInstance = &Instance_hasInstance;
2864 definition.finalize = &CYFinalize;
2865 Instance_ = JSClassCreate(&definition);
2867 definition.className = "ArrayInstance";
2868 ArrayInstance_ = JSClassCreate(&definition);
2870 definition.className = "BooleanInstance";
2871 BooleanInstance_ = JSClassCreate(&definition);
2873 definition.className = "NumberInstance";
2874 NumberInstance_ = JSClassCreate(&definition);
2876 definition.className = "ObjectInstance";
2877 ObjectInstance_ = JSClassCreate(&definition);
2879 definition.className = "StringInstance";
2880 StringInstance_ = JSClassCreate(&definition);
2882 definition.className = "FunctionInstance";
2883 definition.staticValues = FunctionInstance_staticValues;
2884 definition.callAsFunction = &FunctionInstance_callAsFunction;
2885 FunctionInstance_ = JSClassCreate(&definition);
2887 definition = kJSClassDefinitionEmpty;
2888 definition.className = "Class";
2889 definition.staticFunctions = Class_staticFunctions;
2890 Class_ = JSClassCreate(&definition);
2892 definition = kJSClassDefinitionEmpty;
2893 definition.className = "Internal";
2894 definition.staticFunctions = Internal_staticFunctions;
2895 definition.hasProperty = &Internal_hasProperty;
2896 definition.getProperty = &Internal_getProperty;
2897 definition.setProperty = &Internal_setProperty;
2898 definition.getPropertyNames = &Internal_getPropertyNames;
2899 definition.finalize = &CYFinalize;
2900 Internal_ = JSClassCreate(&definition);
2902 definition = kJSClassDefinitionEmpty;
2903 definition.className = "Message";
2904 definition.staticFunctions = cy::Functor::StaticFunctions;
2905 definition.staticValues = cy::Functor::StaticValues;
2906 definition.callAsFunction = &Message_callAsFunction;
2907 definition.finalize = &CYFinalize;
2908 Message_ = JSClassCreate(&definition);
2910 definition = kJSClassDefinitionEmpty;
2911 definition.className = "Messages";
2912 definition.hasProperty = &Messages_hasProperty;
2913 definition.getProperty = &Messages_getProperty;
2914 definition.setProperty = &Messages_setProperty;
2915 #if 0 && OBJC_API_VERSION < 2
2916 definition.deleteProperty = &Messages_deleteProperty;
2918 definition.getPropertyNames = &Messages_getPropertyNames;
2919 definition.finalize = &CYFinalize;
2920 Messages_ = JSClassCreate(&definition);
2922 definition = kJSClassDefinitionEmpty;
2923 definition.className = "Selector";
2924 definition.staticValues = Selector_staticValues;
2925 definition.staticFunctions = Selector_staticFunctions;
2926 definition.callAsFunction = &Selector_callAsFunction;
2927 definition.finalize = &CYFinalize;
2928 Selector_ = JSClassCreate(&definition);
2930 definition = kJSClassDefinitionEmpty;
2931 definition.className = "Super";
2932 definition.staticFunctions = Internal_staticFunctions;
2933 definition.finalize = &CYFinalize;
2934 Super_ = JSClassCreate(&definition);
2936 definition = kJSClassDefinitionEmpty;
2937 definition.className = "ObjectiveC::Classes";
2938 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2939 definition.getProperty = &ObjectiveC_Classes_getProperty;
2940 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2941 ObjectiveC_Classes_ = JSClassCreate(&definition);
2943 definition = kJSClassDefinitionEmpty;
2944 definition.className = "ObjectiveC::Constants";
2945 definition.getProperty = &ObjectiveC_Constants_getProperty;
2946 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2947 ObjectiveC_Constants_ = JSClassCreate(&definition);
2949 #if OBJC_API_VERSION >= 2
2950 definition = kJSClassDefinitionEmpty;
2951 definition.className = "ObjectiveC::Images";
2952 definition.getProperty = &ObjectiveC_Images_getProperty;
2953 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2954 ObjectiveC_Images_ = JSClassCreate(&definition);
2956 definition = kJSClassDefinitionEmpty;
2957 definition.className = "ObjectiveC::Image::Classes";
2958 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2959 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2960 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2963 definition = kJSClassDefinitionEmpty;
2964 definition.className = "ObjectiveC::Protocols";
2965 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2966 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2967 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2970 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2971 // XXX: this is horrible; there has to be a better way to do this
2973 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2975 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2981 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2982 JSObjectRef global(CYGetGlobalObject(context));
2983 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2984 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2985 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2986 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2988 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2989 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2991 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2992 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2993 CYArrayPush(context, alls, protocols);
2995 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2996 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2997 CYArrayPush(context, alls, classes);
2999 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
3000 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
3001 CYArrayPush(context, alls, constants);
3003 #if OBJC_API_VERSION >= 2
3004 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3007 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
3008 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3009 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3010 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3011 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
3013 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
3014 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3016 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
3017 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
3018 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
3019 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
3020 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
3022 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
3023 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
3024 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
3025 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
3026 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
3028 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
3029 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
3030 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
3031 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
3032 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
3034 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
3035 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
3036 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
3037 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
3038 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
3040 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3041 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3042 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3043 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3044 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3046 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3047 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3048 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3049 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3050 CYSetPrototype(context, StringInstance_prototype, String_prototype);
3052 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
3053 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
3054 CYSetPrototype(context, Class_prototype, Instance_prototype);
3056 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3057 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3058 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3060 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3061 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3064 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3067 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3069 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3070 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3073 static CYHook CYObjectiveCHook = {
3074 &CYObjectiveC_ExecuteStart,
3075 &CYObjectiveC_ExecuteEnd,
3076 &CYObjectiveC_CallFunction,
3077 &CYObjectiveC_Initialize,
3078 &CYObjectiveC_SetupContext,
3079 &CYObjectiveC_PoolFFI,
3080 &CYObjectiveC_FromFFI,
3083 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3085 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3086 CYSetupContext(context);
3087 } CYObjectiveCatch }
3089 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3092 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3093 CYStream stream(utf8.data, utf8.data + utf8.size);
3094 utf8 = CYPoolCode(pool, stream);
3096 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3097 size_t bytes(utf16.size * sizeof(uint16_t));
3098 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3099 memcpy(copy, utf16.data, bytes);
3103 } catch (const CYException &exception) {
3105 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];