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>
44 #include "JavaScript.hpp"
46 #include "Execute.hpp"
54 #define CYObjectiveTry_ { \
56 #define CYObjectiveTry { \
57 JSContextRef context(context_); \
59 #define CYObjectiveCatch \
60 catch (const CYException &error) { \
61 @throw CYCastNSObject(NULL, context, error.CastJSValue(context)); \
67 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
69 #define CYPoolCatch(value) \
70 @catch (NSException *error) { \
71 _saved = [error retain]; \
72 throw CYJSError(context, CYCastJSValue(context, error)); \
77 [_saved autorelease]; \
83 #define CYSadCatch(value) \
84 @catch (NSException *error ) { \
85 throw CYJSError(context, CYCastJSValue(context, error)); \
90 #define class_getSuperclass GSObjCSuper
91 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
92 #define class_getName GSNameFromClass
94 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
96 #define ivar_getName(ivar) ((ivar)->ivar_name)
97 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
98 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
100 #define method_getName(method) ((method)->method_name)
101 #define method_getImplementation(method) ((method)->method_imp)
102 #define method_getTypeEncoding(method) ((method)->method_types)
103 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
106 #define objc_getClass GSClassFromName
108 #define objc_getProtocol GSProtocolFromName
110 #define object_getClass GSObjCClass
112 #define object_getInstanceVariable(object, name, value) ({ \
113 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
114 _assert(value != NULL); \
116 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
120 #define object_setIvar(object, ivar, value) ({ \
121 void *data = (value); \
122 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
125 #define protocol_getName(protocol) [(protocol) name]
128 static void (*$objc_setAssociatedObject)(id object, void *key, id value, objc_AssociationPolicy policy);
129 static id (*$objc_getAssociatedObject)(id object, void *key);
130 static void (*$objc_removeAssociatedObjects)(id object);
132 struct BlockLiteral {
136 void (*invoke)(void *, ...);
140 struct BlockDescriptor1 {
141 unsigned long int reserved;
142 unsigned long int size;
145 struct BlockDescriptor2 {
146 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
147 void (*dispose_helper)(BlockLiteral *src);
150 struct BlockDescriptor3 {
151 const char *signature;
156 BLOCK_DEALLOCATING = 0x0001,
157 BLOCK_REFCOUNT_MASK = 0xfffe,
158 BLOCK_NEEDS_FREE = 1 << 24,
159 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
160 BLOCK_HAS_CTOR = 1 << 26,
161 BLOCK_IS_GC = 1 << 27,
162 BLOCK_IS_GLOBAL = 1 << 28,
163 BLOCK_HAS_STRET = 1 << 29,
164 BLOCK_HAS_SIGNATURE = 1 << 30,
167 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
169 /* Objective-C Pool Release {{{ */
170 void CYPoolRelease_(void *data) {
171 id object(reinterpret_cast<id>(data));
175 id CYPoolRelease_(CYPool *pool, id object) {
178 else if (pool == NULL)
179 return [object autorelease];
181 pool->atexit(CYPoolRelease_);
186 template <typename Type_>
187 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
188 return (Type_) CYPoolRelease_(pool, (id) object);
191 /* Objective-C Strings {{{ */
192 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
193 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
194 char *string(new(pool) char[size]);
195 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
196 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
200 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
202 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
205 return CYCopyJSString(CYPoolCString(pool, context, value));
209 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
212 // XXX: this definition scares me; is anyone using this?!
213 NSString *string([value description]);
214 return CYCopyJSString(context, string);
217 NSString *CYCopyNSString(const CYUTF8String &value) {
219 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
221 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
225 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
227 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
230 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
234 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
235 return CYCopyNSString(context, CYJSString(context, value));
238 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
239 return CYPoolRelease(pool, CYCopyNSString(value));
242 NSString *CYCastNSString(CYPool *pool, SEL sel) {
243 const char *name(sel_getName(sel));
244 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
247 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
248 return CYPoolRelease(pool, CYCopyNSString(context, value));
251 CYUTF8String CYCastUTF8String(NSString *value) {
252 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
253 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
257 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
259 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
260 if (exception == NULL)
262 *exception = CYCastJSValue(context, error);
265 size_t CYGetIndex(NSString *value) {
266 return CYGetIndex(CYCastUTF8String(value));
269 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
270 return CYGetOffset(CYPoolCString(pool, context, value), index);
273 static JSClassRef Instance_;
275 static JSClassRef ArrayInstance_;
276 static JSClassRef BooleanInstance_;
277 static JSClassRef FunctionInstance_;
278 static JSClassRef NumberInstance_;
279 static JSClassRef ObjectInstance_;
280 static JSClassRef StringInstance_;
282 static JSClassRef Class_;
283 static JSClassRef Internal_;
284 static JSClassRef Message_;
285 static JSClassRef Messages_;
286 static JSClassRef Selector_;
287 static JSClassRef Super_;
289 static JSClassRef ObjectiveC_Classes_;
290 static JSClassRef ObjectiveC_Constants_;
291 static JSClassRef ObjectiveC_Protocols_;
294 static JSClassRef ObjectiveC_Image_Classes_;
295 static JSClassRef ObjectiveC_Images_;
299 static Class __NSMallocBlock__;
300 static Class NSCFBoolean_;
301 static Class NSCFType_;
302 static Class NSGenericDeallocHandler_;
303 static Class NSZombie_;
305 static std::set<Class> banned_;
307 static Class NSBoolNumber_;
310 static Class NSArray_;
311 static Class NSBlock_;
312 static Class NSDictionary_;
313 static Class NSNumber_;
314 static Class NSString_;
315 static Class Object_;
317 static Type_privateData *Object_type;
318 static Type_privateData *Selector_type;
320 Type_privateData *Instance::GetType() const {
324 Type_privateData *Selector_privateData::GetType() const {
325 return Selector_type;
328 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
330 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
332 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
333 else if (meta && !class_isMetaClass(self))
334 return CYGetCachedObject(context, CYJSString("Class_prototype"));
336 JSObjectRef global(CYGetGlobalObject(context));
337 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
340 sprintf(label, "i%p", self);
341 CYJSString name(label);
343 JSValueRef value(CYGetProperty(context, cy, name));
344 if (!JSValueIsUndefined(context, value))
347 JSClassRef _class(NULL);
348 JSValueRef prototype;
351 if (self == NSCFBoolean_)
353 if (self == NSBoolNumber_)
355 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
356 else if (self == NSArray_)
357 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
358 else if (self == NSBlock_)
359 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
360 else if (self == NSNumber_)
361 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
362 else if (self == NSDictionary_)
363 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
364 else if (self == NSString_)
365 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
367 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
369 JSObjectRef object(JSObjectMake(context, _class, NULL));
370 JSObjectSetPrototype(context, object, prototype);
371 CYSetProperty(context, cy, name, object);
376 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
377 return CYGetClassPrototype(context, self, class_isMetaClass(self));
380 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
381 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
382 if (Class super = class_getSuperclass(_class))
383 JSObjectSetPrototype(context, value, Messages::Make(context, super));
387 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
388 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
392 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
393 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
397 bool CYIsKindOfClass(id object, Class _class) {
398 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
404 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
405 JSObjectRef value(JSObjectMake(context, CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance_, new Instance(object, flags)));
406 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
410 Instance::~Instance() {
411 if ((flags_ & Transient) == 0)
412 [GetValue() release];
415 struct Message_privateData :
420 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
421 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
427 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
428 Instance::Flags flags;
431 flags = Instance::Transient;
433 flags = Instance::None;
434 object = [object retain];
437 return Instance::Make(context, object, flags);
440 @interface NSMethodSignature (Cycript)
441 - (NSString *) _typeString;
444 @interface NSObject (Cycript)
446 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
447 - (JSType) cy$JSType;
449 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
450 - (NSString *) cy$toCYON:(bool)objective;
452 - (bool) cy$hasProperty:(NSString *)name;
453 - (NSObject *) cy$getProperty:(NSString *)name;
454 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
455 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
456 - (bool) cy$deleteProperty:(NSString *)name;
457 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
459 + (bool) cy$hasImplicitProperties;
465 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
468 NSString *CYCastNSCYON(id value, bool objective) {
474 Class _class(object_getClass(value));
475 SEL sel(@selector(cy$toCYON:));
477 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
478 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
479 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
480 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
481 string = [value cy$toCYON:objective];
486 else if (value == NSZombie_)
487 string = @"_NSZombie_";
488 else if (_class == NSZombie_)
489 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
490 // XXX: frowny /in/ the pants
491 else if (banned_.find(value) != banned_.end())
495 string = [NSString stringWithFormat:@"%@", value];
500 string = @"undefined";
507 struct PropertyAttributes {
512 const char *variable;
525 PropertyAttributes(objc_property_t property) :
537 name = property_getName(property);
538 const char *attributes(property_getAttributes(property));
540 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
541 if ((next = strchr(token, ',')) != NULL)
544 case 'R': readonly = true; break;
545 case 'C': copy = true; break;
546 case '&': retain = true; break;
547 case 'N': nonatomic = true; break;
548 case 'G': getter_ = token + 1; break;
549 case 'S': setter_ = token + 1; break;
550 case 'V': variable = token + 1; break;
554 /*if (variable == NULL) {
555 variable = property_getName(property);
556 size_t size(strlen(variable));
557 char *name(new(pool_) char[size + 2]);
559 memcpy(name + 1, variable, size);
560 name[size + 1] = '\0';
565 const char *Getter() {
567 getter_ = pool_.strdup(name);
571 const char *Setter() {
572 if (setter_ == NULL && !readonly) {
573 size_t length(strlen(name));
575 char *temp(new(pool_) char[length + 5]);
581 temp[3] = toupper(name[0]);
582 memcpy(temp + 4, name + 1, length - 1);
585 temp[length + 3] = ':';
586 temp[length + 4] = '\0';
596 @interface CYWebUndefined : NSObject {
599 + (CYWebUndefined *) undefined;
603 @implementation CYWebUndefined
605 + (CYWebUndefined *) undefined {
606 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
612 #define WebUndefined CYWebUndefined
614 /* Bridge: CYJSObject {{{ */
615 @interface CYJSObject : NSMutableDictionary {
617 JSGlobalContextRef context_;
620 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
622 - (NSUInteger) count;
623 - (id) objectForKey:(id)key;
624 - (NSEnumerator *) keyEnumerator;
625 - (void) setObject:(id)object forKey:(id)key;
626 - (void) removeObjectForKey:(id)key;
630 /* Bridge: CYJSArray {{{ */
631 @interface CYJSArray : NSMutableArray {
633 JSGlobalContextRef context_;
636 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
638 - (NSUInteger) count;
639 - (id) objectAtIndex:(NSUInteger)index;
641 - (void) addObject:(id)anObject;
642 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
643 - (void) removeLastObject;
644 - (void) removeObjectAtIndex:(NSUInteger)index;
645 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
650 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
651 return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
654 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
655 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
658 struct CYBlockDescriptor {
660 BlockDescriptor1 one_;
661 BlockDescriptor2 two_;
662 BlockDescriptor3 three_;
665 Closure_privateData *internal_;
668 void CYDisposeBlock(BlockLiteral *literal) {
669 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
672 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
673 JSObjectRef _this(CYCastJSObject(context, values[0]));
674 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
677 static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
678 CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
681 NSObject *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
682 _assert(__NSMallocBlock__ != Nil);
683 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
685 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
686 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
688 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
689 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
691 literal->isa = __NSMallocBlock__;
692 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
693 literal->reserved = 0;
694 literal->descriptor = descriptor;
696 descriptor->d_.one_.size = sizeof(descriptor->d_);
697 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
698 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
700 return reinterpret_cast<NSObject *>(literal);
703 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
704 if (CYJSValueIsNSObject(context, object)) {
705 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
706 return internal->GetValue();
709 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
710 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
711 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
714 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
715 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
719 @interface NSBoolNumber : NSNumber {
724 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
728 switch (JSType type = JSValueGetType(context, value)) {
729 case kJSTypeUndefined:
730 object = [WebUndefined undefined];
740 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
743 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
749 object = CYCopyNSNumber(context, value);
754 object = CYCopyNSString(context, value);
759 // XXX: this might could be more efficient
760 object = CYCastNSObject(pool, context, (JSObjectRef) value);
765 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
772 return CYPoolRelease(pool, object);
774 return [object retain];
777 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
778 return CYNSObject(pool, context, value, true);
781 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
782 return CYNSObject(&pool, context, value, false);
785 /* Bridge: NSArray {{{ */
786 @implementation NSArray (Cycript)
789 return [[self mutableCopy] autorelease];
792 - (NSString *) cy$toCYON:(bool)objective {
793 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
794 [json appendString:@"@["];
798 for (id object in self) {
800 for (size_t index(0), count([self count]); index != count; ++index) {
801 id object([self objectAtIndex:index]);
804 [json appendString:@","];
807 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
808 [json appendString:CYCastNSCYON(object, true)];
810 [json appendString:@","];
815 [json appendString:@"]"];
819 - (bool) cy$hasProperty:(NSString *)name {
820 if ([name isEqualToString:@"length"])
823 size_t index(CYGetIndex(name));
824 if (index == _not(size_t) || index >= [self count])
825 return [super cy$hasProperty:name];
830 - (NSObject *) cy$getProperty:(NSString *)name {
831 size_t index(CYGetIndex(name));
832 if (index == _not(size_t) || index >= [self count])
833 return [super cy$getProperty:name];
835 return [self objectAtIndex:index];
838 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
840 if ([name isEqualToString:@"length"])
841 return CYCastJSValue(context, [self count]);
844 return [super cy$getProperty:name inContext:context];
847 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
848 [super cy$getPropertyNames:names inContext:context];
850 for (size_t index(0), count([self count]); index != count; ++index) {
851 id object([self objectAtIndex:index]);
852 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
854 sprintf(name, "%zu", index);
855 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
860 + (bool) cy$hasImplicitProperties {
866 /* Bridge: NSBlock {{{ */
873 /* Bridge: NSBoolNumber {{{ */
875 @implementation NSBoolNumber (Cycript)
877 - (JSType) cy$JSType {
878 return kJSTypeBoolean;
881 - (NSString *) cy$toCYON:(bool)objective {
882 NSString *value([self boolValue] ? @"true" : @"false");
883 return objective ? value : [NSString stringWithFormat:@"@%@", value];
886 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
887 return CYCastJSValue(context, (bool) [self boolValue]);
893 /* Bridge: NSDictionary {{{ */
894 @implementation NSDictionary (Cycript)
897 return [[self mutableCopy] autorelease];
900 - (NSString *) cy$toCYON:(bool)objective {
901 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
902 [json appendString:@"@{"];
906 for (NSObject *key in self) {
908 NSEnumerator *keys([self keyEnumerator]);
909 while (NSObject *key = [keys nextObject]) {
912 [json appendString:@","];
915 [json appendString:CYCastNSCYON(key, true)];
916 [json appendString:@":"];
917 NSObject *object([self objectForKey:key]);
918 [json appendString:CYCastNSCYON(object, true)];
921 [json appendString:@"}"];
925 - (bool) cy$hasProperty:(NSString *)name {
926 return [self objectForKey:name] != nil;
929 - (NSObject *) cy$getProperty:(NSString *)name {
930 return [self objectForKey:name];
933 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
934 [super cy$getPropertyNames:names inContext:context];
937 for (NSObject *key in self) {
939 NSEnumerator *keys([self keyEnumerator]);
940 while (NSObject *key = [keys nextObject]) {
942 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
946 + (bool) cy$hasImplicitProperties {
952 /* Bridge: NSMutableArray {{{ */
953 @implementation NSMutableArray (Cycript)
955 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
956 if ([name isEqualToString:@"length"]) {
957 // XXX: is this not intelligent?
958 NSNumber *number(reinterpret_cast<NSNumber *>(value));
960 NSUInteger size([number unsignedIntegerValue]);
962 NSUInteger size([number unsignedIntValue]);
964 NSUInteger count([self count]);
966 [self removeObjectsInRange:NSMakeRange(size, count - size)];
967 else if (size != count) {
968 WebUndefined *undefined([WebUndefined undefined]);
969 for (size_t i(count); i != size; ++i)
970 [self addObject:undefined];
975 size_t index(CYGetIndex(name));
976 if (index == _not(size_t))
977 return [super cy$setProperty:name to:value];
979 id object(value ?: [NSNull null]);
981 size_t count([self count]);
983 [self replaceObjectAtIndex:index withObject:object];
985 if (index != count) {
986 WebUndefined *undefined([WebUndefined undefined]);
987 for (size_t i(count); i != index; ++i)
988 [self addObject:undefined];
991 [self addObject:object];
997 - (bool) cy$deleteProperty:(NSString *)name {
998 size_t index(CYGetIndex(name));
999 if (index == _not(size_t) || index >= [self count])
1000 return [super cy$deleteProperty:name];
1001 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1007 /* Bridge: NSMutableDictionary {{{ */
1008 @implementation NSMutableDictionary (Cycript)
1010 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1011 [self setObject:(value ?: [NSNull null]) forKey:name];
1015 - (bool) cy$deleteProperty:(NSString *)name {
1016 if ([self objectForKey:name] == nil)
1019 [self removeObjectForKey:name];
1026 /* Bridge: NSNumber {{{ */
1027 @implementation NSNumber (Cycript)
1029 - (JSType) cy$JSType {
1031 // XXX: this just seems stupid
1032 if ([self class] == NSCFBoolean_)
1033 return kJSTypeBoolean;
1035 return kJSTypeNumber;
1038 - (NSString *) cy$toCYON:(bool)objective {
1039 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1040 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1043 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1044 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1045 } CYObjectiveCatch }
1049 /* Bridge: NSNull {{{ */
1050 @implementation NSNull (Cycript)
1052 - (JSType) cy$JSType {
1056 - (NSString *) cy$toCYON:(bool)objective {
1057 NSString *value(@"null");
1058 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1061 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1062 return CYJSNull(context);
1063 } CYObjectiveCatch }
1067 /* Bridge: NSObject {{{ */
1068 @implementation NSObject (Cycript)
1074 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1075 return [self cy$valueOfInContext:context];
1078 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1080 } CYObjectiveCatch }
1082 - (JSType) cy$JSType {
1083 return kJSTypeObject;
1086 - (NSString *) cy$toCYON:(bool)objective {
1087 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true]];
1090 - (bool) cy$hasProperty:(NSString *)name {
1094 - (NSObject *) cy$getProperty:(NSString *)name {
1098 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1099 if (NSObject *value = [self cy$getProperty:name])
1100 return CYCastJSValue(context, value);
1102 } CYObjectiveCatch }
1104 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1108 - (bool) cy$deleteProperty:(NSString *)name {
1112 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1115 + (bool) cy$hasImplicitProperties {
1121 /* Bridge: NSProxy {{{ */
1122 @implementation NSProxy (Cycript)
1124 - (NSString *) cy$toCYON:(bool)objective {
1125 return [[self description] cy$toCYON:objective];
1130 /* Bridge: NSSet {{{ */
1131 @implementation NSSet (Cycript)
1133 - (NSString *) cy$toCYON:(bool)objective {
1134 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1135 [json appendString:@"[NSSet setWithArray:"];
1136 [json appendString:CYCastNSCYON([self allObjects], true)];
1137 [json appendString:@"]]"];
1143 /* Bridge: NSString {{{ */
1144 @implementation NSString (Cycript)
1147 return [[self copy] autorelease];
1150 - (JSType) cy$JSType {
1151 return kJSTypeString;
1154 - (NSString *) cy$toCYON:(bool)objective {
1155 std::ostringstream str;
1158 CYUTF8String string(CYCastUTF8String(self));
1159 CYStringify(str, string.data, string.size);
1160 std::string value(str.str());
1161 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1164 - (bool) cy$hasProperty:(NSString *)name {
1165 size_t index(CYGetIndex(name));
1166 if (index == _not(size_t) || index >= [self length])
1167 return [super cy$hasProperty:name];
1172 - (NSObject *) cy$getProperty:(NSString *)name {
1173 size_t index(CYGetIndex(name));
1174 if (index == _not(size_t) || index >= [self length])
1175 return [super cy$getProperty:name];
1177 return [self substringWithRange:NSMakeRange(index, 1)];
1180 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1181 [super cy$getPropertyNames:names inContext:context];
1183 for (size_t index(0), length([self length]); index != length; ++index) {
1185 sprintf(name, "%zu", index);
1186 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1190 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1191 return CYCastJSValue(context, CYJSString(context, self));
1192 } CYObjectiveCatch }
1196 /* Bridge: WebUndefined {{{ */
1197 @implementation WebUndefined (Cycript)
1199 - (JSType) cy$JSType {
1200 return kJSTypeUndefined;
1203 - (NSString *) cy$toCYON:(bool)objective {
1204 NSString *value(@"undefined");
1205 return value; // XXX: maybe use the below code, adding @undefined?
1206 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1209 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1210 return CYJSUndefined(context);
1211 } CYObjectiveCatch }
1216 static bool CYIsClass(id self) {
1218 return class_isMetaClass(object_getClass(self));
1220 return GSObjCIsClass(self);
1224 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1225 id self(CYCastNSObject(&pool, context, value));
1226 if (CYIsClass(self))
1227 return (Class) self;
1228 throw CYJSError(context, "got something that is not a Class");
1232 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1234 size_t size(JSPropertyNameArrayGetCount(names));
1235 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1236 for (size_t index(0); index != size; ++index)
1237 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1241 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1243 return CYJSNull(context);
1245 return CYMakeInstance(context, value, false);
1246 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1248 @implementation CYJSObject
1250 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1251 if ((self = [super init]) != nil) {
1253 context_ = CYGetJSContext(context);
1254 JSGlobalContextRetain(context_);
1255 JSValueProtect(context_, object_);
1257 } CYObjectiveCatch }
1259 - (void) dealloc { CYObjectiveTry {
1260 JSValueUnprotect(context_, object_);
1261 JSGlobalContextRelease(context_);
1263 } CYObjectiveCatch }
1265 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1267 const char *cyon(CYPoolCCYON(pool, context, object_));
1269 return [super cy$toCYON:objective];
1271 return [NSString stringWithUTF8String:cyon];
1272 } CYObjectiveCatch }
1274 - (NSUInteger) count { CYObjectiveTry {
1275 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1276 size_t size(JSPropertyNameArrayGetCount(names));
1277 JSPropertyNameArrayRelease(names);
1279 } CYObjectiveCatch }
1281 - (id) objectForKey:(id)key { CYObjectiveTry {
1282 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1283 if (JSValueIsUndefined(context, value))
1285 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1286 } CYObjectiveCatch }
1288 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1289 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1290 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1291 JSPropertyNameArrayRelease(names);
1293 } CYObjectiveCatch }
1295 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1296 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1297 } CYObjectiveCatch }
1299 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1300 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1301 } CYObjectiveCatch }
1305 @implementation CYJSArray
1307 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1309 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_)];
1310 } CYObjectiveCatch }
1312 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1313 if ((self = [super init]) != nil) {
1315 context_ = CYGetJSContext(context);
1316 JSGlobalContextRetain(context_);
1317 JSValueProtect(context_, object_);
1319 } CYObjectiveCatch }
1321 - (void) dealloc { CYObjectiveTry {
1322 JSValueUnprotect(context_, object_);
1323 JSGlobalContextRelease(context_);
1325 } CYObjectiveCatch }
1327 - (NSUInteger) count { CYObjectiveTry {
1328 return CYArrayLength(context, object_);
1329 } CYObjectiveCatch }
1331 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1332 size_t bounds([self count]);
1333 if (index >= bounds)
1334 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1335 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1336 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1337 } CYObjectiveCatch }
1339 - (void) addObject:(id)object { CYObjectiveTry {
1340 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1341 } CYObjectiveCatch }
1343 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1344 size_t bounds([self count] + 1);
1345 if (index >= bounds)
1346 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1347 JSValueRef arguments[3];
1348 arguments[0] = CYCastJSValue(context, index);
1349 arguments[1] = CYCastJSValue(context, 0);
1350 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1351 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1352 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1353 } CYObjectiveCatch }
1355 - (void) removeLastObject { CYObjectiveTry {
1356 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1357 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1358 } CYObjectiveCatch }
1360 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1361 size_t bounds([self count]);
1362 if (index >= bounds)
1363 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1364 JSValueRef arguments[2];
1365 arguments[0] = CYCastJSValue(context, index);
1366 arguments[1] = CYCastJSValue(context, 1);
1367 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1368 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1369 } CYObjectiveCatch }
1371 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1372 size_t bounds([self count]);
1373 if (index >= bounds)
1374 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1375 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1376 } CYObjectiveCatch }
1380 // XXX: inherit from or replace with CYJSObject
1381 @interface CYInternal : NSObject {
1382 JSGlobalContextRef context_;
1383 JSObjectRef object_;
1388 @implementation CYInternal
1390 - (void) dealloc { CYObjectiveTry {
1391 JSValueUnprotect(context_, object_);
1392 JSGlobalContextRelease(context_);
1394 } CYObjectiveCatch }
1396 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1397 if ((self = [super init]) != nil) {
1398 context_ = CYGetJSContext(context);
1399 JSGlobalContextRetain(context_);
1401 } CYObjectiveCatch }
1403 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1404 if (object_ == NULL)
1407 return JSObjectHasProperty(context, object_, name);
1410 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1411 if (object_ == NULL)
1414 return CYGetProperty(context, object_, name);
1417 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1418 @synchronized (self) {
1419 if (object_ == NULL) {
1420 object_ = JSObjectMake(context, NULL, NULL);
1421 JSValueProtect(context, object_);
1425 CYSetProperty(context, object_, name, value);
1428 + (CYInternal *) get:(id)object {
1429 if ($objc_getAssociatedObject == NULL)
1432 @synchronized (object) {
1433 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1440 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1441 if ($objc_getAssociatedObject == NULL)
1444 @synchronized (object) {
1445 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1448 if ($objc_setAssociatedObject == NULL)
1451 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1452 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1461 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1462 Selector_privateData *internal(new Selector_privateData(sel));
1463 return JSObjectMake(context, Selector_, internal);
1466 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1467 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1468 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1469 return reinterpret_cast<SEL>(internal->value_);
1471 return CYCastPointer<SEL>(context, value);
1474 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1475 return (void *) [[NSAutoreleasePool alloc] init];
1476 } CYSadCatch(NULL) }
1478 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1479 return [(NSAutoreleasePool *) handle release];
1482 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1484 return Instance::Make(context, nil);
1485 if (Class _class = objc_getClass(name.data))
1486 return CYMakeInstance(context, _class, true);
1487 if (Protocol *protocol = objc_getProtocol(name.data))
1488 return CYMakeInstance(context, protocol, true);
1490 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1492 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1493 ffi_call(cif, function, value, values);
1496 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1497 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1499 switch (type->primitive) {
1500 case sig::block_P: {
1501 _assert(type->data.signature.count != 0);
1502 sig::Signature signature;
1503 sig::Copy(*pool, signature, type->data.signature);
1505 sig::Element *elements(new(*pool) sig::Element[++signature.count]);
1506 elements[0] = signature.elements[0];
1507 memcpy(elements + 2, signature.elements + 1, sizeof(sig::Element) * (signature.count - 2));
1508 signature.elements = elements;
1510 elements[1].name = NULL;
1511 elements[1].type = new(*pool) sig::Type();
1512 elements[1].offset = _not(size_t);
1514 memset(elements[1].type, 0, sizeof(sig::Type));
1515 elements[1].type->primitive = sig::object_P;
1517 JSObjectRef function(CYCastJSObject(context, value));
1518 *reinterpret_cast<id *>(data) = CYMakeBlock(context, function, signature);
1522 case sig::typename_P:
1523 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1526 case sig::selector_P:
1527 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1535 } CYSadCatch(false) }
1537 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1538 switch (type->primitive) {
1539 // XXX: do something epic about blocks
1542 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1543 JSValueRef value(CYCastJSValue(context, object));
1549 case sig::typename_P:
1550 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1552 case sig::selector_P:
1553 if (SEL sel = *reinterpret_cast<SEL *>(data))
1554 return CYMakeSelector(context, sel);
1558 return CYJSNull(context);
1562 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1564 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1565 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1568 #if OBJC_API_VERSION >= 2
1570 method_getReturnType(method, type, sizeof(type));
1572 const char *type(method_getTypeEncoding(method));
1578 // XXX: possibly use a more "awesome" check?
1582 static const char *CYPoolTypeEncoding(CYPool &pool, JSContextRef context, SEL sel, objc_method *method) {
1584 return method_getTypeEncoding(method);
1586 const char *name(sel_getName(sel));
1587 size_t length(strlen(name));
1589 char keyed[length + 2];
1591 keyed[length + 1] = '\0';
1592 memcpy(keyed + 1, name, length);
1594 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1595 return entry->value_;
1600 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1601 JSObjectRef _this(CYCastJSObject(context, values[0]));
1602 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1605 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1606 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1609 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1610 Message_privateData *internal(new Message_privateData(sel, type, imp));
1611 return JSObjectMake(context, Message_, internal);
1614 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1615 JSObjectRef function(CYCastJSObject(context, value));
1617 sig::Signature signature;
1618 sig::Parse(pool, &signature, encoding, &Structor_);
1619 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageClosure_));
1620 // XXX: see notes in Library.cpp about needing to leak
1621 return reinterpret_cast<IMP>(internal->GetValue());
1624 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1625 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1626 Class _class(internal->GetValue());
1629 const char *name(CYPoolCString(pool, context, property));
1631 if (SEL sel = sel_getUid(name))
1632 if (class_getInstanceMethod(_class, sel) != NULL)
1638 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1639 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1640 Class _class(internal->GetValue());
1643 const char *name(CYPoolCString(pool, context, property));
1645 if (SEL sel = sel_getUid(name))
1646 if (objc_method *method = class_getInstanceMethod(_class, sel))
1647 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1652 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1653 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1654 Class _class(internal->GetValue());
1657 const char *name(CYPoolCString(pool, context, property));
1658 SEL sel(sel_registerName(name));
1663 if (JSValueIsObjectOfClass(context, value, Message_)) {
1664 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1665 type = sig::Unparse(pool, &message->signature_);
1666 imp = reinterpret_cast<IMP>(message->GetValue());
1668 objc_method *method(class_getInstanceMethod(_class, sel));
1669 type = CYPoolTypeEncoding(pool, context, sel, method);
1670 imp = CYMakeMessage(context, value, type);
1673 objc_method *method(NULL);
1674 #if OBJC_API_VERSION >= 2
1676 objc_method **methods(class_copyMethodList(_class, &size));
1677 for (size_t i(0); i != size; ++i)
1678 if (sel_isEqual(method_getName(methods[i]), sel)) {
1679 method = methods[i];
1684 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1685 for (int i(0); i != methods->method_count; ++i)
1686 if (sel_isEqual(method_getName(&methods->method_list[i]), sel)) {
1687 method = &methods->method_list[i];
1693 method_setImplementation(method, imp);
1696 GSMethodList list(GSAllocMethodList(1));
1697 GSAppendMethodToList(list, sel, type, imp, YES);
1698 GSAddMethodList(_class, list, YES);
1699 GSFlushMethodCacheForClass(_class);
1701 class_addMethod(_class, sel, imp, type);
1708 #if 0 && OBJC_API_VERSION < 2
1709 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1710 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1711 Class _class(internal->GetValue());
1714 const char *name(CYPoolCString(pool, context, property));
1716 if (SEL sel = sel_getUid(name))
1717 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1718 objc_method_list list = {NULL, 1, {method}};
1719 class_removeMethods(_class, &list);
1727 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1728 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1729 Class _class(internal->GetValue());
1731 #if OBJC_API_VERSION >= 2
1733 objc_method **data(class_copyMethodList(_class, &size));
1734 for (size_t i(0); i != size; ++i)
1735 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1738 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1739 for (int i(0); i != methods->method_count; ++i)
1740 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1744 static bool CYHasImplicitProperties(Class _class) {
1745 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1746 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1748 return [_class cy$hasImplicitProperties];
1751 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1752 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1753 id self(internal->GetValue());
1755 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1759 NSString *name(CYCastNSString(&pool, context, property));
1761 if (CYInternal *internal = [CYInternal get:self])
1762 if ([internal hasProperty:property inContext:context])
1765 Class _class(object_getClass(self));
1768 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1769 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1770 if ([self cy$hasProperty:name])
1772 } CYPoolCatch(false)
1774 const char *string(CYPoolCString(pool, context, name));
1777 if (class_getProperty(_class, string) != NULL)
1781 if (CYHasImplicitProperties(_class))
1782 if (SEL sel = sel_getUid(string))
1783 if (CYImplements(self, _class, sel, true))
1789 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1790 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1791 id self(internal->GetValue());
1793 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1794 return Internal::Make(context, self, object);
1797 NSString *name(CYCastNSString(&pool, context, property));
1799 if (CYInternal *internal = [CYInternal get:self])
1800 if (JSValueRef value = [internal getProperty:property inContext:context])
1804 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1808 const char *string(CYPoolCString(pool, context, name));
1809 Class _class(object_getClass(self));
1812 if (objc_property_t property = class_getProperty(_class, string)) {
1813 PropertyAttributes attributes(property);
1814 SEL sel(sel_registerName(attributes.Getter()));
1815 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1819 if (CYHasImplicitProperties(_class))
1820 if (SEL sel = sel_getUid(string))
1821 if (CYImplements(self, _class, sel, true))
1822 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1827 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1828 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1829 id self(internal->GetValue());
1833 NSString *name(CYCastNSString(&pool, context, property));
1834 NSObject *data(CYCastNSObject(&pool, context, value));
1837 if ([self cy$setProperty:name to:data])
1839 } CYPoolCatch(false)
1841 const char *string(CYPoolCString(pool, context, name));
1842 Class _class(object_getClass(self));
1845 if (objc_property_t property = class_getProperty(_class, string)) {
1846 PropertyAttributes attributes(property);
1847 if (const char *setter = attributes.Setter()) {
1848 SEL sel(sel_registerName(setter));
1849 JSValueRef arguments[1] = {value};
1850 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1856 size_t length(strlen(string));
1858 char set[length + 5];
1864 if (string[0] != '\0') {
1865 set[3] = toupper(string[0]);
1866 memcpy(set + 4, string + 1, length - 1);
1869 set[length + 3] = ':';
1870 set[length + 4] = '\0';
1872 if (SEL sel = sel_getUid(set))
1873 if (CYImplements(self, _class, sel)) {
1874 JSValueRef arguments[1] = {value};
1875 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1879 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1880 [internal setProperty:property toValue:value inContext:context];
1887 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1888 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1889 id self(internal->GetValue());
1892 NSString *name(CYCastNSString(NULL, context, property));
1893 return [self cy$deleteProperty:name];
1894 } CYPoolCatch(false)
1895 } CYCatch(false) return /*XXX*/ false; }
1897 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1898 const char *name(sel_getName(method_getName(method)));
1899 if (strchr(name, ':') != NULL)
1902 const char *type(method_getTypeEncoding(method));
1903 if (type == NULL || *type == '\0' || *type == 'v')
1906 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1909 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1910 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1911 id self(internal->GetValue());
1914 Class _class(object_getClass(self));
1919 objc_property_t *data(class_copyPropertyList(_class, &size));
1920 for (size_t i(0); i != size; ++i)
1921 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1926 if (CYHasImplicitProperties(_class))
1927 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1928 #if OBJC_API_VERSION >= 2
1930 objc_method **data(class_copyMethodList(current, &size));
1931 for (size_t i(0); i != size; ++i)
1932 Instance_getPropertyNames_message(names, data[i]);
1935 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1936 for (int i(0); i != methods->method_count; ++i)
1937 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1942 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1943 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1944 [self cy$getPropertyNames:names inContext:context];
1948 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1949 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1950 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1954 static const char *CYBlockEncoding(NSBlock *self) {
1955 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1956 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1958 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1959 descriptor += sizeof(BlockDescriptor1);
1960 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1961 descriptor += sizeof(BlockDescriptor2);
1962 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1963 return descriptor3->signature;
1966 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1967 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1968 id self(internal->GetValue());
1970 if (const char *encoding = CYBlockEncoding(self)) {
1976 sig::Signature signature;
1977 sig::Parse(pool, &signature, encoding, &Structor_);
1980 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1982 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1983 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1984 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1988 CYThrow("NSBlock without signature field passed arguments");
1992 } CYPoolCatch(NULL);
1997 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1998 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1999 Class _class(internal->GetValue());
2000 if (!CYIsClass(_class))
2003 if (CYJSValueIsNSObject(context, instance)) {
2004 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2005 // XXX: this isn't always safe
2006 return [linternal->GetValue() isKindOfClass:_class];
2012 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2014 throw CYJSError(context, "incorrect number of arguments to Instance");
2016 id value(CYCastNSObject(&pool, context, arguments[0]));
2018 value = [NSNull null];
2019 return CYCastJSValue(context, [value cy$box]);
2022 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2023 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2026 id self(internal->GetValue());
2027 const char *name(CYPoolCString(pool, context, property));
2029 if (object_getInstanceVariable(self, name, NULL) != NULL)
2035 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2036 length = CYCastDouble(encoding + 1);
2040 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2041 for (size_t i(0); i != size; ++i)
2042 if (ivars[i] == ivar)
2044 else if (ivar_getOffset(ivars[i]) == offset) {
2045 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2046 _assert(encoding[0] == 'b');
2047 shift += CYCastDouble(encoding + 1);
2052 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2053 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2056 id self(internal->GetValue());
2057 const char *name(CYPoolCString(pool, context, property));
2060 if (strcmp(name, "isa") == 0)
2061 return CYCastJSValue(context, object_getClass(self));
2064 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2065 ptrdiff_t offset(ivar_getOffset(ivar));
2066 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2068 const char *encoding(ivar_getTypeEncoding(ivar));
2069 if (encoding[0] == 'b') {
2070 unsigned length, shift;
2071 CYBitField(length, shift, self, ivar, encoding, offset);
2072 _assert(shift + length <= sizeof(uintptr_t) * 8);
2073 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2074 uintptr_t mask((1 << length) - 1);
2075 return CYCastJSValue(context, (field >> shift) & mask);
2077 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2078 return CYFromFFI(context, type.type_, type.GetFFI(), data);
2085 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2086 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2089 id self(internal->GetValue());
2090 const char *name(CYPoolCString(pool, context, property));
2092 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2093 ptrdiff_t offset(ivar_getOffset(ivar));
2094 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2096 const char *encoding(ivar_getTypeEncoding(ivar));
2097 if (encoding[0] == 'b') {
2098 unsigned length, shift;
2099 CYBitField(length, shift, self, ivar, encoding, offset);
2100 _assert(shift + length <= sizeof(uintptr_t) * 8);
2101 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2102 uintptr_t mask((1 << length) - 1);
2103 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2105 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2106 CYPoolFFI(&pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2114 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2115 if (Class super = class_getSuperclass(_class))
2116 Internal_getPropertyNames_(super, names);
2118 #if OBJC_API_VERSION >= 2
2120 objc_ivar **data(class_copyIvarList(_class, &size));
2121 for (size_t i(0); i != size; ++i)
2122 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2125 if (objc_ivar_list *ivars = _class->ivars)
2126 for (int i(0); i != ivars->ivar_count; ++i)
2127 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2131 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2132 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2135 id self(internal->GetValue());
2136 Class _class(object_getClass(self));
2138 Internal_getPropertyNames_(_class, names);
2141 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2142 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2143 return internal->GetOwner();
2146 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2148 NSString *name(CYCastNSString(&pool, context, property));
2149 if (Class _class = NSClassFromString(name))
2150 return CYMakeInstance(context, _class, true);
2155 static Class *CYCopyClassList(size_t &size) {
2156 size = objc_getClassList(NULL, 0);
2157 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2160 size_t writ(objc_getClassList(data, size));
2166 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2178 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2181 if (Class *data = CYCopyClassList(size)) {
2182 for (size_t i(0); i != size; ++i)
2183 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2188 while (Class _class = objc_next_class(&state))
2189 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2193 #if OBJC_API_VERSION >= 2
2194 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2195 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2198 const char *name(CYPoolCString(pool, context, property));
2200 const char **data(objc_copyClassNamesForImage(internal, &size));
2202 for (size_t i(0); i != size; ++i)
2203 if (strcmp(name, data[i]) == 0) {
2204 if (Class _class = objc_getClass(name)) {
2205 value = CYMakeInstance(context, _class, true);
2216 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2217 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2219 const char **data(objc_copyClassNamesForImage(internal, &size));
2220 for (size_t i(0); i != size; ++i)
2221 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2225 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2227 const char *name(CYPoolCString(pool, context, property));
2229 const char **data(objc_copyImageNames(&size));
2230 for (size_t i(0); i != size; ++i)
2231 if (strcmp(name, data[i]) == 0) {
2240 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2241 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2245 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2247 const char **data(objc_copyImageNames(&size));
2248 for (size_t i(0); i != size; ++i)
2249 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2254 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2256 const char *name(CYPoolCString(pool, context, property));
2257 if (Protocol *protocol = objc_getProtocol(name))
2258 return CYMakeInstance(context, protocol, true);
2262 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2263 #if OBJC_API_VERSION >= 2
2265 Protocol **data(objc_copyProtocolList(&size));
2266 for (size_t i(0); i != size; ++i)
2267 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2274 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2276 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2278 return Instance::Make(context, nil);
2282 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2283 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2287 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2288 *data = reinterpret_cast<void *>(address);
2289 return KERN_SUCCESS;
2293 std::set<Class> query_;
2294 JSContextRef context_;
2295 JSObjectRef results_;
2298 struct CYObjectStruct {
2302 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2303 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2304 JSContextRef context(choice->context_);
2306 for (unsigned i(0); i != count; ++i) {
2307 vm_range_t &range(ranges[i]);
2308 void *data(reinterpret_cast<void *>(range.address));
2309 size_t size(range.size);
2311 if (size < sizeof(CYObjectStruct))
2314 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2316 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2318 Class isa(reinterpret_cast<Class>(pointers[0]));
2321 std::set<Class>::const_iterator result(choice->query_.find(isa));
2322 if (result == choice->query_.end())
2325 size_t needed(class_getInstanceSize(*result));
2326 // XXX: if (size < needed)
2327 if (needed <= 496 && (needed + 15) / 16 * 16 != size || needed > 496 && (needed + 511) / 512 * 512 != size)
2329 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2333 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2335 throw CYJSError(context, "choose() takes a class argument");
2337 CYGarbageCollect(context);
2340 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2342 vm_address_t *zones(NULL);
2344 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2345 _assert(error == KERN_SUCCESS);
2347 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2348 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2351 choice.context_ = context;
2352 choice.results_ = results;
2355 Class *classes(CYCopyClassList(number));
2356 _assert(classes != NULL);
2358 for (size_t i(0); i != number; ++i)
2359 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2360 if (current == _class) {
2361 choice.query_.insert(classes[i]);
2367 for (unsigned i(0); i != size; ++i) {
2368 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2369 if (zone == NULL || zone->introspect == NULL)
2372 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2380 #if defined(__i386__) || defined(__x86_64__)
2381 #define OBJC_MAX_STRUCT_BY_VALUE 8
2382 static int struct_forward_array[] = {
2383 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2384 #elif defined(__arm__)
2385 #define OBJC_MAX_STRUCT_BY_VALUE 1
2386 static int struct_forward_array[] = {
2388 #elif defined(__arm64__)
2391 #error missing objc-runtime-info
2395 static bool stret(ffi_type *ffi_type) {
2396 return ffi_type->type == FFI_TYPE_STRUCT && (
2397 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2398 struct_forward_array[ffi_type->size] != 0
2404 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2408 _class = object_getClass(self);
2412 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2413 imp = method_getImplementation(method);
2414 type = method_getTypeEncoding(method);
2419 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2421 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2422 type = CYPoolCString(pool, context, [method _typeString]);
2430 sig::Signature signature;
2431 sig::Parse(pool, &signature, type, &Structor_);
2433 size_t used(count + 3);
2434 if (used > signature.count) {
2435 sig::Element *elements(new (pool) sig::Element[used]);
2436 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2438 for (size_t index(signature.count); index != used; ++index) {
2439 sig::Element *element(&elements[index]);
2440 element->name = NULL;
2441 element->offset = _not(size_t);
2443 sig::Type *type(new (pool) sig::Type);
2444 memset(type, 0, sizeof(*type));
2445 type->primitive = sig::object_P;
2446 element->type = type;
2449 signature.elements = elements;
2450 signature.count = used;
2454 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2459 if (stret(cif.rtype))
2460 imp = class_getMethodImplementation_stret(_class, _cmd);
2463 imp = class_getMethodImplementation(_class, _cmd);
2465 objc_super super = {self, _class};
2466 imp = objc_msg_lookup_super(&super, _cmd);
2470 void (*function)() = reinterpret_cast<void (*)()>(imp);
2471 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2474 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2476 throw CYJSError(context, "too few arguments to objc_msgSend");
2486 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2487 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2488 self = internal->GetValue();
2489 _class = internal->class_;;
2490 uninitialized = false;
2491 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2492 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2493 self = internal->GetValue();
2495 uninitialized = internal->IsUninitialized();
2497 internal->value_ = nil;
2499 self = CYCastNSObject(&pool, context, arguments[0]);
2501 uninitialized = false;
2505 return CYJSNull(context);
2507 _cmd = CYCastSEL(context, arguments[1]);
2509 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2512 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2513 return $objc_msgSend(context, object, _this, count, arguments);
2516 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2517 JSValueRef setup[count + 2];
2520 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2521 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2524 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2526 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2528 // XXX: handle Instance::Uninitialized?
2529 id self(CYCastNSObject(&pool, context, _this));
2533 setup[1] = &internal->sel_;
2535 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2538 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2540 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2542 id self(CYCastNSObject(&pool, context, arguments[0]));
2543 Class _class(CYCastClass(pool, context, arguments[1]));
2544 return cy::Super::Make(context, self, _class);
2547 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2549 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2551 const char *name(CYPoolCString(pool, context, arguments[0]));
2552 return CYMakeSelector(context, sel_registerName(name));
2555 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2557 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2558 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2559 return CYMakeInstance(context, self, false);
2562 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2563 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2564 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2567 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2568 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2569 Type_privateData *typical(internal->GetType());
2574 if (typical == NULL) {
2578 type = typical->type_;
2579 ffi = typical->ffi_;
2582 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2585 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2586 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2587 const char *encoding(CYBlockEncoding(internal->GetValue()));
2588 if (encoding == NULL)
2589 return CYJSNull(context);
2590 // XXX: this should be stored on a FunctionInstance private value subclass
2592 sig::Signature signature;
2593 sig::Parse(pool, &signature, encoding, &Structor_);
2594 return CYMakeType(context, &signature);
2597 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2598 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2599 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2602 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2603 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2604 id self(internal->GetValue());
2605 if (!CYIsClass(self))
2606 return CYJSUndefined(context);
2607 return CYGetClassPrototype(context, self);
2610 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2611 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2612 id self(internal->GetValue());
2613 if (!CYIsClass(self))
2614 return CYJSUndefined(context);
2615 return Messages::Make(context, (Class) self);
2618 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2619 if (!CYJSValueIsNSObject(context, _this))
2622 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2623 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2626 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2627 if (!CYJSValueIsNSObject(context, _this))
2630 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2631 id value(internal->GetValue());
2638 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2640 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2641 return CYJSUndefined(context);
2642 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2645 return CYCastJSValue(context, CYJSString(context, [value description]));
2647 } CYCatch(NULL) return /*XXX*/ NULL; }
2649 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2650 if (!CYJSValueIsNSObject(context, _this))
2653 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2654 id value(internal->GetValue());
2656 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2659 if (JSValueRef result = [value cy$valueOfInContext:context])
2663 } CYCatch(NULL) return /*XXX*/ NULL; }
2665 static JSValueRef Instance_callAsFunction_toPointer(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 // XXX: but... but... THIS ISN'T A POINTER! :(
2671 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2672 } CYCatch(NULL) return /*XXX*/ NULL; }
2674 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2675 if (!CYJSValueIsNSObject(context, _this))
2678 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2679 id value(internal->GetValue());
2682 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2683 return CYCastJSValue(context, CYJSString(context, [value description]));
2685 } CYCatch(NULL) return /*XXX*/ NULL; }
2687 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2688 if (!CYJSValueIsNSObject(context, _this))
2691 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2692 id value(internal->GetValue());
2694 if (!CYIsClass(value))
2695 CYThrow("non-Class object cannot be used as Type");
2697 // XXX: this is a very silly implementation
2699 std::ostringstream type;
2701 type << class_getName(value);
2705 return CYMakeType(context, type.str().c_str());
2707 } CYCatch(NULL) return /*XXX*/ NULL; }
2709 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2710 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2711 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2714 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2715 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2718 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2719 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2720 const char *name(sel_getName(internal->GetValue()));
2723 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2724 return CYCastJSValue(context, CYJSString(context, string));
2726 } CYCatch(NULL) return /*XXX*/ NULL; }
2728 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2730 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2733 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2734 SEL sel(internal->GetValue());
2736 objc_method *method;
2737 if (Class _class = CYCastClass(pool, context, arguments[0]))
2738 method = class_getInstanceMethod(_class, sel);
2742 const char *encoding(CYPoolTypeEncoding(pool, context, sel, method));
2743 if (encoding == NULL)
2744 return CYJSNull(context);
2746 sig::Signature signature;
2747 sig::Parse(pool, &signature, encoding, &Structor_);
2748 return CYMakeType(context, &signature);
2751 static JSStaticValue Selector_staticValues[2] = {
2752 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2753 {NULL, NULL, NULL, 0}
2756 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2757 static JSStaticValue Instance_staticValues[5] = {
2758 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2759 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2760 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2761 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2762 {NULL, NULL, NULL, 0}
2765 static JSStaticValue FunctionInstance_staticValues[6] = {
2766 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2767 // XXX: this is sadly a duplicate of Instance_staticValues
2768 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2769 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2770 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2771 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2772 {NULL, NULL, NULL, 0}
2775 static JSStaticFunction Instance_staticFunctions[7] = {
2776 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2777 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2778 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2779 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2780 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2781 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2785 static JSStaticFunction Class_staticFunctions[2] = {
2786 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2790 static JSStaticFunction Internal_staticFunctions[2] = {
2791 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2795 static JSStaticFunction Selector_staticFunctions[5] = {
2796 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2797 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2798 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2799 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2804 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2805 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2806 } CYObjectiveCatch }
2809 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2810 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2811 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2812 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2814 CYPool &pool(CYGetGlobalPool());
2816 Object_type = new(pool) Type_privateData("@");
2817 Selector_type = new(pool) Type_privateData(":");
2819 NSArray_ = objc_getClass("NSArray");
2820 NSBlock_ = objc_getClass("NSBlock");
2821 NSDictionary_ = objc_getClass("NSDictionary");
2822 NSNumber_ = objc_getClass("NSNumber");
2823 NSString_ = objc_getClass("NSString");
2824 Object_ = objc_getClass("Object");
2827 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2829 // XXX: apparently, iOS now has both of these
2830 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2831 if (NSCFBoolean_ == nil)
2832 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2834 NSCFType_ = objc_getClass("NSCFType");
2836 NSZombie_ = objc_getClass("_NSZombie_");
2838 banned_.insert(Object_);
2839 banned_.insert(objc_getClass("__NSAtom"));
2840 banned_.insert(objc_getClass("__NSGenericDeallocHandler"));
2841 banned_.insert(objc_getClass("NSMessageBuilder"));
2842 banned_.insert(objc_getClass("__NSMessageBuilder"));
2844 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2847 JSClassDefinition definition;
2849 definition = kJSClassDefinitionEmpty;
2850 definition.className = "Instance";
2851 definition.staticValues = Instance_staticValues;
2852 definition.staticFunctions = Instance_staticFunctions;
2853 definition.hasProperty = &Instance_hasProperty;
2854 definition.getProperty = &Instance_getProperty;
2855 definition.setProperty = &Instance_setProperty;
2856 definition.deleteProperty = &Instance_deleteProperty;
2857 definition.getPropertyNames = &Instance_getPropertyNames;
2858 definition.callAsConstructor = &Instance_callAsConstructor;
2859 definition.hasInstance = &Instance_hasInstance;
2860 definition.finalize = &CYFinalize;
2861 Instance_ = JSClassCreate(&definition);
2863 definition.className = "ArrayInstance";
2864 ArrayInstance_ = JSClassCreate(&definition);
2866 definition.className = "BooleanInstance";
2867 BooleanInstance_ = JSClassCreate(&definition);
2869 definition.className = "NumberInstance";
2870 NumberInstance_ = JSClassCreate(&definition);
2872 definition.className = "ObjectInstance";
2873 ObjectInstance_ = JSClassCreate(&definition);
2875 definition.className = "StringInstance";
2876 StringInstance_ = JSClassCreate(&definition);
2878 definition.className = "FunctionInstance";
2879 definition.staticValues = FunctionInstance_staticValues;
2880 definition.callAsFunction = &FunctionInstance_callAsFunction;
2881 FunctionInstance_ = JSClassCreate(&definition);
2883 definition = kJSClassDefinitionEmpty;
2884 definition.className = "Class";
2885 definition.staticFunctions = Class_staticFunctions;
2886 Class_ = JSClassCreate(&definition);
2888 definition = kJSClassDefinitionEmpty;
2889 definition.className = "Internal";
2890 definition.staticFunctions = Internal_staticFunctions;
2891 definition.hasProperty = &Internal_hasProperty;
2892 definition.getProperty = &Internal_getProperty;
2893 definition.setProperty = &Internal_setProperty;
2894 definition.getPropertyNames = &Internal_getPropertyNames;
2895 definition.finalize = &CYFinalize;
2896 Internal_ = JSClassCreate(&definition);
2898 definition = kJSClassDefinitionEmpty;
2899 definition.className = "Message";
2900 definition.staticFunctions = cy::Functor::StaticFunctions;
2901 definition.staticValues = cy::Functor::StaticValues;
2902 definition.callAsFunction = &Message_callAsFunction;
2903 definition.finalize = &CYFinalize;
2904 Message_ = JSClassCreate(&definition);
2906 definition = kJSClassDefinitionEmpty;
2907 definition.className = "Messages";
2908 definition.hasProperty = &Messages_hasProperty;
2909 definition.getProperty = &Messages_getProperty;
2910 definition.setProperty = &Messages_setProperty;
2911 #if 0 && OBJC_API_VERSION < 2
2912 definition.deleteProperty = &Messages_deleteProperty;
2914 definition.getPropertyNames = &Messages_getPropertyNames;
2915 definition.finalize = &CYFinalize;
2916 Messages_ = JSClassCreate(&definition);
2918 definition = kJSClassDefinitionEmpty;
2919 definition.className = "Selector";
2920 definition.staticValues = Selector_staticValues;
2921 definition.staticFunctions = Selector_staticFunctions;
2922 definition.callAsFunction = &Selector_callAsFunction;
2923 definition.finalize = &CYFinalize;
2924 Selector_ = JSClassCreate(&definition);
2926 definition = kJSClassDefinitionEmpty;
2927 definition.className = "Super";
2928 definition.staticFunctions = Internal_staticFunctions;
2929 definition.finalize = &CYFinalize;
2930 Super_ = JSClassCreate(&definition);
2932 definition = kJSClassDefinitionEmpty;
2933 definition.className = "ObjectiveC::Classes";
2934 definition.getProperty = &ObjectiveC_Classes_getProperty;
2935 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2936 ObjectiveC_Classes_ = JSClassCreate(&definition);
2938 definition = kJSClassDefinitionEmpty;
2939 definition.className = "ObjectiveC::Constants";
2940 definition.getProperty = &ObjectiveC_Constants_getProperty;
2941 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2942 ObjectiveC_Constants_ = JSClassCreate(&definition);
2944 #if OBJC_API_VERSION >= 2
2945 definition = kJSClassDefinitionEmpty;
2946 definition.className = "ObjectiveC::Images";
2947 definition.getProperty = &ObjectiveC_Images_getProperty;
2948 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2949 ObjectiveC_Images_ = JSClassCreate(&definition);
2951 definition = kJSClassDefinitionEmpty;
2952 definition.className = "ObjectiveC::Image::Classes";
2953 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2954 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2955 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2958 definition = kJSClassDefinitionEmpty;
2959 definition.className = "ObjectiveC::Protocols";
2960 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2961 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2962 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2965 // XXX: this is horrible; there has to be a better way to do this
2967 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24");
2969 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2974 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2975 JSObjectRef global(CYGetGlobalObject(context));
2976 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2977 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2978 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2979 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2981 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2982 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2984 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2985 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2986 CYArrayPush(context, alls, protocols);
2988 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2989 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2990 CYArrayPush(context, alls, classes);
2992 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2993 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2994 CYArrayPush(context, alls, constants);
2996 #if OBJC_API_VERSION >= 2
2997 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3000 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
3001 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3002 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3003 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3004 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
3006 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
3007 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3009 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
3010 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
3011 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
3012 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
3013 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
3015 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
3016 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
3017 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
3018 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
3019 JSObjectSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
3021 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
3022 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
3023 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
3024 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
3025 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
3027 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
3028 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
3029 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
3030 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
3031 JSObjectSetPrototype(context, NumberInstance_prototype, Number_prototype);
3033 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3034 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3035 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3036 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3037 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3039 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3040 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3041 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3042 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3043 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
3045 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
3046 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
3047 JSObjectSetPrototype(context, Class_prototype, Instance_prototype);
3049 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3050 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3051 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3053 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3054 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3057 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3060 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3062 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3063 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3066 static CYHooks CYObjectiveCHooks = {
3067 &CYObjectiveC_ExecuteStart,
3068 &CYObjectiveC_ExecuteEnd,
3069 &CYObjectiveC_CallFunction,
3070 &CYObjectiveC_Initialize,
3071 &CYObjectiveC_SetupContext,
3072 &CYObjectiveC_PoolFFI,
3073 &CYObjectiveC_FromFFI,
3076 struct CYObjectiveC {
3078 hooks_ = &CYObjectiveCHooks;
3079 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
3080 _assert(hooks_ != NULL);
3084 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3085 CYSetupContext(context);
3086 } CYObjectiveCatch }
3088 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3091 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3092 utf8 = CYPoolCode(pool, utf8);
3094 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3095 size_t bytes(utf16.size * sizeof(uint16_t));
3096 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3097 memcpy(copy, utf16.data, bytes);
3101 } catch (const CYException &exception) {
3103 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];