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, Instance::Flags flags = Instance::None) {
429 _assert(object != nil);
431 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
433 if (weak != NULL && &JSWeakObjectMapGet != NULL)
434 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
437 if ((flags & Instance::Permanent) == 0)
438 object = [object retain];
440 JSObjectRef instance(Instance::Make(context, object, flags));
442 if (weak != NULL && &JSWeakObjectMapSet != NULL)
443 JSWeakObjectMapSet(context, weak, object, instance);
448 @interface NSMethodSignature (Cycript)
449 - (NSString *) _typeString;
452 @interface NSObject (Cycript)
454 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
455 - (JSType) cy$JSType;
457 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
458 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
460 - (bool) cy$hasProperty:(NSString *)name;
461 - (NSObject *) cy$getProperty:(NSString *)name;
462 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
463 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
464 - (bool) cy$deleteProperty:(NSString *)name;
465 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
467 + (bool) cy$hasImplicitProperties;
473 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
476 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
477 _assert(value != nil);
479 Class _class(object_getClass(value));
481 if (class_isMetaClass(_class)) {
482 const char *name(class_getName(value));
483 if (class_isMetaClass(value))
484 return [NSString stringWithFormat:@"object_getClass(%s)", name];
486 return [NSString stringWithUTF8String:name];
490 if (_class == NSZombie_)
491 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
494 SEL sel(@selector(cy$toCYON:inSet:));
496 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
497 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
498 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
499 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
500 return [value cy$toCYON:objective inSet:objects];
502 return [NSString stringWithFormat:@"%@", value];
505 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
507 return CYCastNSCYON(value, objective, *objects);
509 std::set<void *> objects;
510 return CYCastNSCYON(value, objective, objects);
515 struct PropertyAttributes {
520 const char *variable;
533 PropertyAttributes(objc_property_t property) :
545 name = property_getName(property);
546 const char *attributes(property_getAttributes(property));
548 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
549 if ((next = strchr(token, ',')) != NULL)
552 case 'R': readonly = true; break;
553 case 'C': copy = true; break;
554 case '&': retain = true; break;
555 case 'N': nonatomic = true; break;
556 case 'G': getter_ = token + 1; break;
557 case 'S': setter_ = token + 1; break;
558 case 'V': variable = token + 1; break;
562 /*if (variable == NULL) {
563 variable = property_getName(property);
564 size_t size(strlen(variable));
565 char *name(new(pool_) char[size + 2]);
567 memcpy(name + 1, variable, size);
568 name[size + 1] = '\0';
573 const char *Getter() {
575 getter_ = pool_.strdup(name);
579 const char *Setter() {
580 if (setter_ == NULL && !readonly) {
581 size_t length(strlen(name));
583 char *temp(new(pool_) char[length + 5]);
589 temp[3] = toupper(name[0]);
590 memcpy(temp + 4, name + 1, length - 1);
593 temp[length + 3] = ':';
594 temp[length + 4] = '\0';
604 @interface CYWebUndefined : NSObject {
607 + (CYWebUndefined *) undefined;
611 @implementation CYWebUndefined
613 + (CYWebUndefined *) undefined {
614 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
620 #define WebUndefined CYWebUndefined
622 /* Bridge: CYJSObject {{{ */
623 @interface CYJSObject : NSMutableDictionary {
625 JSGlobalContextRef context_;
628 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
630 - (NSUInteger) count;
631 - (id) objectForKey:(id)key;
632 - (NSEnumerator *) keyEnumerator;
633 - (void) setObject:(id)object forKey:(id)key;
634 - (void) removeObjectForKey:(id)key;
638 /* Bridge: CYJSArray {{{ */
639 @interface CYJSArray : NSMutableArray {
641 JSGlobalContextRef context_;
644 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
646 - (NSUInteger) count;
647 - (id) objectAtIndex:(NSUInteger)index;
649 - (void) addObject:(id)anObject;
650 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
651 - (void) removeLastObject;
652 - (void) removeObjectAtIndex:(NSUInteger)index;
653 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
658 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
659 return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
662 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
663 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
666 struct CYBlockDescriptor {
668 BlockDescriptor1 one_;
669 BlockDescriptor2 two_;
670 BlockDescriptor3 three_;
673 Closure_privateData *internal_;
676 void CYDisposeBlock(BlockLiteral *literal) {
677 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
680 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
681 JSObjectRef _this(CYCastJSObject(context, values[0]));
682 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
685 static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
686 CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
689 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
690 _assert(__NSMallocBlock__ != Nil);
691 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
693 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
694 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
696 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
697 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
699 literal->isa = __NSMallocBlock__;
700 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
701 literal->reserved = 0;
702 literal->descriptor = descriptor;
704 descriptor->d_.one_.size = sizeof(descriptor->d_);
705 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
706 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
708 return reinterpret_cast<NSBlock *>(literal);
711 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
712 if (CYJSValueIsNSObject(context, object)) {
713 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
714 return internal->GetValue();
717 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
718 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
719 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
722 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
723 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
727 @interface NSBoolNumber : NSNumber {
732 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
736 switch (JSType type = JSValueGetType(context, value)) {
737 case kJSTypeUndefined:
738 object = [WebUndefined undefined];
748 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
751 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
757 object = CYCopyNSNumber(context, value);
762 object = CYCopyNSString(context, value);
767 // XXX: this might could be more efficient
768 object = CYCastNSObject(pool, context, (JSObjectRef) value);
773 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
780 return CYPoolRelease(pool, object);
782 return [object retain];
785 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
786 return CYNSObject(pool, context, value, true);
789 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
790 return CYNSObject(&pool, context, value, false);
793 /* Bridge: NSArray {{{ */
794 @implementation NSArray (Cycript)
797 return [[self mutableCopy] autorelease];
800 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
801 _oassert(objects.insert(self).second);
803 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
804 [json appendString:@"@["];
808 for (id object in self) {
810 for (size_t index(0), count([self count]); index != count; ++index) {
811 id object([self objectAtIndex:index]);
814 [json appendString:@","];
817 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
818 [json appendString:CYCastNSCYON(object, true, objects)];
820 [json appendString:@","];
825 [json appendString:@"]"];
829 - (bool) cy$hasProperty:(NSString *)name {
830 if ([name isEqualToString:@"length"])
833 size_t index(CYGetIndex(name));
834 if (index == _not(size_t) || index >= [self count])
835 return [super cy$hasProperty:name];
840 - (NSObject *) cy$getProperty:(NSString *)name {
841 size_t index(CYGetIndex(name));
842 if (index == _not(size_t) || index >= [self count])
843 return [super cy$getProperty:name];
845 return [self objectAtIndex:index];
848 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
850 if ([name isEqualToString:@"length"])
851 return CYCastJSValue(context, [self count]);
854 return [super cy$getProperty:name inContext:context];
857 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
858 [super cy$getPropertyNames:names inContext:context];
860 for (size_t index(0), count([self count]); index != count; ++index) {
861 id object([self objectAtIndex:index]);
862 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
864 sprintf(name, "%zu", index);
865 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
870 + (bool) cy$hasImplicitProperties {
876 /* Bridge: NSBlock {{{ */
883 /* Bridge: NSBoolNumber {{{ */
885 @implementation NSBoolNumber (Cycript)
887 - (JSType) cy$JSType {
888 return kJSTypeBoolean;
891 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
892 NSString *value([self boolValue] ? @"true" : @"false");
893 return objective ? value : [NSString stringWithFormat:@"@%@", value];
896 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
897 return CYCastJSValue(context, (bool) [self boolValue]);
903 /* Bridge: NSDictionary {{{ */
904 @implementation NSDictionary (Cycript)
907 return [[self mutableCopy] autorelease];
910 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
911 _oassert(objects.insert(self).second);
913 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
914 [json appendString:@"@{"];
918 for (NSObject *key in self) {
920 NSEnumerator *keys([self keyEnumerator]);
921 while (NSObject *key = [keys nextObject]) {
924 [json appendString:@","];
927 [json appendString:CYCastNSCYON(key, true, objects)];
928 [json appendString:@":"];
929 NSObject *object([self objectForKey:key]);
930 [json appendString:CYCastNSCYON(object, true, objects)];
933 [json appendString:@"}"];
937 - (bool) cy$hasProperty:(NSString *)name {
938 return [self objectForKey:name] != nil;
941 - (NSObject *) cy$getProperty:(NSString *)name {
942 return [self objectForKey:name];
945 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
946 [super cy$getPropertyNames:names inContext:context];
949 for (NSObject *key in self) {
951 NSEnumerator *keys([self keyEnumerator]);
952 while (NSObject *key = [keys nextObject]) {
954 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
958 + (bool) cy$hasImplicitProperties {
964 /* Bridge: NSMutableArray {{{ */
965 @implementation NSMutableArray (Cycript)
967 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
968 if ([name isEqualToString:@"length"]) {
969 // XXX: is this not intelligent?
970 NSNumber *number(reinterpret_cast<NSNumber *>(value));
972 NSUInteger size([number unsignedIntegerValue]);
974 NSUInteger size([number unsignedIntValue]);
976 NSUInteger count([self count]);
978 [self removeObjectsInRange:NSMakeRange(size, count - size)];
979 else if (size != count) {
980 WebUndefined *undefined([WebUndefined undefined]);
981 for (size_t i(count); i != size; ++i)
982 [self addObject:undefined];
987 size_t index(CYGetIndex(name));
988 if (index == _not(size_t))
989 return [super cy$setProperty:name to:value];
991 id object(value ?: [NSNull null]);
993 size_t count([self count]);
995 [self replaceObjectAtIndex:index withObject:object];
997 if (index != count) {
998 WebUndefined *undefined([WebUndefined undefined]);
999 for (size_t i(count); i != index; ++i)
1000 [self addObject:undefined];
1003 [self addObject:object];
1009 - (bool) cy$deleteProperty:(NSString *)name {
1010 size_t index(CYGetIndex(name));
1011 if (index == _not(size_t) || index >= [self count])
1012 return [super cy$deleteProperty:name];
1013 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1019 /* Bridge: NSMutableDictionary {{{ */
1020 @implementation NSMutableDictionary (Cycript)
1022 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1023 [self setObject:(value ?: [NSNull null]) forKey:name];
1027 - (bool) cy$deleteProperty:(NSString *)name {
1028 if ([self objectForKey:name] == nil)
1031 [self removeObjectForKey:name];
1038 /* Bridge: NSNumber {{{ */
1039 @implementation NSNumber (Cycript)
1041 - (JSType) cy$JSType {
1043 // XXX: this just seems stupid
1044 if ([self class] == NSCFBoolean_)
1045 return kJSTypeBoolean;
1047 return kJSTypeNumber;
1050 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1051 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1052 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1055 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1056 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1057 } CYObjectiveCatch }
1061 /* Bridge: NSNull {{{ */
1062 @implementation NSNull (Cycript)
1064 - (JSType) cy$JSType {
1068 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1069 NSString *value(@"null");
1070 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1073 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1074 return CYJSNull(context);
1075 } CYObjectiveCatch }
1079 /* Bridge: NSObject {{{ */
1080 @implementation NSObject (Cycript)
1086 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1087 return [self cy$valueOfInContext:context];
1090 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1092 } CYObjectiveCatch }
1094 - (JSType) cy$JSType {
1095 return kJSTypeObject;
1098 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1099 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1102 - (bool) cy$hasProperty:(NSString *)name {
1106 - (NSObject *) cy$getProperty:(NSString *)name {
1110 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1111 if (NSObject *value = [self cy$getProperty:name])
1112 return CYCastJSValue(context, value);
1114 } CYObjectiveCatch }
1116 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1120 - (bool) cy$deleteProperty:(NSString *)name {
1124 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1127 + (bool) cy$hasImplicitProperties {
1133 /* Bridge: NSProxy {{{ */
1134 @implementation NSProxy (Cycript)
1136 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1137 return [[self description] cy$toCYON:objective inSet:objects];
1142 /* Bridge: NSSet {{{ */
1143 @implementation NSSet (Cycript)
1145 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1146 _oassert(objects.insert(self).second);
1148 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1149 [json appendString:@"[NSSet setWithArray:"];
1150 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1151 [json appendString:@"]]"];
1157 /* Bridge: NSString {{{ */
1158 @implementation NSString (Cycript)
1161 return [[self copy] autorelease];
1164 - (JSType) cy$JSType {
1165 return kJSTypeString;
1168 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1169 std::ostringstream str;
1172 CYUTF8String string(CYCastUTF8String(self));
1173 CYStringify(str, string.data, string.size);
1174 std::string value(str.str());
1175 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1178 - (bool) cy$hasProperty:(NSString *)name {
1179 size_t index(CYGetIndex(name));
1180 if (index == _not(size_t) || index >= [self length])
1181 return [super cy$hasProperty:name];
1186 - (NSObject *) cy$getProperty:(NSString *)name {
1187 size_t index(CYGetIndex(name));
1188 if (index == _not(size_t) || index >= [self length])
1189 return [super cy$getProperty:name];
1191 return [self substringWithRange:NSMakeRange(index, 1)];
1194 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1195 [super cy$getPropertyNames:names inContext:context];
1197 for (size_t index(0), length([self length]); index != length; ++index) {
1199 sprintf(name, "%zu", index);
1200 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1204 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1205 return CYCastJSValue(context, CYJSString(context, self));
1206 } CYObjectiveCatch }
1210 /* Bridge: WebUndefined {{{ */
1211 @implementation WebUndefined (Cycript)
1213 - (JSType) cy$JSType {
1214 return kJSTypeUndefined;
1217 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1218 NSString *value(@"undefined");
1219 return value; // XXX: maybe use the below code, adding @undefined?
1220 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1223 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1224 return CYJSUndefined(context);
1225 } CYObjectiveCatch }
1230 static bool CYIsClass(id self) {
1232 return class_isMetaClass(object_getClass(self));
1234 return GSObjCIsClass(self);
1238 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1239 id self(CYCastNSObject(&pool, context, value));
1240 if (CYIsClass(self))
1241 return (Class) self;
1242 throw CYJSError(context, "got something that is not a Class");
1246 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1248 size_t size(JSPropertyNameArrayGetCount(names));
1249 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1250 for (size_t index(0); index != size; ++index)
1251 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1255 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1257 return CYJSNull(context);
1259 return CYMakeInstance(context, value);
1260 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1262 @implementation CYJSObject
1264 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1265 if ((self = [super init]) != nil) {
1267 context_ = CYGetJSContext(context);
1268 JSGlobalContextRetain(context_);
1269 JSValueProtect(context_, object_);
1271 } CYObjectiveCatch }
1273 - (void) dealloc { CYObjectiveTry {
1274 JSValueUnprotect(context_, object_);
1275 JSGlobalContextRelease(context_);
1277 } CYObjectiveCatch }
1279 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1281 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1283 return [super cy$toCYON:objective inSet:objects];
1285 return [NSString stringWithUTF8String:cyon];
1286 } CYObjectiveCatch }
1288 - (NSUInteger) count { CYObjectiveTry {
1289 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1290 size_t size(JSPropertyNameArrayGetCount(names));
1291 JSPropertyNameArrayRelease(names);
1293 } CYObjectiveCatch }
1295 - (id) objectForKey:(id)key { CYObjectiveTry {
1296 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1297 if (JSValueIsUndefined(context, value))
1299 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1300 } CYObjectiveCatch }
1302 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1303 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1304 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1305 JSPropertyNameArrayRelease(names);
1307 } CYObjectiveCatch }
1309 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1310 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1311 } CYObjectiveCatch }
1313 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1314 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1315 } CYObjectiveCatch }
1319 @implementation CYJSArray
1321 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1323 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1324 } CYObjectiveCatch }
1326 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1327 if ((self = [super init]) != nil) {
1329 context_ = CYGetJSContext(context);
1330 JSGlobalContextRetain(context_);
1331 JSValueProtect(context_, object_);
1333 } CYObjectiveCatch }
1335 - (void) dealloc { CYObjectiveTry {
1336 JSValueUnprotect(context_, object_);
1337 JSGlobalContextRelease(context_);
1339 } CYObjectiveCatch }
1341 - (NSUInteger) count { CYObjectiveTry {
1342 return CYArrayLength(context, object_);
1343 } CYObjectiveCatch }
1345 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1346 size_t bounds([self count]);
1347 if (index >= bounds)
1348 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1349 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1350 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1351 } CYObjectiveCatch }
1353 - (void) addObject:(id)object { CYObjectiveTry {
1354 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1355 } CYObjectiveCatch }
1357 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1358 size_t bounds([self count] + 1);
1359 if (index >= bounds)
1360 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1361 JSValueRef arguments[3];
1362 arguments[0] = CYCastJSValue(context, index);
1363 arguments[1] = CYCastJSValue(context, 0);
1364 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1365 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1366 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1367 } CYObjectiveCatch }
1369 - (void) removeLastObject { CYObjectiveTry {
1370 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1371 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1372 } CYObjectiveCatch }
1374 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1375 size_t bounds([self count]);
1376 if (index >= bounds)
1377 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1378 JSValueRef arguments[2];
1379 arguments[0] = CYCastJSValue(context, index);
1380 arguments[1] = CYCastJSValue(context, 1);
1381 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1382 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1383 } CYObjectiveCatch }
1385 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1386 size_t bounds([self count]);
1387 if (index >= bounds)
1388 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1389 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1390 } CYObjectiveCatch }
1394 // XXX: inherit from or replace with CYJSObject
1395 @interface CYInternal : NSObject {
1396 JSGlobalContextRef context_;
1397 JSObjectRef object_;
1402 @implementation CYInternal
1404 - (void) dealloc { CYObjectiveTry {
1405 JSValueUnprotect(context_, object_);
1406 JSGlobalContextRelease(context_);
1408 } CYObjectiveCatch }
1410 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1411 if ((self = [super init]) != nil) {
1412 context_ = CYGetJSContext(context);
1413 JSGlobalContextRetain(context_);
1415 } CYObjectiveCatch }
1417 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1418 if (object_ == NULL)
1421 return JSObjectHasProperty(context, object_, name);
1424 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1425 if (object_ == NULL)
1428 return CYGetProperty(context, object_, name);
1431 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1432 @synchronized (self) {
1433 if (object_ == NULL) {
1434 object_ = JSObjectMake(context, NULL, NULL);
1435 JSValueProtect(context, object_);
1439 CYSetProperty(context, object_, name, value);
1442 + (CYInternal *) get:(id)object {
1443 if (&objc_getAssociatedObject == NULL)
1446 @synchronized (object) {
1447 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1454 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1455 if (&objc_getAssociatedObject == NULL)
1458 @synchronized (object) {
1459 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1462 if (&objc_setAssociatedObject == NULL)
1465 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1466 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1475 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1476 Selector_privateData *internal(new Selector_privateData(sel));
1477 return JSObjectMake(context, Selector_, internal);
1480 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1481 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1482 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1483 return reinterpret_cast<SEL>(internal->value_);
1486 return sel_registerName(CYPoolCString(pool, context, value));
1490 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1491 return (void *) [[NSAutoreleasePool alloc] init];
1492 } CYSadCatch(NULL) }
1494 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1495 return [(NSAutoreleasePool *) handle release];
1498 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1499 ffi_call(cif, function, value, values);
1502 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, sig::Signature *signature) {
1503 if (JSValueIsNull(context, value))
1505 JSObjectRef object(CYCastJSObject(context, value));
1507 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1508 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1510 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1511 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1515 _assert(JSObjectIsFunction(context, object));
1517 _assert(signature != NULL);
1518 _assert(signature->count != 0);
1520 sig::Signature modified;
1521 modified.count = signature->count + 1;
1522 modified.elements = new(pool) sig::Element[modified.count];
1524 modified.elements[0] = signature->elements[0];
1525 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1527 modified.elements[1].name = NULL;
1528 modified.elements[1].type = new(pool) sig::Type();
1529 modified.elements[1].offset = _not(size_t);
1531 memset(modified.elements[1].type, 0, sizeof(sig::Type));
1532 modified.elements[1].type->primitive = sig::object_P;
1534 return CYMakeBlock(context, object, modified);
1537 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1538 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1540 switch (type->primitive) {
1542 // XXX: this function might not handle the idea of a null pool
1543 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &type->data.signature);
1547 case sig::typename_P:
1548 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1551 case sig::selector_P:
1552 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1560 } CYSadCatch(false) }
1562 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1563 switch (type->primitive) {
1564 // XXX: do something epic about blocks
1567 if (NSObject *value = *reinterpret_cast<NSObject **>(data)) {
1568 JSObjectRef object(CYMakeInstance(context, value));
1571 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1573 if ((internal->flags_ & Instance::Uninitialized) != 0) {
1574 internal->flags_ = static_cast<Instance::Flags>(internal->flags_ & ~Instance::Uninitialized);
1575 _assert(internal->value_ == nil);
1576 internal->value_ = value;
1585 case sig::typename_P:
1586 if (Class value = *reinterpret_cast<Class *>(data))
1587 return CYMakeInstance(context, value, Instance::Permanent);
1590 case sig::selector_P:
1591 if (SEL value = *reinterpret_cast<SEL *>(data))
1592 return CYMakeSelector(context, value);
1596 return CYJSNull(context);
1600 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1602 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1603 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1606 #if OBJC_API_VERSION >= 2
1608 method_getReturnType(method, type, sizeof(type));
1610 const char *type(method_getTypeEncoding(method));
1616 // XXX: possibly use a more "awesome" check?
1620 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1621 JSObjectRef _this(CYCastJSObject(context, values[0]));
1622 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1625 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1626 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1629 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1630 Message_privateData *internal(new Message_privateData(sel, type, imp));
1631 return JSObjectMake(context, Message_, internal);
1634 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1635 JSObjectRef function(CYCastJSObject(context, value));
1637 sig::Signature signature;
1638 sig::Parse(pool, &signature, encoding, &Structor_);
1639 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageClosure_));
1640 // XXX: see notes in Library.cpp about needing to leak
1641 return reinterpret_cast<IMP>(internal->GetValue());
1644 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1645 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1646 Class _class(internal->GetValue());
1649 const char *name(CYPoolCString(pool, context, property));
1651 if (SEL sel = sel_getUid(name))
1652 if (class_getInstanceMethod(_class, sel) != NULL)
1658 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1659 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1660 Class _class(internal->GetValue());
1663 const char *name(CYPoolCString(pool, context, property));
1665 if (SEL sel = sel_getUid(name))
1666 if (objc_method *method = class_getInstanceMethod(_class, sel))
1667 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1672 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1673 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1674 Class _class(internal->GetValue());
1677 const char *name(CYPoolCString(pool, context, property));
1678 SEL sel(sel_registerName(name));
1683 if (JSValueIsObjectOfClass(context, value, Message_)) {
1684 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1685 type = sig::Unparse(pool, &message->signature_);
1686 imp = reinterpret_cast<IMP>(message->GetValue());
1687 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1688 type = method_getTypeEncoding(method);
1689 imp = CYMakeMessage(context, value, type);
1690 } else _assert(false);
1692 objc_method *method(NULL);
1693 #if OBJC_API_VERSION >= 2
1695 objc_method **methods(class_copyMethodList(_class, &size));
1696 for (size_t i(0); i != size; ++i)
1697 if (sel_isEqual(method_getName(methods[i]), sel)) {
1698 method = methods[i];
1703 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1704 for (int i(0); i != methods->method_count; ++i)
1705 if (sel_isEqual(method_getName(&methods->method_list[i]), sel)) {
1706 method = &methods->method_list[i];
1712 method_setImplementation(method, imp);
1715 GSMethodList list(GSAllocMethodList(1));
1716 GSAppendMethodToList(list, sel, type, imp, YES);
1717 GSAddMethodList(_class, list, YES);
1718 GSFlushMethodCacheForClass(_class);
1720 class_addMethod(_class, sel, imp, type);
1727 #if 0 && OBJC_API_VERSION < 2
1728 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1729 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1730 Class _class(internal->GetValue());
1733 const char *name(CYPoolCString(pool, context, property));
1735 if (SEL sel = sel_getUid(name))
1736 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1737 objc_method_list list = {NULL, 1, {method}};
1738 class_removeMethods(_class, &list);
1746 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1747 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1748 Class _class(internal->GetValue());
1750 #if OBJC_API_VERSION >= 2
1752 objc_method **data(class_copyMethodList(_class, &size));
1753 for (size_t i(0); i != size; ++i)
1754 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1757 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1758 for (int i(0); i != methods->method_count; ++i)
1759 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1763 static bool CYHasImplicitProperties(Class _class) {
1764 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1765 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1767 return [_class cy$hasImplicitProperties];
1770 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1771 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1772 id self(internal->GetValue());
1774 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1778 NSString *name(CYCastNSString(&pool, context, property));
1780 if (CYInternal *internal = [CYInternal get:self])
1781 if ([internal hasProperty:property inContext:context])
1784 Class _class(object_getClass(self));
1787 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1788 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1789 if ([self cy$hasProperty:name])
1791 } CYPoolCatch(false)
1793 const char *string(CYPoolCString(pool, context, name));
1796 if (class_getProperty(_class, string) != NULL)
1800 if (CYHasImplicitProperties(_class))
1801 if (SEL sel = sel_getUid(string))
1802 if (CYImplements(self, _class, sel, true))
1808 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1809 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1810 id self(internal->GetValue());
1812 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1813 return Internal::Make(context, self, object);
1816 NSString *name(CYCastNSString(&pool, context, property));
1818 if (CYInternal *internal = [CYInternal get:self])
1819 if (JSValueRef value = [internal getProperty:property inContext:context])
1823 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1827 const char *string(CYPoolCString(pool, context, name));
1828 Class _class(object_getClass(self));
1831 if (objc_property_t property = class_getProperty(_class, string)) {
1832 PropertyAttributes attributes(property);
1833 SEL sel(sel_registerName(attributes.Getter()));
1834 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1838 if (CYHasImplicitProperties(_class))
1839 if (SEL sel = sel_getUid(string))
1840 if (CYImplements(self, _class, sel, true))
1841 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1846 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1847 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1848 id self(internal->GetValue());
1852 NSString *name(CYCastNSString(&pool, context, property));
1853 NSObject *data(CYCastNSObject(&pool, context, value));
1856 if ([self cy$setProperty:name to:data])
1858 } CYPoolCatch(false)
1860 const char *string(CYPoolCString(pool, context, name));
1861 Class _class(object_getClass(self));
1864 if (objc_property_t property = class_getProperty(_class, string)) {
1865 PropertyAttributes attributes(property);
1866 if (const char *setter = attributes.Setter()) {
1867 SEL sel(sel_registerName(setter));
1868 JSValueRef arguments[1] = {value};
1869 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1875 size_t length(strlen(string));
1877 char set[length + 5];
1883 if (string[0] != '\0') {
1884 set[3] = toupper(string[0]);
1885 memcpy(set + 4, string + 1, length - 1);
1888 set[length + 3] = ':';
1889 set[length + 4] = '\0';
1891 if (SEL sel = sel_getUid(set))
1892 if (CYImplements(self, _class, sel)) {
1893 JSValueRef arguments[1] = {value};
1894 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1898 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1899 [internal setProperty:property toValue:value inContext:context];
1906 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1907 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1908 id self(internal->GetValue());
1911 NSString *name(CYCastNSString(NULL, context, property));
1912 return [self cy$deleteProperty:name];
1913 } CYPoolCatch(false)
1914 } CYCatch(false) return /*XXX*/ false; }
1916 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1917 const char *name(sel_getName(method_getName(method)));
1918 if (strchr(name, ':') != NULL)
1921 const char *type(method_getTypeEncoding(method));
1922 if (type == NULL || *type == '\0' || *type == 'v')
1925 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1928 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1929 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1930 id self(internal->GetValue());
1933 Class _class(object_getClass(self));
1938 objc_property_t *data(class_copyPropertyList(_class, &size));
1939 for (size_t i(0); i != size; ++i)
1940 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1945 if (CYHasImplicitProperties(_class))
1946 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1947 #if OBJC_API_VERSION >= 2
1949 objc_method **data(class_copyMethodList(current, &size));
1950 for (size_t i(0); i != size; ++i)
1951 Instance_getPropertyNames_message(names, data[i]);
1954 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1955 for (int i(0); i != methods->method_count; ++i)
1956 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1961 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1962 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1963 [self cy$getPropertyNames:names inContext:context];
1967 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1968 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1969 JSObjectRef value(CYMakeInstance(context, [internal->GetValue() alloc], Instance::Uninitialized));
1973 static const char *CYBlockEncoding(NSBlock *self) {
1974 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1975 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1977 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1978 descriptor += sizeof(BlockDescriptor1);
1979 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1980 descriptor += sizeof(BlockDescriptor2);
1981 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1982 return descriptor3->signature;
1985 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1986 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1987 id self(internal->GetValue());
1989 if (const char *encoding = CYBlockEncoding(self)) {
1995 sig::Signature signature;
1996 sig::Parse(pool, &signature, encoding, &Structor_);
1999 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2001 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
2002 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
2003 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
2007 CYThrow("NSBlock without signature field passed arguments");
2011 } CYPoolCatch(NULL);
2016 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
2017 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2018 Class _class(internal->GetValue());
2019 if (!CYIsClass(_class))
2022 if (CYJSValueIsNSObject(context, instance)) {
2023 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2024 // XXX: this isn't always safe
2025 return [linternal->GetValue() isKindOfClass:_class];
2031 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2033 throw CYJSError(context, "incorrect number of arguments to Instance");
2035 id value(CYCastNSObject(&pool, context, arguments[0]));
2037 value = [NSNull null];
2038 return CYCastJSValue(context, [value cy$box]);
2041 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2042 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2045 id self(internal->GetValue());
2046 const char *name(CYPoolCString(pool, context, property));
2048 if (object_getInstanceVariable(self, name, NULL) != NULL)
2054 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2055 length = CYCastDouble(encoding + 1);
2059 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2060 for (size_t i(0); i != size; ++i)
2061 if (ivars[i] == ivar)
2063 else if (ivar_getOffset(ivars[i]) == offset) {
2064 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2065 _assert(encoding != NULL);
2066 _assert(encoding[0] == 'b');
2067 shift += CYCastDouble(encoding + 1);
2072 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2073 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2076 id self(internal->GetValue());
2077 const char *name(CYPoolCString(pool, context, property));
2080 if (strcmp(name, "isa") == 0)
2081 return CYCastJSValue(context, object_getClass(self));
2084 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2085 ptrdiff_t offset(ivar_getOffset(ivar));
2086 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2088 const char *encoding(ivar_getTypeEncoding(ivar));
2089 _assert(encoding != NULL);
2090 _assert(encoding[0] != '\0');
2091 if (encoding[0] == 'b') {
2092 unsigned length, shift;
2093 CYBitField(length, shift, self, ivar, encoding, offset);
2094 _assert(shift + length <= sizeof(uintptr_t) * 8);
2095 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2096 uintptr_t mask((1 << length) - 1);
2097 return CYCastJSValue(context, (field >> shift) & mask);
2099 auto type(new(pool) Type_privateData(encoding));
2100 return CYFromFFI(context, type->type_, type->GetFFI(), data);
2107 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2108 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2111 id self(internal->GetValue());
2112 const char *name(CYPoolCString(pool, context, property));
2114 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2115 ptrdiff_t offset(ivar_getOffset(ivar));
2116 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2118 const char *encoding(ivar_getTypeEncoding(ivar));
2119 _assert(encoding != NULL);
2120 if (encoding[0] == 'b') {
2121 unsigned length, shift;
2122 CYBitField(length, shift, self, ivar, encoding, offset);
2123 _assert(shift + length <= sizeof(uintptr_t) * 8);
2124 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2125 uintptr_t mask((1 << length) - 1);
2126 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2128 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2129 CYPoolFFI(&pool, context, type->type_, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2137 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2138 if (Class super = class_getSuperclass(_class))
2139 Internal_getPropertyNames_(super, names);
2141 #if OBJC_API_VERSION >= 2
2143 objc_ivar **data(class_copyIvarList(_class, &size));
2144 for (size_t i(0); i != size; ++i)
2145 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2148 if (objc_ivar_list *ivars = _class->ivars)
2149 for (int i(0); i != ivars->ivar_count; ++i)
2150 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2154 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2155 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2158 id self(internal->GetValue());
2159 Class _class(object_getClass(self));
2161 Internal_getPropertyNames_(_class, names);
2164 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2165 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2166 return internal->GetOwner();
2169 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2171 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2174 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2176 NSString *name(CYCastNSString(&pool, context, property));
2177 if (Class _class = NSClassFromString(name))
2178 return CYMakeInstance(context, _class, Instance::Permanent);
2183 static Class *CYCopyClassList(size_t &size) {
2184 size = objc_getClassList(NULL, 0);
2185 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2188 size_t writ(objc_getClassList(data, size));
2194 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2206 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2209 if (Class *data = CYCopyClassList(size)) {
2210 for (size_t i(0); i != size; ++i)
2211 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2216 while (Class _class = objc_next_class(&state))
2217 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2221 #if OBJC_API_VERSION >= 2
2222 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2223 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2226 const char *name(CYPoolCString(pool, context, property));
2228 const char **data(objc_copyClassNamesForImage(internal, &size));
2230 for (size_t i(0); i != size; ++i)
2231 if (strcmp(name, data[i]) == 0) {
2232 if (Class _class = objc_getClass(name)) {
2233 value = CYMakeInstance(context, _class, Instance::Permanent);
2244 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2245 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2247 const char **data(objc_copyClassNamesForImage(internal, &size));
2248 for (size_t i(0); i != size; ++i)
2249 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2253 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2255 const char *name(CYPoolCString(pool, context, property));
2257 const char **data(objc_copyImageNames(&size));
2258 for (size_t i(0); i != size; ++i)
2259 if (strcmp(name, data[i]) == 0) {
2268 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2269 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2273 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2275 const char **data(objc_copyImageNames(&size));
2276 for (size_t i(0); i != size; ++i)
2277 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2282 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2284 const char *name(CYPoolCString(pool, context, property));
2285 if (Protocol *protocol = objc_getProtocol(name))
2286 return CYMakeInstance(context, protocol, Instance::Permanent);
2290 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2291 #if OBJC_API_VERSION >= 2
2293 Protocol **data(objc_copyProtocolList(&size));
2294 for (size_t i(0); i != size; ++i)
2295 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2302 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2304 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2306 return CYJSNull(context);
2310 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2311 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2315 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2316 *data = reinterpret_cast<void *>(address);
2317 return KERN_SUCCESS;
2321 std::set<Class> query_;
2322 JSContextRef context_;
2323 JSObjectRef results_;
2326 struct CYObjectStruct {
2330 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2331 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2332 JSContextRef context(choice->context_);
2334 for (unsigned i(0); i != count; ++i) {
2335 vm_range_t &range(ranges[i]);
2336 void *data(reinterpret_cast<void *>(range.address));
2337 size_t size(range.size);
2339 if (size < sizeof(CYObjectStruct))
2342 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2344 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2346 Class isa(reinterpret_cast<Class>(pointers[0]));
2349 std::set<Class>::const_iterator result(choice->query_.find(isa));
2350 if (result == choice->query_.end())
2353 size_t needed(class_getInstanceSize(*result));
2354 // XXX: if (size < needed)
2356 size_t boundary(496);
2360 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2362 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2366 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2368 throw CYJSError(context, "choose() takes a class argument");
2370 CYGarbageCollect(context);
2373 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2375 vm_address_t *zones(NULL);
2377 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2378 _assert(error == KERN_SUCCESS);
2380 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2381 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2384 choice.context_ = context;
2385 choice.results_ = results;
2388 Class *classes(CYCopyClassList(number));
2389 _assert(classes != NULL);
2391 for (size_t i(0); i != number; ++i)
2392 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2393 if (current == _class) {
2394 choice.query_.insert(classes[i]);
2400 for (unsigned i(0); i != size; ++i) {
2401 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2402 if (zone == NULL || zone->introspect == NULL)
2405 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2413 #if defined(__i386__) || defined(__x86_64__)
2414 #define OBJC_MAX_STRUCT_BY_VALUE 8
2415 static int struct_forward_array[] = {
2416 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2417 #elif defined(__arm__)
2418 #define OBJC_MAX_STRUCT_BY_VALUE 1
2419 static int struct_forward_array[] = {
2421 #elif defined(__arm64__)
2424 #error missing objc-runtime-info
2428 static bool stret(ffi_type *ffi_type) {
2429 return ffi_type->type == FFI_TYPE_STRUCT && (
2430 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2431 struct_forward_array[ffi_type->size] != 0
2437 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2441 _class = object_getClass(self);
2445 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2446 imp = method_getImplementation(method);
2447 type = method_getTypeEncoding(method);
2452 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2454 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2455 type = CYPoolCString(pool, context, [method _typeString]);
2463 sig::Signature signature;
2464 sig::Parse(pool, &signature, type, &Structor_);
2466 size_t used(count + 3);
2467 if (used > signature.count) {
2468 sig::Element *elements(new (pool) sig::Element[used]);
2469 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2471 for (size_t index(signature.count); index != used; ++index) {
2472 sig::Element *element(&elements[index]);
2473 element->name = NULL;
2474 element->offset = _not(size_t);
2476 sig::Type *type(new (pool) sig::Type);
2477 memset(type, 0, sizeof(*type));
2478 type->primitive = sig::object_P;
2479 element->type = type;
2482 signature.elements = elements;
2483 signature.count = used;
2487 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2492 if (stret(cif.rtype))
2493 imp = class_getMethodImplementation_stret(_class, _cmd);
2496 imp = class_getMethodImplementation(_class, _cmd);
2498 objc_super super = {self, _class};
2499 imp = objc_msg_lookup_super(&super, _cmd);
2503 void (*function)() = reinterpret_cast<void (*)()>(imp);
2504 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2507 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2509 throw CYJSError(context, "too few arguments to objc_msgSend");
2519 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2520 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2521 self = internal->GetValue();
2522 _class = internal->class_;;
2523 uninitialized = false;
2524 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2525 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2526 self = internal->GetValue();
2528 uninitialized = internal->IsUninitialized();
2530 internal->value_ = nil;
2532 self = CYCastNSObject(&pool, context, arguments[0]);
2534 uninitialized = false;
2538 return CYJSNull(context);
2540 _cmd = CYCastSEL(context, arguments[1]);
2542 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2545 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2546 return $objc_msgSend(context, object, _this, count, arguments);
2549 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2550 JSValueRef setup[count + 2];
2553 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2554 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2557 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2559 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2561 // XXX: handle Instance::Uninitialized?
2562 id self(CYCastNSObject(&pool, context, _this));
2566 setup[1] = &internal->sel_;
2568 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2571 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2573 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2575 id self(CYCastNSObject(&pool, context, arguments[0]));
2576 Class _class(CYCastClass(pool, context, arguments[1]));
2577 return cy::Super::Make(context, self, _class);
2580 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2582 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2584 const char *name(CYPoolCString(pool, context, arguments[0]));
2585 return CYMakeSelector(context, sel_registerName(name));
2588 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2590 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2591 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2592 return CYMakeInstance(context, self);
2595 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2596 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2597 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2600 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2601 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2602 Type_privateData *typical(internal->GetType());
2607 if (typical == NULL) {
2611 type = typical->type_;
2612 ffi = typical->ffi_;
2615 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2618 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2619 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2620 const char *encoding(CYBlockEncoding(internal->GetValue()));
2621 if (encoding == NULL)
2622 return CYJSNull(context);
2623 // XXX: this should be stored on a FunctionInstance private value subclass
2625 sig::Signature signature;
2626 sig::Parse(pool, &signature, encoding, &Structor_);
2627 return CYMakeType(context, &signature);
2630 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2631 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2632 return CYMakeInstance(context, object_getClass(internal->GetValue()), Instance::Permanent);
2635 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2636 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2637 id self(internal->GetValue());
2638 if (!CYIsClass(self))
2639 return CYJSUndefined(context);
2640 return CYGetClassPrototype(context, self);
2643 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2644 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2645 id self(internal->GetValue());
2646 if (!CYIsClass(self))
2647 return CYJSUndefined(context);
2648 return Messages::Make(context, (Class) self);
2651 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2652 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2654 if (!CYJSValueIsNSObject(context, _this))
2657 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2658 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2661 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2662 if (!CYJSValueIsNSObject(context, _this))
2665 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2666 id value(internal->GetValue());
2673 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2675 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2676 return CYJSUndefined(context);
2677 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2680 return CYCastJSValue(context, CYJSString(context, [value description]));
2682 } CYCatch(NULL) return /*XXX*/ NULL; }
2684 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2685 if (!CYJSValueIsNSObject(context, _this))
2688 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2689 id value(internal->GetValue());
2690 _assert(value != nil);
2692 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2695 if (JSValueRef result = [value cy$valueOfInContext:context])
2699 } CYCatch(NULL) return /*XXX*/ NULL; }
2701 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2702 if (!CYJSValueIsNSObject(context, _this))
2705 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2706 // XXX: but... but... THIS ISN'T A POINTER! :(
2707 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2708 } CYCatch(NULL) return /*XXX*/ NULL; }
2710 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2711 if (!CYJSValueIsNSObject(context, _this))
2714 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2715 id value(internal->GetValue());
2718 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2719 return CYCastJSValue(context, CYJSString(context, [value description]));
2721 } CYCatch(NULL) return /*XXX*/ NULL; }
2723 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2724 if (!CYJSValueIsNSObject(context, _this))
2727 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2728 id value(internal->GetValue());
2730 if (!CYIsClass(value))
2731 CYThrow("non-Class object cannot be used as Type");
2734 memset(&type, 0, sizeof(type));
2735 type.primitive = sig::object_P;
2736 type.name = class_getName(value);
2737 return CYMakeType(context, &type);
2738 } CYCatch(NULL) return /*XXX*/ NULL; }
2740 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2741 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2742 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2745 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2746 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2749 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2750 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2751 const char *name(sel_getName(internal->GetValue()));
2754 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2755 return CYCastJSValue(context, CYJSString(context, string));
2757 } CYCatch(NULL) return /*XXX*/ NULL; }
2759 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2761 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2764 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2765 SEL sel(internal->GetValue());
2767 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2768 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2769 const char *encoding(method_getTypeEncoding(method));
2771 sig::Signature signature;
2772 sig::Parse(pool, &signature, encoding, &Structor_);
2773 return CYMakeType(context, &signature);
2776 static JSStaticValue Selector_staticValues[2] = {
2777 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2778 {NULL, NULL, NULL, 0}
2781 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2782 static JSStaticValue Instance_staticValues[5] = {
2783 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2784 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2785 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2786 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2787 {NULL, NULL, NULL, 0}
2790 static JSStaticValue FunctionInstance_staticValues[6] = {
2791 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2792 // XXX: this is sadly a duplicate of Instance_staticValues
2793 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2794 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2795 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2796 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2797 {NULL, NULL, NULL, 0}
2800 static JSStaticFunction Instance_staticFunctions[7] = {
2801 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2802 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2803 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2804 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2805 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2806 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2810 static JSStaticFunction Class_staticFunctions[2] = {
2811 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2815 static JSStaticFunction Internal_staticFunctions[2] = {
2816 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2820 static JSStaticFunction Selector_staticFunctions[5] = {
2821 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2822 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2823 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2824 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2829 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2830 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2831 } CYObjectiveCatch }
2834 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2835 CYPool &pool(CYGetGlobalPool());
2837 Object_type = new(pool) Type_privateData(sig::object_P);
2838 Selector_type = new(pool) Type_privateData(sig::selector_P);
2840 NSArray_ = objc_getClass("NSArray");
2841 NSBlock_ = objc_getClass("NSBlock");
2842 NSDictionary_ = objc_getClass("NSDictionary");
2843 NSNumber_ = objc_getClass("NSNumber");
2844 NSString_ = objc_getClass("NSString");
2845 Object_ = objc_getClass("Object");
2848 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2850 // XXX: apparently, iOS now has both of these
2851 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2852 if (NSCFBoolean_ == nil)
2853 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2855 NSCFType_ = objc_getClass("NSCFType");
2857 NSZombie_ = objc_getClass("_NSZombie_");
2859 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2862 JSClassDefinition definition;
2864 definition = kJSClassDefinitionEmpty;
2865 definition.className = "Instance";
2866 definition.staticValues = Instance_staticValues;
2867 definition.staticFunctions = Instance_staticFunctions;
2868 definition.hasProperty = &Instance_hasProperty;
2869 definition.getProperty = &Instance_getProperty;
2870 definition.setProperty = &Instance_setProperty;
2871 definition.deleteProperty = &Instance_deleteProperty;
2872 definition.getPropertyNames = &Instance_getPropertyNames;
2873 definition.callAsConstructor = &Instance_callAsConstructor;
2874 definition.hasInstance = &Instance_hasInstance;
2875 definition.finalize = &CYFinalize;
2876 Instance_ = JSClassCreate(&definition);
2878 definition.className = "ArrayInstance";
2879 ArrayInstance_ = JSClassCreate(&definition);
2881 definition.className = "BooleanInstance";
2882 BooleanInstance_ = JSClassCreate(&definition);
2884 definition.className = "NumberInstance";
2885 NumberInstance_ = JSClassCreate(&definition);
2887 definition.className = "ObjectInstance";
2888 ObjectInstance_ = JSClassCreate(&definition);
2890 definition.className = "StringInstance";
2891 StringInstance_ = JSClassCreate(&definition);
2893 definition.className = "FunctionInstance";
2894 definition.staticValues = FunctionInstance_staticValues;
2895 definition.callAsFunction = &FunctionInstance_callAsFunction;
2896 FunctionInstance_ = JSClassCreate(&definition);
2898 definition = kJSClassDefinitionEmpty;
2899 definition.className = "Class";
2900 definition.staticFunctions = Class_staticFunctions;
2901 Class_ = JSClassCreate(&definition);
2903 definition = kJSClassDefinitionEmpty;
2904 definition.className = "Internal";
2905 definition.staticFunctions = Internal_staticFunctions;
2906 definition.hasProperty = &Internal_hasProperty;
2907 definition.getProperty = &Internal_getProperty;
2908 definition.setProperty = &Internal_setProperty;
2909 definition.getPropertyNames = &Internal_getPropertyNames;
2910 definition.finalize = &CYFinalize;
2911 Internal_ = JSClassCreate(&definition);
2913 definition = kJSClassDefinitionEmpty;
2914 definition.className = "Message";
2915 definition.staticFunctions = cy::Functor::StaticFunctions;
2916 definition.staticValues = cy::Functor::StaticValues;
2917 definition.callAsFunction = &Message_callAsFunction;
2918 definition.finalize = &CYFinalize;
2919 Message_ = JSClassCreate(&definition);
2921 definition = kJSClassDefinitionEmpty;
2922 definition.className = "Messages";
2923 definition.hasProperty = &Messages_hasProperty;
2924 definition.getProperty = &Messages_getProperty;
2925 definition.setProperty = &Messages_setProperty;
2926 #if 0 && OBJC_API_VERSION < 2
2927 definition.deleteProperty = &Messages_deleteProperty;
2929 definition.getPropertyNames = &Messages_getPropertyNames;
2930 definition.finalize = &CYFinalize;
2931 Messages_ = JSClassCreate(&definition);
2933 definition = kJSClassDefinitionEmpty;
2934 definition.className = "Selector";
2935 definition.staticValues = Selector_staticValues;
2936 definition.staticFunctions = Selector_staticFunctions;
2937 definition.callAsFunction = &Selector_callAsFunction;
2938 definition.finalize = &CYFinalize;
2939 Selector_ = JSClassCreate(&definition);
2941 definition = kJSClassDefinitionEmpty;
2942 definition.className = "Super";
2943 definition.staticFunctions = Internal_staticFunctions;
2944 definition.finalize = &CYFinalize;
2945 Super_ = JSClassCreate(&definition);
2947 definition = kJSClassDefinitionEmpty;
2948 definition.className = "ObjectiveC::Classes";
2949 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2950 definition.getProperty = &ObjectiveC_Classes_getProperty;
2951 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2952 ObjectiveC_Classes_ = JSClassCreate(&definition);
2954 definition = kJSClassDefinitionEmpty;
2955 definition.className = "ObjectiveC::Constants";
2956 definition.getProperty = &ObjectiveC_Constants_getProperty;
2957 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2958 ObjectiveC_Constants_ = JSClassCreate(&definition);
2960 #if OBJC_API_VERSION >= 2
2961 definition = kJSClassDefinitionEmpty;
2962 definition.className = "ObjectiveC::Images";
2963 definition.getProperty = &ObjectiveC_Images_getProperty;
2964 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2965 ObjectiveC_Images_ = JSClassCreate(&definition);
2967 definition = kJSClassDefinitionEmpty;
2968 definition.className = "ObjectiveC::Image::Classes";
2969 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2970 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2971 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2974 definition = kJSClassDefinitionEmpty;
2975 definition.className = "ObjectiveC::Protocols";
2976 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2977 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2978 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2981 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2982 // XXX: this is horrible; there has to be a better way to do this
2984 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2986 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2992 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2993 JSObjectRef global(CYGetGlobalObject(context));
2994 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2995 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2996 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2997 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2999 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
3000 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
3002 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3003 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
3004 CYArrayPush(context, alls, protocols);
3006 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
3007 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
3008 CYArrayPush(context, alls, classes);
3010 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
3011 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
3012 CYArrayPush(context, alls, constants);
3014 #if OBJC_API_VERSION >= 2
3015 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3018 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
3019 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3020 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3021 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3022 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
3024 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
3025 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3027 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
3028 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
3029 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
3030 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
3031 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
3033 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
3034 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
3035 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
3036 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
3037 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
3039 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
3040 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
3041 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
3042 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
3043 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
3045 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
3046 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
3047 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
3048 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
3049 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
3051 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3052 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3053 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3054 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3055 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3057 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3058 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3059 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3060 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3061 CYSetPrototype(context, StringInstance_prototype, String_prototype);
3063 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
3064 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
3065 CYSetPrototype(context, Class_prototype, Instance_prototype);
3067 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3068 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3069 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3071 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3072 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3075 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3078 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3080 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3081 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3084 static CYHook CYObjectiveCHook = {
3085 &CYObjectiveC_ExecuteStart,
3086 &CYObjectiveC_ExecuteEnd,
3087 &CYObjectiveC_CallFunction,
3088 &CYObjectiveC_Initialize,
3089 &CYObjectiveC_SetupContext,
3090 &CYObjectiveC_PoolFFI,
3091 &CYObjectiveC_FromFFI,
3094 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3096 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3097 CYSetupContext(context);
3098 } CYObjectiveCatch }
3100 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3103 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3104 CYStream stream(utf8.data, utf8.data + utf8.size);
3105 utf8 = CYPoolCode(pool, stream);
3107 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3108 size_t bytes(utf16.size * sizeof(uint16_t));
3109 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3110 memcpy(copy, utf16.data, bytes);
3114 } catch (const CYException &exception) {
3116 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];