1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2013 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cycript. 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]
133 static void (*$objc_setAssociatedObject)(id object, void *key, id value, objc_AssociationPolicy policy);
134 static id (*$objc_getAssociatedObject)(id object, void *key);
135 static void (*$objc_removeAssociatedObjects)(id object);
139 struct BlockLiteral {
143 void (*invoke)(void *, ...);
147 struct BlockDescriptor1 {
148 unsigned long int reserved;
149 unsigned long int size;
152 struct BlockDescriptor2 {
153 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
154 void (*dispose_helper)(BlockLiteral *src);
157 struct BlockDescriptor3 {
158 const char *signature;
163 BLOCK_DEALLOCATING = 0x0001,
164 BLOCK_REFCOUNT_MASK = 0xfffe,
165 BLOCK_NEEDS_FREE = 1 << 24,
166 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
167 BLOCK_HAS_CTOR = 1 << 26,
168 BLOCK_IS_GC = 1 << 27,
169 BLOCK_IS_GLOBAL = 1 << 28,
170 BLOCK_HAS_STRET = 1 << 29,
171 BLOCK_HAS_SIGNATURE = 1 << 30,
174 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
176 /* Objective-C Pool Release {{{ */
177 void CYPoolRelease_(void *data) {
178 id object(reinterpret_cast<id>(data));
182 id CYPoolRelease_(CYPool *pool, id object) {
185 else if (pool == NULL)
186 return [object autorelease];
188 pool->atexit(CYPoolRelease_);
193 template <typename Type_>
194 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
195 return (Type_) CYPoolRelease_(pool, (id) object);
198 /* Objective-C Strings {{{ */
199 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
200 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
201 char *string(new(pool) char[size]);
202 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
203 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
207 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
209 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
212 return CYCopyJSString(CYPoolCString(pool, context, value));
216 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
219 // XXX: this definition scares me; is anyone using this?!
220 NSString *string([value description]);
221 return CYCopyJSString(context, string);
224 NSString *CYCopyNSString(const CYUTF8String &value) {
226 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
228 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
232 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
234 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
237 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
241 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
242 return CYCopyNSString(context, CYJSString(context, value));
245 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
246 return CYPoolRelease(pool, CYCopyNSString(value));
249 NSString *CYCastNSString(CYPool *pool, SEL sel) {
250 const char *name(sel_getName(sel));
251 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
254 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
255 return CYPoolRelease(pool, CYCopyNSString(context, value));
258 CYUTF8String CYCastUTF8String(NSString *value) {
259 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
260 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
264 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
266 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
267 if (exception == NULL)
269 *exception = CYCastJSValue(context, error);
272 size_t CYGetIndex(NSString *value) {
273 return CYGetIndex(CYCastUTF8String(value));
276 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
277 return CYGetOffset(CYPoolCString(pool, context, value), index);
280 static JSClassRef Instance_;
282 static JSClassRef ArrayInstance_;
283 static JSClassRef BooleanInstance_;
284 static JSClassRef FunctionInstance_;
285 static JSClassRef NumberInstance_;
286 static JSClassRef ObjectInstance_;
287 static JSClassRef StringInstance_;
289 static JSClassRef Class_;
290 static JSClassRef Internal_;
291 static JSClassRef Message_;
292 static JSClassRef Messages_;
293 static JSClassRef Selector_;
294 static JSClassRef Super_;
296 static JSClassRef ObjectiveC_Classes_;
297 static JSClassRef ObjectiveC_Constants_;
298 static JSClassRef ObjectiveC_Protocols_;
301 static JSClassRef ObjectiveC_Image_Classes_;
302 static JSClassRef ObjectiveC_Images_;
306 static Class __NSMallocBlock__;
307 static Class NSCFBoolean_;
308 static Class NSCFType_;
309 static Class NSGenericDeallocHandler_;
310 static Class NSZombie_;
312 static std::set<Class> banned_;
314 static Class NSBoolNumber_;
317 static Class NSArray_;
318 static Class NSBlock_;
319 static Class NSDictionary_;
320 static Class NSNumber_;
321 static Class NSString_;
322 static Class Object_;
324 static Type_privateData *Object_type;
325 static Type_privateData *Selector_type;
327 Type_privateData *Instance::GetType() const {
331 Type_privateData *Selector_privateData::GetType() const {
332 return Selector_type;
335 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
337 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
339 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
340 else if (meta && !class_isMetaClass(self))
341 return CYGetCachedObject(context, CYJSString("Class_prototype"));
343 JSObjectRef global(CYGetGlobalObject(context));
344 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
347 sprintf(label, "i%p", self);
348 CYJSString name(label);
350 JSValueRef value(CYGetProperty(context, cy, name));
351 if (!JSValueIsUndefined(context, value))
354 JSClassRef _class(NULL);
355 JSValueRef prototype;
358 if (self == NSCFBoolean_)
360 if (self == NSBoolNumber_)
362 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
363 else if (self == NSArray_)
364 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
365 else if (self == NSBlock_)
366 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
367 else if (self == NSNumber_)
368 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
369 else if (self == NSDictionary_)
370 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
371 else if (self == NSString_)
372 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
374 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
376 JSObjectRef object(JSObjectMake(context, _class, NULL));
377 CYSetPrototype(context, object, prototype);
378 CYSetProperty(context, cy, name, object);
383 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
384 return CYGetClassPrototype(context, self, class_isMetaClass(self));
387 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
388 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
389 if (Class super = class_getSuperclass(_class))
390 CYSetPrototype(context, value, Messages::Make(context, super));
394 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
395 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
399 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
400 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
404 bool CYIsKindOfClass(id object, Class _class) {
405 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
411 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
412 JSObjectRef value(JSObjectMake(context, CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance_, new Instance(object, flags)));
413 CYSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
417 Instance::~Instance() {
418 if ((flags_ & Transient) == 0)
419 [GetValue() release];
422 struct Message_privateData :
427 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
428 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
434 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
435 Instance::Flags flags;
438 flags = Instance::Transient;
440 flags = Instance::None;
441 object = [object retain];
444 return Instance::Make(context, object, flags);
447 @interface NSMethodSignature (Cycript)
448 - (NSString *) _typeString;
451 @interface NSObject (Cycript)
453 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
454 - (JSType) cy$JSType;
456 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
457 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
459 - (bool) cy$hasProperty:(NSString *)name;
460 - (NSObject *) cy$getProperty:(NSString *)name;
461 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
462 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
463 - (bool) cy$deleteProperty:(NSString *)name;
464 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
466 + (bool) cy$hasImplicitProperties;
472 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
475 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
481 Class _class(object_getClass(value));
482 SEL sel(@selector(cy$toCYON:inSet:));
484 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
485 string = reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
486 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
487 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
488 string = [value cy$toCYON:objective inSet:objects];
493 else if (value == NSZombie_)
494 string = @"_NSZombie_";
495 else if (_class == NSZombie_)
496 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
497 // XXX: frowny /in/ the pants
498 else if (banned_.find(value) != banned_.end())
502 string = [NSString stringWithFormat:@"%@", value];
507 string = @"undefined";
513 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
515 return CYCastNSCYON(value, objective, *objects);
517 std::set<void *> objects;
518 return CYCastNSCYON(value, objective, objects);
523 struct PropertyAttributes {
528 const char *variable;
541 PropertyAttributes(objc_property_t property) :
553 name = property_getName(property);
554 const char *attributes(property_getAttributes(property));
556 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
557 if ((next = strchr(token, ',')) != NULL)
560 case 'R': readonly = true; break;
561 case 'C': copy = true; break;
562 case '&': retain = true; break;
563 case 'N': nonatomic = true; break;
564 case 'G': getter_ = token + 1; break;
565 case 'S': setter_ = token + 1; break;
566 case 'V': variable = token + 1; break;
570 /*if (variable == NULL) {
571 variable = property_getName(property);
572 size_t size(strlen(variable));
573 char *name(new(pool_) char[size + 2]);
575 memcpy(name + 1, variable, size);
576 name[size + 1] = '\0';
581 const char *Getter() {
583 getter_ = pool_.strdup(name);
587 const char *Setter() {
588 if (setter_ == NULL && !readonly) {
589 size_t length(strlen(name));
591 char *temp(new(pool_) char[length + 5]);
597 temp[3] = toupper(name[0]);
598 memcpy(temp + 4, name + 1, length - 1);
601 temp[length + 3] = ':';
602 temp[length + 4] = '\0';
612 @interface CYWebUndefined : NSObject {
615 + (CYWebUndefined *) undefined;
619 @implementation CYWebUndefined
621 + (CYWebUndefined *) undefined {
622 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
628 #define WebUndefined CYWebUndefined
630 /* Bridge: CYJSObject {{{ */
631 @interface CYJSObject : NSMutableDictionary {
633 JSGlobalContextRef context_;
636 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
638 - (NSUInteger) count;
639 - (id) objectForKey:(id)key;
640 - (NSEnumerator *) keyEnumerator;
641 - (void) setObject:(id)object forKey:(id)key;
642 - (void) removeObjectForKey:(id)key;
646 /* Bridge: CYJSArray {{{ */
647 @interface CYJSArray : NSMutableArray {
649 JSGlobalContextRef context_;
652 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
654 - (NSUInteger) count;
655 - (id) objectAtIndex:(NSUInteger)index;
657 - (void) addObject:(id)anObject;
658 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
659 - (void) removeLastObject;
660 - (void) removeObjectAtIndex:(NSUInteger)index;
661 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
666 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
667 return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
670 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
671 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
674 struct CYBlockDescriptor {
676 BlockDescriptor1 one_;
677 BlockDescriptor2 two_;
678 BlockDescriptor3 three_;
681 Closure_privateData *internal_;
684 void CYDisposeBlock(BlockLiteral *literal) {
685 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
688 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
689 JSObjectRef _this(CYCastJSObject(context, values[0]));
690 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
693 static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
694 CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
697 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
698 _assert(__NSMallocBlock__ != Nil);
699 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
701 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
702 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
704 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
705 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
707 literal->isa = __NSMallocBlock__;
708 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
709 literal->reserved = 0;
710 literal->descriptor = descriptor;
712 descriptor->d_.one_.size = sizeof(descriptor->d_);
713 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
714 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
716 return reinterpret_cast<NSBlock *>(literal);
719 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
720 if (CYJSValueIsNSObject(context, object)) {
721 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
722 return internal->GetValue();
725 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
726 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
727 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
730 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
731 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
735 @interface NSBoolNumber : NSNumber {
740 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
744 switch (JSType type = JSValueGetType(context, value)) {
745 case kJSTypeUndefined:
746 object = [WebUndefined undefined];
756 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
759 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
765 object = CYCopyNSNumber(context, value);
770 object = CYCopyNSString(context, value);
775 // XXX: this might could be more efficient
776 object = CYCastNSObject(pool, context, (JSObjectRef) value);
781 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
788 return CYPoolRelease(pool, object);
790 return [object retain];
793 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
794 return CYNSObject(pool, context, value, true);
797 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
798 return CYNSObject(&pool, context, value, false);
801 /* Bridge: NSArray {{{ */
802 @implementation NSArray (Cycript)
805 return [[self mutableCopy] autorelease];
808 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
809 _oassert(objects.insert(self).second);
811 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
812 [json appendString:@"@["];
816 for (id object in self) {
818 for (size_t index(0), count([self count]); index != count; ++index) {
819 id object([self objectAtIndex:index]);
822 [json appendString:@","];
825 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
826 [json appendString:CYCastNSCYON(object, true, objects)];
828 [json appendString:@","];
833 [json appendString:@"]"];
837 - (bool) cy$hasProperty:(NSString *)name {
838 if ([name isEqualToString:@"length"])
841 size_t index(CYGetIndex(name));
842 if (index == _not(size_t) || index >= [self count])
843 return [super cy$hasProperty:name];
848 - (NSObject *) cy$getProperty:(NSString *)name {
849 size_t index(CYGetIndex(name));
850 if (index == _not(size_t) || index >= [self count])
851 return [super cy$getProperty:name];
853 return [self objectAtIndex:index];
856 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
858 if ([name isEqualToString:@"length"])
859 return CYCastJSValue(context, [self count]);
862 return [super cy$getProperty:name inContext:context];
865 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
866 [super cy$getPropertyNames:names inContext:context];
868 for (size_t index(0), count([self count]); index != count; ++index) {
869 id object([self objectAtIndex:index]);
870 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
872 sprintf(name, "%zu", index);
873 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
878 + (bool) cy$hasImplicitProperties {
884 /* Bridge: NSBlock {{{ */
891 /* Bridge: NSBoolNumber {{{ */
893 @implementation NSBoolNumber (Cycript)
895 - (JSType) cy$JSType {
896 return kJSTypeBoolean;
899 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
900 NSString *value([self boolValue] ? @"true" : @"false");
901 return objective ? value : [NSString stringWithFormat:@"@%@", value];
904 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
905 return CYCastJSValue(context, (bool) [self boolValue]);
911 /* Bridge: NSDictionary {{{ */
912 @implementation NSDictionary (Cycript)
915 return [[self mutableCopy] autorelease];
918 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
919 _oassert(objects.insert(self).second);
921 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
922 [json appendString:@"@{"];
926 for (NSObject *key in self) {
928 NSEnumerator *keys([self keyEnumerator]);
929 while (NSObject *key = [keys nextObject]) {
932 [json appendString:@","];
935 [json appendString:CYCastNSCYON(key, true, objects)];
936 [json appendString:@":"];
937 NSObject *object([self objectForKey:key]);
938 [json appendString:CYCastNSCYON(object, true, objects)];
941 [json appendString:@"}"];
945 - (bool) cy$hasProperty:(NSString *)name {
946 return [self objectForKey:name] != nil;
949 - (NSObject *) cy$getProperty:(NSString *)name {
950 return [self objectForKey:name];
953 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
954 [super cy$getPropertyNames:names inContext:context];
957 for (NSObject *key in self) {
959 NSEnumerator *keys([self keyEnumerator]);
960 while (NSObject *key = [keys nextObject]) {
962 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
966 + (bool) cy$hasImplicitProperties {
972 /* Bridge: NSMutableArray {{{ */
973 @implementation NSMutableArray (Cycript)
975 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
976 if ([name isEqualToString:@"length"]) {
977 // XXX: is this not intelligent?
978 NSNumber *number(reinterpret_cast<NSNumber *>(value));
980 NSUInteger size([number unsignedIntegerValue]);
982 NSUInteger size([number unsignedIntValue]);
984 NSUInteger count([self count]);
986 [self removeObjectsInRange:NSMakeRange(size, count - size)];
987 else if (size != count) {
988 WebUndefined *undefined([WebUndefined undefined]);
989 for (size_t i(count); i != size; ++i)
990 [self addObject:undefined];
995 size_t index(CYGetIndex(name));
996 if (index == _not(size_t))
997 return [super cy$setProperty:name to:value];
999 id object(value ?: [NSNull null]);
1001 size_t count([self count]);
1003 [self replaceObjectAtIndex:index withObject:object];
1005 if (index != count) {
1006 WebUndefined *undefined([WebUndefined undefined]);
1007 for (size_t i(count); i != index; ++i)
1008 [self addObject:undefined];
1011 [self addObject:object];
1017 - (bool) cy$deleteProperty:(NSString *)name {
1018 size_t index(CYGetIndex(name));
1019 if (index == _not(size_t) || index >= [self count])
1020 return [super cy$deleteProperty:name];
1021 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1027 /* Bridge: NSMutableDictionary {{{ */
1028 @implementation NSMutableDictionary (Cycript)
1030 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1031 [self setObject:(value ?: [NSNull null]) forKey:name];
1035 - (bool) cy$deleteProperty:(NSString *)name {
1036 if ([self objectForKey:name] == nil)
1039 [self removeObjectForKey:name];
1046 /* Bridge: NSNumber {{{ */
1047 @implementation NSNumber (Cycript)
1049 - (JSType) cy$JSType {
1051 // XXX: this just seems stupid
1052 if ([self class] == NSCFBoolean_)
1053 return kJSTypeBoolean;
1055 return kJSTypeNumber;
1058 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1059 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1060 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1063 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1064 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1065 } CYObjectiveCatch }
1069 /* Bridge: NSNull {{{ */
1070 @implementation NSNull (Cycript)
1072 - (JSType) cy$JSType {
1076 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1077 NSString *value(@"null");
1078 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1081 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1082 return CYJSNull(context);
1083 } CYObjectiveCatch }
1087 /* Bridge: NSObject {{{ */
1088 @implementation NSObject (Cycript)
1094 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1095 return [self cy$valueOfInContext:context];
1098 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1100 } CYObjectiveCatch }
1102 - (JSType) cy$JSType {
1103 return kJSTypeObject;
1106 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1107 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1110 - (bool) cy$hasProperty:(NSString *)name {
1114 - (NSObject *) cy$getProperty:(NSString *)name {
1118 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1119 if (NSObject *value = [self cy$getProperty:name])
1120 return CYCastJSValue(context, value);
1122 } CYObjectiveCatch }
1124 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1128 - (bool) cy$deleteProperty:(NSString *)name {
1132 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1135 + (bool) cy$hasImplicitProperties {
1141 /* Bridge: NSProxy {{{ */
1142 @implementation NSProxy (Cycript)
1144 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1145 return [[self description] cy$toCYON:objective inSet:objects];
1150 /* Bridge: NSSet {{{ */
1151 @implementation NSSet (Cycript)
1153 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1154 _oassert(objects.insert(self).second);
1156 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1157 [json appendString:@"[NSSet setWithArray:"];
1158 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1159 [json appendString:@"]]"];
1165 /* Bridge: NSString {{{ */
1166 @implementation NSString (Cycript)
1169 return [[self copy] autorelease];
1172 - (JSType) cy$JSType {
1173 return kJSTypeString;
1176 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1177 std::ostringstream str;
1180 CYUTF8String string(CYCastUTF8String(self));
1181 CYStringify(str, string.data, string.size);
1182 std::string value(str.str());
1183 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1186 - (bool) cy$hasProperty:(NSString *)name {
1187 size_t index(CYGetIndex(name));
1188 if (index == _not(size_t) || index >= [self length])
1189 return [super cy$hasProperty:name];
1194 - (NSObject *) cy$getProperty:(NSString *)name {
1195 size_t index(CYGetIndex(name));
1196 if (index == _not(size_t) || index >= [self length])
1197 return [super cy$getProperty:name];
1199 return [self substringWithRange:NSMakeRange(index, 1)];
1202 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1203 [super cy$getPropertyNames:names inContext:context];
1205 for (size_t index(0), length([self length]); index != length; ++index) {
1207 sprintf(name, "%zu", index);
1208 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1212 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1213 return CYCastJSValue(context, CYJSString(context, self));
1214 } CYObjectiveCatch }
1218 /* Bridge: WebUndefined {{{ */
1219 @implementation WebUndefined (Cycript)
1221 - (JSType) cy$JSType {
1222 return kJSTypeUndefined;
1225 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1226 NSString *value(@"undefined");
1227 return value; // XXX: maybe use the below code, adding @undefined?
1228 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1231 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1232 return CYJSUndefined(context);
1233 } CYObjectiveCatch }
1238 static bool CYIsClass(id self) {
1240 return class_isMetaClass(object_getClass(self));
1242 return GSObjCIsClass(self);
1246 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1247 id self(CYCastNSObject(&pool, context, value));
1248 if (CYIsClass(self))
1249 return (Class) self;
1250 throw CYJSError(context, "got something that is not a Class");
1254 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1256 size_t size(JSPropertyNameArrayGetCount(names));
1257 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1258 for (size_t index(0); index != size; ++index)
1259 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1263 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1265 return CYJSNull(context);
1267 return CYMakeInstance(context, value, false);
1268 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1270 @implementation CYJSObject
1272 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1273 if ((self = [super init]) != nil) {
1275 context_ = CYGetJSContext(context);
1276 JSGlobalContextRetain(context_);
1277 JSValueProtect(context_, object_);
1279 } CYObjectiveCatch }
1281 - (void) dealloc { CYObjectiveTry {
1282 JSValueUnprotect(context_, object_);
1283 JSGlobalContextRelease(context_);
1285 } CYObjectiveCatch }
1287 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1289 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1291 return [super cy$toCYON:objective inSet:objects];
1293 return [NSString stringWithUTF8String:cyon];
1294 } CYObjectiveCatch }
1296 - (NSUInteger) count { CYObjectiveTry {
1297 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1298 size_t size(JSPropertyNameArrayGetCount(names));
1299 JSPropertyNameArrayRelease(names);
1301 } CYObjectiveCatch }
1303 - (id) objectForKey:(id)key { CYObjectiveTry {
1304 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1305 if (JSValueIsUndefined(context, value))
1307 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1308 } CYObjectiveCatch }
1310 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1311 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1312 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1313 JSPropertyNameArrayRelease(names);
1315 } CYObjectiveCatch }
1317 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1318 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1319 } CYObjectiveCatch }
1321 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1322 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1323 } CYObjectiveCatch }
1327 @implementation CYJSArray
1329 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1331 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1332 } CYObjectiveCatch }
1334 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1335 if ((self = [super init]) != nil) {
1337 context_ = CYGetJSContext(context);
1338 JSGlobalContextRetain(context_);
1339 JSValueProtect(context_, object_);
1341 } CYObjectiveCatch }
1343 - (void) dealloc { CYObjectiveTry {
1344 JSValueUnprotect(context_, object_);
1345 JSGlobalContextRelease(context_);
1347 } CYObjectiveCatch }
1349 - (NSUInteger) count { CYObjectiveTry {
1350 return CYArrayLength(context, object_);
1351 } CYObjectiveCatch }
1353 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1354 size_t bounds([self count]);
1355 if (index >= bounds)
1356 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1357 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1358 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1359 } CYObjectiveCatch }
1361 - (void) addObject:(id)object { CYObjectiveTry {
1362 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1363 } CYObjectiveCatch }
1365 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1366 size_t bounds([self count] + 1);
1367 if (index >= bounds)
1368 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1369 JSValueRef arguments[3];
1370 arguments[0] = CYCastJSValue(context, index);
1371 arguments[1] = CYCastJSValue(context, 0);
1372 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1373 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1374 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1375 } CYObjectiveCatch }
1377 - (void) removeLastObject { CYObjectiveTry {
1378 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1379 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1380 } CYObjectiveCatch }
1382 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1383 size_t bounds([self count]);
1384 if (index >= bounds)
1385 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1386 JSValueRef arguments[2];
1387 arguments[0] = CYCastJSValue(context, index);
1388 arguments[1] = CYCastJSValue(context, 1);
1389 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1390 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1391 } CYObjectiveCatch }
1393 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1394 size_t bounds([self count]);
1395 if (index >= bounds)
1396 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1397 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1398 } CYObjectiveCatch }
1402 // XXX: inherit from or replace with CYJSObject
1403 @interface CYInternal : NSObject {
1404 JSGlobalContextRef context_;
1405 JSObjectRef object_;
1410 @implementation CYInternal
1412 - (void) dealloc { CYObjectiveTry {
1413 JSValueUnprotect(context_, object_);
1414 JSGlobalContextRelease(context_);
1416 } CYObjectiveCatch }
1418 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1419 if ((self = [super init]) != nil) {
1420 context_ = CYGetJSContext(context);
1421 JSGlobalContextRetain(context_);
1423 } CYObjectiveCatch }
1425 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1426 if (object_ == NULL)
1429 return JSObjectHasProperty(context, object_, name);
1432 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1433 if (object_ == NULL)
1436 return CYGetProperty(context, object_, name);
1439 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1440 @synchronized (self) {
1441 if (object_ == NULL) {
1442 object_ = JSObjectMake(context, NULL, NULL);
1443 JSValueProtect(context, object_);
1447 CYSetProperty(context, object_, name, value);
1450 + (CYInternal *) get:(id)object {
1451 if ($objc_getAssociatedObject == NULL)
1454 @synchronized (object) {
1455 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1462 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1463 if ($objc_getAssociatedObject == NULL)
1466 @synchronized (object) {
1467 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1470 if ($objc_setAssociatedObject == NULL)
1473 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1474 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1483 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1484 Selector_privateData *internal(new Selector_privateData(sel));
1485 return JSObjectMake(context, Selector_, internal);
1488 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1489 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1490 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1491 return reinterpret_cast<SEL>(internal->value_);
1494 return sel_registerName(CYPoolCString(pool, context, value));
1498 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1499 return (void *) [[NSAutoreleasePool alloc] init];
1500 } CYSadCatch(NULL) }
1502 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1503 return [(NSAutoreleasePool *) handle release];
1506 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1508 return Instance::Make(context, nil);
1509 if (Class _class = objc_getClass(name.data))
1510 return CYMakeInstance(context, _class, true);
1511 if (Protocol *protocol = objc_getProtocol(name.data))
1512 return CYMakeInstance(context, protocol, true);
1514 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1516 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1517 ffi_call(cif, function, value, values);
1520 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, sig::Signature *signature) {
1521 if (JSValueIsNull(context, value))
1523 JSObjectRef object(CYCastJSObject(context, value));
1525 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1526 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1528 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1529 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1533 _assert(JSObjectIsFunction(context, object));
1535 _assert(signature != NULL);
1536 _assert(signature->count != 0);
1538 sig::Signature modified;
1539 modified.count = signature->count + 1;
1540 modified.elements = new(pool) sig::Element[modified.count];
1542 modified.elements[0] = signature->elements[0];
1543 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1545 modified.elements[1].name = NULL;
1546 modified.elements[1].type = new(pool) sig::Type();
1547 modified.elements[1].offset = _not(size_t);
1549 memset(modified.elements[1].type, 0, sizeof(sig::Type));
1550 modified.elements[1].type->primitive = sig::object_P;
1552 return CYMakeBlock(context, object, modified);
1555 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1556 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1558 switch (type->primitive) {
1560 // XXX: this function might not handle the idea of a null pool
1561 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &type->data.signature);
1565 case sig::typename_P:
1566 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1569 case sig::selector_P:
1570 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1578 } CYSadCatch(false) }
1580 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1581 switch (type->primitive) {
1582 // XXX: do something epic about blocks
1585 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1586 JSValueRef value(CYCastJSValue(context, object));
1592 case sig::typename_P:
1593 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1595 case sig::selector_P:
1596 if (SEL sel = *reinterpret_cast<SEL *>(data))
1597 return CYMakeSelector(context, sel);
1601 return CYJSNull(context);
1605 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1607 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1608 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1611 #if OBJC_API_VERSION >= 2
1613 method_getReturnType(method, type, sizeof(type));
1615 const char *type(method_getTypeEncoding(method));
1621 // XXX: possibly use a more "awesome" check?
1625 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1626 JSObjectRef _this(CYCastJSObject(context, values[0]));
1627 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1630 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1631 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1634 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1635 Message_privateData *internal(new Message_privateData(sel, type, imp));
1636 return JSObjectMake(context, Message_, internal);
1639 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1640 JSObjectRef function(CYCastJSObject(context, value));
1642 sig::Signature signature;
1643 sig::Parse(pool, &signature, encoding, &Structor_);
1644 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageClosure_));
1645 // XXX: see notes in Library.cpp about needing to leak
1646 return reinterpret_cast<IMP>(internal->GetValue());
1649 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1650 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1651 Class _class(internal->GetValue());
1654 const char *name(CYPoolCString(pool, context, property));
1656 if (SEL sel = sel_getUid(name))
1657 if (class_getInstanceMethod(_class, sel) != NULL)
1663 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1664 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1665 Class _class(internal->GetValue());
1668 const char *name(CYPoolCString(pool, context, property));
1670 if (SEL sel = sel_getUid(name))
1671 if (objc_method *method = class_getInstanceMethod(_class, sel))
1672 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1677 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1678 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1679 Class _class(internal->GetValue());
1682 const char *name(CYPoolCString(pool, context, property));
1683 SEL sel(sel_registerName(name));
1688 if (JSValueIsObjectOfClass(context, value, Message_)) {
1689 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1690 type = sig::Unparse(pool, &message->signature_);
1691 imp = reinterpret_cast<IMP>(message->GetValue());
1692 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1693 type = method_getTypeEncoding(method);
1694 imp = CYMakeMessage(context, value, type);
1695 } else _assert(false);
1697 objc_method *method(NULL);
1698 #if OBJC_API_VERSION >= 2
1700 objc_method **methods(class_copyMethodList(_class, &size));
1701 for (size_t i(0); i != size; ++i)
1702 if (sel_isEqual(method_getName(methods[i]), sel)) {
1703 method = methods[i];
1708 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1709 for (int i(0); i != methods->method_count; ++i)
1710 if (sel_isEqual(method_getName(&methods->method_list[i]), sel)) {
1711 method = &methods->method_list[i];
1717 method_setImplementation(method, imp);
1720 GSMethodList list(GSAllocMethodList(1));
1721 GSAppendMethodToList(list, sel, type, imp, YES);
1722 GSAddMethodList(_class, list, YES);
1723 GSFlushMethodCacheForClass(_class);
1725 class_addMethod(_class, sel, imp, type);
1732 #if 0 && OBJC_API_VERSION < 2
1733 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1734 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1735 Class _class(internal->GetValue());
1738 const char *name(CYPoolCString(pool, context, property));
1740 if (SEL sel = sel_getUid(name))
1741 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1742 objc_method_list list = {NULL, 1, {method}};
1743 class_removeMethods(_class, &list);
1751 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1752 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1753 Class _class(internal->GetValue());
1755 #if OBJC_API_VERSION >= 2
1757 objc_method **data(class_copyMethodList(_class, &size));
1758 for (size_t i(0); i != size; ++i)
1759 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1762 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1763 for (int i(0); i != methods->method_count; ++i)
1764 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1768 static bool CYHasImplicitProperties(Class _class) {
1769 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1770 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1772 return [_class cy$hasImplicitProperties];
1775 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1776 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1777 id self(internal->GetValue());
1779 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1783 NSString *name(CYCastNSString(&pool, context, property));
1785 if (CYInternal *internal = [CYInternal get:self])
1786 if ([internal hasProperty:property inContext:context])
1789 Class _class(object_getClass(self));
1792 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1793 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1794 if ([self cy$hasProperty:name])
1796 } CYPoolCatch(false)
1798 const char *string(CYPoolCString(pool, context, name));
1801 if (class_getProperty(_class, string) != NULL)
1805 if (CYHasImplicitProperties(_class))
1806 if (SEL sel = sel_getUid(string))
1807 if (CYImplements(self, _class, sel, true))
1813 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1814 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1815 id self(internal->GetValue());
1817 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1818 return Internal::Make(context, self, object);
1821 NSString *name(CYCastNSString(&pool, context, property));
1823 if (CYInternal *internal = [CYInternal get:self])
1824 if (JSValueRef value = [internal getProperty:property inContext:context])
1828 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1832 const char *string(CYPoolCString(pool, context, name));
1833 Class _class(object_getClass(self));
1836 if (objc_property_t property = class_getProperty(_class, string)) {
1837 PropertyAttributes attributes(property);
1838 SEL sel(sel_registerName(attributes.Getter()));
1839 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1843 if (CYHasImplicitProperties(_class))
1844 if (SEL sel = sel_getUid(string))
1845 if (CYImplements(self, _class, sel, true))
1846 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1851 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1852 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1853 id self(internal->GetValue());
1857 NSString *name(CYCastNSString(&pool, context, property));
1858 NSObject *data(CYCastNSObject(&pool, context, value));
1861 if ([self cy$setProperty:name to:data])
1863 } CYPoolCatch(false)
1865 const char *string(CYPoolCString(pool, context, name));
1866 Class _class(object_getClass(self));
1869 if (objc_property_t property = class_getProperty(_class, string)) {
1870 PropertyAttributes attributes(property);
1871 if (const char *setter = attributes.Setter()) {
1872 SEL sel(sel_registerName(setter));
1873 JSValueRef arguments[1] = {value};
1874 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1880 size_t length(strlen(string));
1882 char set[length + 5];
1888 if (string[0] != '\0') {
1889 set[3] = toupper(string[0]);
1890 memcpy(set + 4, string + 1, length - 1);
1893 set[length + 3] = ':';
1894 set[length + 4] = '\0';
1896 if (SEL sel = sel_getUid(set))
1897 if (CYImplements(self, _class, sel)) {
1898 JSValueRef arguments[1] = {value};
1899 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1903 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1904 [internal setProperty:property toValue:value inContext:context];
1911 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1912 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1913 id self(internal->GetValue());
1916 NSString *name(CYCastNSString(NULL, context, property));
1917 return [self cy$deleteProperty:name];
1918 } CYPoolCatch(false)
1919 } CYCatch(false) return /*XXX*/ false; }
1921 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1922 const char *name(sel_getName(method_getName(method)));
1923 if (strchr(name, ':') != NULL)
1926 const char *type(method_getTypeEncoding(method));
1927 if (type == NULL || *type == '\0' || *type == 'v')
1930 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1933 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1934 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1935 id self(internal->GetValue());
1938 Class _class(object_getClass(self));
1943 objc_property_t *data(class_copyPropertyList(_class, &size));
1944 for (size_t i(0); i != size; ++i)
1945 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1950 if (CYHasImplicitProperties(_class))
1951 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1952 #if OBJC_API_VERSION >= 2
1954 objc_method **data(class_copyMethodList(current, &size));
1955 for (size_t i(0); i != size; ++i)
1956 Instance_getPropertyNames_message(names, data[i]);
1959 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1960 for (int i(0); i != methods->method_count; ++i)
1961 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1966 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1967 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1968 [self cy$getPropertyNames:names inContext:context];
1972 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1973 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1974 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1978 static const char *CYBlockEncoding(NSBlock *self) {
1979 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1980 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1982 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1983 descriptor += sizeof(BlockDescriptor1);
1984 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1985 descriptor += sizeof(BlockDescriptor2);
1986 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1987 return descriptor3->signature;
1990 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1991 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1992 id self(internal->GetValue());
1994 if (const char *encoding = CYBlockEncoding(self)) {
2000 sig::Signature signature;
2001 sig::Parse(pool, &signature, encoding, &Structor_);
2004 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2006 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
2007 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
2008 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
2012 CYThrow("NSBlock without signature field passed arguments");
2016 } CYPoolCatch(NULL);
2021 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
2022 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2023 Class _class(internal->GetValue());
2024 if (!CYIsClass(_class))
2027 if (CYJSValueIsNSObject(context, instance)) {
2028 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2029 // XXX: this isn't always safe
2030 return [linternal->GetValue() isKindOfClass:_class];
2036 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2038 throw CYJSError(context, "incorrect number of arguments to Instance");
2040 id value(CYCastNSObject(&pool, context, arguments[0]));
2042 value = [NSNull null];
2043 return CYCastJSValue(context, [value cy$box]);
2046 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2047 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2050 id self(internal->GetValue());
2051 const char *name(CYPoolCString(pool, context, property));
2053 if (object_getInstanceVariable(self, name, NULL) != NULL)
2059 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2060 length = CYCastDouble(encoding + 1);
2064 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2065 for (size_t i(0); i != size; ++i)
2066 if (ivars[i] == ivar)
2068 else if (ivar_getOffset(ivars[i]) == offset) {
2069 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2070 _assert(encoding != NULL);
2071 _assert(encoding[0] == 'b');
2072 shift += CYCastDouble(encoding + 1);
2077 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2078 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2081 id self(internal->GetValue());
2082 const char *name(CYPoolCString(pool, context, property));
2085 if (strcmp(name, "isa") == 0)
2086 return CYCastJSValue(context, object_getClass(self));
2089 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2090 ptrdiff_t offset(ivar_getOffset(ivar));
2091 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2093 const char *encoding(ivar_getTypeEncoding(ivar));
2094 _assert(encoding != NULL);
2095 if (encoding[0] == 'b') {
2096 unsigned length, shift;
2097 CYBitField(length, shift, self, ivar, encoding, offset);
2098 _assert(shift + length <= sizeof(uintptr_t) * 8);
2099 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2100 uintptr_t mask((1 << length) - 1);
2101 return CYCastJSValue(context, (field >> shift) & mask);
2103 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2104 return CYFromFFI(context, type.type_, type.GetFFI(), data);
2111 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2112 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2115 id self(internal->GetValue());
2116 const char *name(CYPoolCString(pool, context, property));
2118 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2119 ptrdiff_t offset(ivar_getOffset(ivar));
2120 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2122 const char *encoding(ivar_getTypeEncoding(ivar));
2123 _assert(encoding != NULL);
2124 if (encoding[0] == 'b') {
2125 unsigned length, shift;
2126 CYBitField(length, shift, self, ivar, encoding, offset);
2127 _assert(shift + length <= sizeof(uintptr_t) * 8);
2128 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2129 uintptr_t mask((1 << length) - 1);
2130 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2132 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2133 CYPoolFFI(&pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2141 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2142 if (Class super = class_getSuperclass(_class))
2143 Internal_getPropertyNames_(super, names);
2145 #if OBJC_API_VERSION >= 2
2147 objc_ivar **data(class_copyIvarList(_class, &size));
2148 for (size_t i(0); i != size; ++i)
2149 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2152 if (objc_ivar_list *ivars = _class->ivars)
2153 for (int i(0); i != ivars->ivar_count; ++i)
2154 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2158 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2159 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2162 id self(internal->GetValue());
2163 Class _class(object_getClass(self));
2165 Internal_getPropertyNames_(_class, names);
2168 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2169 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2170 return internal->GetOwner();
2173 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2175 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2178 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2180 NSString *name(CYCastNSString(&pool, context, property));
2181 if (Class _class = NSClassFromString(name))
2182 return CYMakeInstance(context, _class, true);
2187 static Class *CYCopyClassList(size_t &size) {
2188 size = objc_getClassList(NULL, 0);
2189 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2192 size_t writ(objc_getClassList(data, size));
2198 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2210 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2213 if (Class *data = CYCopyClassList(size)) {
2214 for (size_t i(0); i != size; ++i)
2215 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2220 while (Class _class = objc_next_class(&state))
2221 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2225 #if OBJC_API_VERSION >= 2
2226 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2227 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2230 const char *name(CYPoolCString(pool, context, property));
2232 const char **data(objc_copyClassNamesForImage(internal, &size));
2234 for (size_t i(0); i != size; ++i)
2235 if (strcmp(name, data[i]) == 0) {
2236 if (Class _class = objc_getClass(name)) {
2237 value = CYMakeInstance(context, _class, true);
2248 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2249 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2251 const char **data(objc_copyClassNamesForImage(internal, &size));
2252 for (size_t i(0); i != size; ++i)
2253 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2257 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2259 const char *name(CYPoolCString(pool, context, property));
2261 const char **data(objc_copyImageNames(&size));
2262 for (size_t i(0); i != size; ++i)
2263 if (strcmp(name, data[i]) == 0) {
2272 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2273 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2277 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2279 const char **data(objc_copyImageNames(&size));
2280 for (size_t i(0); i != size; ++i)
2281 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2286 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2288 const char *name(CYPoolCString(pool, context, property));
2289 if (Protocol *protocol = objc_getProtocol(name))
2290 return CYMakeInstance(context, protocol, true);
2294 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2295 #if OBJC_API_VERSION >= 2
2297 Protocol **data(objc_copyProtocolList(&size));
2298 for (size_t i(0); i != size; ++i)
2299 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2306 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2308 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2310 return Instance::Make(context, nil);
2314 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2315 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2319 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2320 *data = reinterpret_cast<void *>(address);
2321 return KERN_SUCCESS;
2325 std::set<Class> query_;
2326 JSContextRef context_;
2327 JSObjectRef results_;
2330 struct CYObjectStruct {
2334 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2335 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2336 JSContextRef context(choice->context_);
2338 for (unsigned i(0); i != count; ++i) {
2339 vm_range_t &range(ranges[i]);
2340 void *data(reinterpret_cast<void *>(range.address));
2341 size_t size(range.size);
2343 if (size < sizeof(CYObjectStruct))
2346 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2348 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2350 Class isa(reinterpret_cast<Class>(pointers[0]));
2353 std::set<Class>::const_iterator result(choice->query_.find(isa));
2354 if (result == choice->query_.end())
2357 size_t needed(class_getInstanceSize(*result));
2358 // XXX: if (size < needed)
2360 size_t boundary(496);
2364 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2366 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2370 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2372 throw CYJSError(context, "choose() takes a class argument");
2374 CYGarbageCollect(context);
2377 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2379 vm_address_t *zones(NULL);
2381 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2382 _assert(error == KERN_SUCCESS);
2384 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2385 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2388 choice.context_ = context;
2389 choice.results_ = results;
2392 Class *classes(CYCopyClassList(number));
2393 _assert(classes != NULL);
2395 for (size_t i(0); i != number; ++i)
2396 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2397 if (current == _class) {
2398 choice.query_.insert(classes[i]);
2404 for (unsigned i(0); i != size; ++i) {
2405 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2406 if (zone == NULL || zone->introspect == NULL)
2409 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2417 #if defined(__i386__) || defined(__x86_64__)
2418 #define OBJC_MAX_STRUCT_BY_VALUE 8
2419 static int struct_forward_array[] = {
2420 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2421 #elif defined(__arm__)
2422 #define OBJC_MAX_STRUCT_BY_VALUE 1
2423 static int struct_forward_array[] = {
2425 #elif defined(__arm64__)
2428 #error missing objc-runtime-info
2432 static bool stret(ffi_type *ffi_type) {
2433 return ffi_type->type == FFI_TYPE_STRUCT && (
2434 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2435 struct_forward_array[ffi_type->size] != 0
2441 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2445 _class = object_getClass(self);
2449 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2450 imp = method_getImplementation(method);
2451 type = method_getTypeEncoding(method);
2456 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2458 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2459 type = CYPoolCString(pool, context, [method _typeString]);
2467 sig::Signature signature;
2468 sig::Parse(pool, &signature, type, &Structor_);
2470 size_t used(count + 3);
2471 if (used > signature.count) {
2472 sig::Element *elements(new (pool) sig::Element[used]);
2473 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2475 for (size_t index(signature.count); index != used; ++index) {
2476 sig::Element *element(&elements[index]);
2477 element->name = NULL;
2478 element->offset = _not(size_t);
2480 sig::Type *type(new (pool) sig::Type);
2481 memset(type, 0, sizeof(*type));
2482 type->primitive = sig::object_P;
2483 element->type = type;
2486 signature.elements = elements;
2487 signature.count = used;
2491 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2496 if (stret(cif.rtype))
2497 imp = class_getMethodImplementation_stret(_class, _cmd);
2500 imp = class_getMethodImplementation(_class, _cmd);
2502 objc_super super = {self, _class};
2503 imp = objc_msg_lookup_super(&super, _cmd);
2507 void (*function)() = reinterpret_cast<void (*)()>(imp);
2508 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2511 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2513 throw CYJSError(context, "too few arguments to objc_msgSend");
2523 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2524 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2525 self = internal->GetValue();
2526 _class = internal->class_;;
2527 uninitialized = false;
2528 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2529 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2530 self = internal->GetValue();
2532 uninitialized = internal->IsUninitialized();
2534 internal->value_ = nil;
2536 self = CYCastNSObject(&pool, context, arguments[0]);
2538 uninitialized = false;
2542 return CYJSNull(context);
2544 _cmd = CYCastSEL(context, arguments[1]);
2546 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2549 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2550 return $objc_msgSend(context, object, _this, count, arguments);
2553 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2554 JSValueRef setup[count + 2];
2557 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2558 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2561 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2563 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2565 // XXX: handle Instance::Uninitialized?
2566 id self(CYCastNSObject(&pool, context, _this));
2570 setup[1] = &internal->sel_;
2572 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2575 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2577 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2579 id self(CYCastNSObject(&pool, context, arguments[0]));
2580 Class _class(CYCastClass(pool, context, arguments[1]));
2581 return cy::Super::Make(context, self, _class);
2584 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2586 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2588 const char *name(CYPoolCString(pool, context, arguments[0]));
2589 return CYMakeSelector(context, sel_registerName(name));
2592 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2594 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2595 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2596 return CYMakeInstance(context, self, false);
2599 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2600 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2601 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2604 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2605 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2606 Type_privateData *typical(internal->GetType());
2611 if (typical == NULL) {
2615 type = typical->type_;
2616 ffi = typical->ffi_;
2619 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2622 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2623 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2624 const char *encoding(CYBlockEncoding(internal->GetValue()));
2625 if (encoding == NULL)
2626 return CYJSNull(context);
2627 // XXX: this should be stored on a FunctionInstance private value subclass
2629 sig::Signature signature;
2630 sig::Parse(pool, &signature, encoding, &Structor_);
2631 return CYMakeType(context, &signature);
2634 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2635 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2636 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2639 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2640 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2641 id self(internal->GetValue());
2642 if (!CYIsClass(self))
2643 return CYJSUndefined(context);
2644 return CYGetClassPrototype(context, self);
2647 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2648 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2649 id self(internal->GetValue());
2650 if (!CYIsClass(self))
2651 return CYJSUndefined(context);
2652 return Messages::Make(context, (Class) self);
2655 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2656 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2658 if (!CYJSValueIsNSObject(context, _this))
2661 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2662 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2665 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2666 if (!CYJSValueIsNSObject(context, _this))
2669 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2670 id value(internal->GetValue());
2677 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2679 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2680 return CYJSUndefined(context);
2681 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2684 return CYCastJSValue(context, CYJSString(context, [value description]));
2686 } CYCatch(NULL) return /*XXX*/ NULL; }
2688 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2689 if (!CYJSValueIsNSObject(context, _this))
2692 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2693 id value(internal->GetValue());
2695 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2698 if (JSValueRef result = [value cy$valueOfInContext:context])
2702 } CYCatch(NULL) return /*XXX*/ NULL; }
2704 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2705 if (!CYJSValueIsNSObject(context, _this))
2708 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2709 // XXX: but... but... THIS ISN'T A POINTER! :(
2710 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2711 } CYCatch(NULL) return /*XXX*/ NULL; }
2713 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2714 if (!CYJSValueIsNSObject(context, _this))
2717 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2718 id value(internal->GetValue());
2721 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2722 return CYCastJSValue(context, CYJSString(context, [value description]));
2724 } CYCatch(NULL) return /*XXX*/ NULL; }
2726 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2727 if (!CYJSValueIsNSObject(context, _this))
2730 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2731 id value(internal->GetValue());
2733 if (!CYIsClass(value))
2734 CYThrow("non-Class object cannot be used as Type");
2736 // XXX: this is a very silly implementation
2738 std::ostringstream type;
2740 type << class_getName(value);
2744 return CYMakeType(context, type.str().c_str());
2746 } CYCatch(NULL) return /*XXX*/ NULL; }
2748 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2749 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2750 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2753 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2754 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2757 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2758 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2759 const char *name(sel_getName(internal->GetValue()));
2762 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2763 return CYCastJSValue(context, CYJSString(context, string));
2765 } CYCatch(NULL) return /*XXX*/ NULL; }
2767 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2769 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2772 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2773 SEL sel(internal->GetValue());
2775 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2776 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2777 const char *encoding(method_getTypeEncoding(method));
2779 sig::Signature signature;
2780 sig::Parse(pool, &signature, encoding, &Structor_);
2781 return CYMakeType(context, &signature);
2784 static JSStaticValue Selector_staticValues[2] = {
2785 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2786 {NULL, NULL, NULL, 0}
2789 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2790 static JSStaticValue Instance_staticValues[5] = {
2791 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2792 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2793 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2794 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2795 {NULL, NULL, NULL, 0}
2798 static JSStaticValue FunctionInstance_staticValues[6] = {
2799 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2800 // XXX: this is sadly a duplicate of Instance_staticValues
2801 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2802 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2803 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2804 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2805 {NULL, NULL, NULL, 0}
2808 static JSStaticFunction Instance_staticFunctions[7] = {
2809 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2810 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2811 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2812 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2813 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2814 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2818 static JSStaticFunction Class_staticFunctions[2] = {
2819 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2823 static JSStaticFunction Internal_staticFunctions[2] = {
2824 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2828 static JSStaticFunction Selector_staticFunctions[5] = {
2829 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2830 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2831 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2832 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2837 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2838 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2839 } CYObjectiveCatch }
2842 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2843 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2844 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2845 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2847 CYPool &pool(CYGetGlobalPool());
2849 Object_type = new(pool) Type_privateData("@");
2850 Selector_type = new(pool) Type_privateData(":");
2852 NSArray_ = objc_getClass("NSArray");
2853 NSBlock_ = objc_getClass("NSBlock");
2854 NSDictionary_ = objc_getClass("NSDictionary");
2855 NSNumber_ = objc_getClass("NSNumber");
2856 NSString_ = objc_getClass("NSString");
2857 Object_ = objc_getClass("Object");
2860 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2862 // XXX: apparently, iOS now has both of these
2863 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2864 if (NSCFBoolean_ == nil)
2865 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2867 NSCFType_ = objc_getClass("NSCFType");
2869 NSZombie_ = objc_getClass("_NSZombie_");
2871 banned_.insert(Object_);
2872 banned_.insert(objc_getClass("__NSAtom"));
2873 banned_.insert(objc_getClass("__NSGenericDeallocHandler"));
2874 banned_.insert(objc_getClass("NSMessageBuilder"));
2875 banned_.insert(objc_getClass("__NSMessageBuilder"));
2877 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2880 JSClassDefinition definition;
2882 definition = kJSClassDefinitionEmpty;
2883 definition.className = "Instance";
2884 definition.staticValues = Instance_staticValues;
2885 definition.staticFunctions = Instance_staticFunctions;
2886 definition.hasProperty = &Instance_hasProperty;
2887 definition.getProperty = &Instance_getProperty;
2888 definition.setProperty = &Instance_setProperty;
2889 definition.deleteProperty = &Instance_deleteProperty;
2890 definition.getPropertyNames = &Instance_getPropertyNames;
2891 definition.callAsConstructor = &Instance_callAsConstructor;
2892 definition.hasInstance = &Instance_hasInstance;
2893 definition.finalize = &CYFinalize;
2894 Instance_ = JSClassCreate(&definition);
2896 definition.className = "ArrayInstance";
2897 ArrayInstance_ = JSClassCreate(&definition);
2899 definition.className = "BooleanInstance";
2900 BooleanInstance_ = JSClassCreate(&definition);
2902 definition.className = "NumberInstance";
2903 NumberInstance_ = JSClassCreate(&definition);
2905 definition.className = "ObjectInstance";
2906 ObjectInstance_ = JSClassCreate(&definition);
2908 definition.className = "StringInstance";
2909 StringInstance_ = JSClassCreate(&definition);
2911 definition.className = "FunctionInstance";
2912 definition.staticValues = FunctionInstance_staticValues;
2913 definition.callAsFunction = &FunctionInstance_callAsFunction;
2914 FunctionInstance_ = JSClassCreate(&definition);
2916 definition = kJSClassDefinitionEmpty;
2917 definition.className = "Class";
2918 definition.staticFunctions = Class_staticFunctions;
2919 Class_ = JSClassCreate(&definition);
2921 definition = kJSClassDefinitionEmpty;
2922 definition.className = "Internal";
2923 definition.staticFunctions = Internal_staticFunctions;
2924 definition.hasProperty = &Internal_hasProperty;
2925 definition.getProperty = &Internal_getProperty;
2926 definition.setProperty = &Internal_setProperty;
2927 definition.getPropertyNames = &Internal_getPropertyNames;
2928 definition.finalize = &CYFinalize;
2929 Internal_ = JSClassCreate(&definition);
2931 definition = kJSClassDefinitionEmpty;
2932 definition.className = "Message";
2933 definition.staticFunctions = cy::Functor::StaticFunctions;
2934 definition.staticValues = cy::Functor::StaticValues;
2935 definition.callAsFunction = &Message_callAsFunction;
2936 definition.finalize = &CYFinalize;
2937 Message_ = JSClassCreate(&definition);
2939 definition = kJSClassDefinitionEmpty;
2940 definition.className = "Messages";
2941 definition.hasProperty = &Messages_hasProperty;
2942 definition.getProperty = &Messages_getProperty;
2943 definition.setProperty = &Messages_setProperty;
2944 #if 0 && OBJC_API_VERSION < 2
2945 definition.deleteProperty = &Messages_deleteProperty;
2947 definition.getPropertyNames = &Messages_getPropertyNames;
2948 definition.finalize = &CYFinalize;
2949 Messages_ = JSClassCreate(&definition);
2951 definition = kJSClassDefinitionEmpty;
2952 definition.className = "Selector";
2953 definition.staticValues = Selector_staticValues;
2954 definition.staticFunctions = Selector_staticFunctions;
2955 definition.callAsFunction = &Selector_callAsFunction;
2956 definition.finalize = &CYFinalize;
2957 Selector_ = JSClassCreate(&definition);
2959 definition = kJSClassDefinitionEmpty;
2960 definition.className = "Super";
2961 definition.staticFunctions = Internal_staticFunctions;
2962 definition.finalize = &CYFinalize;
2963 Super_ = JSClassCreate(&definition);
2965 definition = kJSClassDefinitionEmpty;
2966 definition.className = "ObjectiveC::Classes";
2967 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2968 definition.getProperty = &ObjectiveC_Classes_getProperty;
2969 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2970 ObjectiveC_Classes_ = JSClassCreate(&definition);
2972 definition = kJSClassDefinitionEmpty;
2973 definition.className = "ObjectiveC::Constants";
2974 definition.getProperty = &ObjectiveC_Constants_getProperty;
2975 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2976 ObjectiveC_Constants_ = JSClassCreate(&definition);
2978 #if OBJC_API_VERSION >= 2
2979 definition = kJSClassDefinitionEmpty;
2980 definition.className = "ObjectiveC::Images";
2981 definition.getProperty = &ObjectiveC_Images_getProperty;
2982 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2983 ObjectiveC_Images_ = JSClassCreate(&definition);
2985 definition = kJSClassDefinitionEmpty;
2986 definition.className = "ObjectiveC::Image::Classes";
2987 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2988 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2989 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2992 definition = kJSClassDefinitionEmpty;
2993 definition.className = "ObjectiveC::Protocols";
2994 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2995 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2996 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2999 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
3000 // XXX: this is horrible; there has to be a better way to do this
3002 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
3004 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
3010 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
3011 JSObjectRef global(CYGetGlobalObject(context));
3012 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
3013 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
3014 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
3015 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
3017 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
3018 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
3020 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3021 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
3022 CYArrayPush(context, alls, protocols);
3024 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
3025 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
3026 CYArrayPush(context, alls, classes);
3028 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
3029 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
3030 CYArrayPush(context, alls, constants);
3032 #if OBJC_API_VERSION >= 2
3033 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3036 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
3037 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3038 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3039 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3040 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
3042 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
3043 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3045 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
3046 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
3047 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
3048 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
3049 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
3051 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
3052 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
3053 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
3054 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
3055 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
3057 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
3058 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
3059 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
3060 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
3061 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
3063 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
3064 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
3065 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
3066 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
3067 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
3069 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3070 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3071 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3072 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3073 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3075 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3076 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3077 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3078 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3079 CYSetPrototype(context, StringInstance_prototype, String_prototype);
3081 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
3082 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
3083 CYSetPrototype(context, Class_prototype, Instance_prototype);
3085 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3086 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3087 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3089 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3090 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3093 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3096 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3098 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3099 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3102 static CYHooks CYObjectiveCHooks = {
3103 &CYObjectiveC_ExecuteStart,
3104 &CYObjectiveC_ExecuteEnd,
3105 &CYObjectiveC_CallFunction,
3106 &CYObjectiveC_Initialize,
3107 &CYObjectiveC_SetupContext,
3108 &CYObjectiveC_PoolFFI,
3109 &CYObjectiveC_FromFFI,
3112 struct CYObjectiveC {
3114 hooks_ = &CYObjectiveCHooks;
3115 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
3116 _assert(hooks_ != NULL);
3120 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3121 CYSetupContext(context);
3122 } CYObjectiveCatch }
3124 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3127 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3128 CYStream stream(utf8.data, utf8.data + utf8.size);
3129 utf8 = CYPoolCode(pool, stream);
3131 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3132 size_t bytes(utf16.size * sizeof(uint16_t));
3133 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3134 memcpy(copy, utf16.data, bytes);
3138 } catch (const CYException &exception) {
3140 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];