1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2015 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "cycript.hpp"
32 #include <malloc/malloc.h>
33 #include <mach/mach.h>
36 #include <objc/message.h>
37 #include <objc/runtime.h>
40 #include <CoreFoundation/CoreFoundation.h>
41 #include <JavaScriptCore/JSStringRefCF.h>
44 #include <Foundation/Foundation.h>
49 #include "JavaScript.hpp"
51 #include "Execute.hpp"
53 #include "ObjectiveC/Internal.hpp"
54 #include "ObjectiveC/Syntax.hpp"
56 #define CYObjectiveTry_ { \
58 #define CYObjectiveTry { \
59 JSContextRef context(context_); \
61 #define CYObjectiveCatch \
62 catch (const CYException &error) { \
63 @throw CYCastNSObject(NULL, context, error.CastJSValue(context, "Error")); \
69 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
71 #define CYPoolCatch(value) \
72 @catch (NSException *error) { \
73 _saved = [error retain]; \
74 throw CYJSError(context, CYCastJSValue(context, error)); \
79 [_saved autorelease]; \
85 #define CYSadCatch(value) \
86 @catch (NSException *error ) { \
87 throw CYJSError(context, CYCastJSValue(context, error)); \
91 #define _oassert(test) \
93 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"_assert(" #test ")" userInfo:nil];
101 void (*invoke)(void *, ...);
105 struct BlockDescriptor1 {
106 unsigned long int reserved;
107 unsigned long int size;
110 struct BlockDescriptor2 {
111 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
112 void (*dispose_helper)(BlockLiteral *src);
115 struct BlockDescriptor3 {
116 const char *signature;
121 BLOCK_DEALLOCATING = 0x0001,
122 BLOCK_REFCOUNT_MASK = 0xfffe,
123 BLOCK_NEEDS_FREE = 1 << 24,
124 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
125 BLOCK_HAS_CTOR = 1 << 26,
126 BLOCK_IS_GC = 1 << 27,
127 BLOCK_IS_GLOBAL = 1 << 28,
128 BLOCK_HAS_STRET = 1 << 29,
129 BLOCK_HAS_SIGNATURE = 1 << 30,
132 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
134 /* Objective-C Pool Release {{{ */
135 void CYPoolRelease_(void *data) {
136 id object(reinterpret_cast<id>(data));
140 id CYPoolRelease_(CYPool *pool, id object) {
143 else if (pool == NULL)
144 return [object autorelease];
146 pool->atexit(CYPoolRelease_);
151 template <typename Type_>
152 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
153 return (Type_) CYPoolRelease_(pool, (id) object);
156 /* Objective-C Strings {{{ */
157 CYUTF8String CYPoolUTF8String(CYPool &pool, JSContextRef context, NSString *value) {
158 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
159 char *string(new(pool) char[size + 1]);
160 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
161 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
162 return CYUTF8String(string, [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
165 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
166 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
167 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
172 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
173 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
177 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
180 // XXX: this definition scares me; is anyone using this?!
181 NSString *string([value description]);
183 return CYCopyJSString(context, string);
186 return CYCopyJSString(CYPoolUTF8String(pool, context, string));
190 NSString *CYCopyNSString(const CYUTF8String &value) {
192 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
194 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
198 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
200 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
203 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
207 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
208 return CYCopyNSString(context, CYJSString(context, value));
211 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
212 return CYPoolRelease(pool, CYCopyNSString(value));
215 NSString *CYCastNSString(CYPool *pool, SEL sel) {
216 const char *name(sel_getName(sel));
217 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
220 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
221 return CYPoolRelease(pool, CYCopyNSString(context, value));
224 CYUTF8String CYCastUTF8String(NSString *value) {
225 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
226 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
230 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
232 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
233 if (exception == NULL)
235 *exception = CYCastJSValue(context, error);
238 size_t CYGetIndex(NSString *value) {
239 return CYGetIndex(CYCastUTF8String(value));
242 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
243 return CYGetOffset(CYPoolCString(pool, context, value), index);
246 static JSClassRef ArrayInstance_;
247 static JSClassRef BooleanInstance_;
248 static JSClassRef ClassInstance_;
249 static JSClassRef FunctionInstance_;
250 static JSClassRef NumberInstance_;
251 static JSClassRef ObjectInstance_;
252 static JSClassRef StringInstance_;
254 static JSClassRef ObjectiveC_Classes_;
255 static JSClassRef ObjectiveC_Constants_;
256 static JSClassRef ObjectiveC_Protocols_;
259 static JSClassRef ObjectiveC_Image_Classes_;
260 static JSClassRef ObjectiveC_Images_;
264 static Class __NSMallocBlock__;
265 static Class NSCFBoolean_;
266 static Class NSCFType_;
267 static Class NSGenericDeallocHandler_;
269 static Class NSBoolNumber_;
272 static Class NSArray_;
273 static Class NSBlock_;
274 static Class NSDictionary_;
275 static Class NSNumber_;
276 static Class NSString_;
277 static Class NSZombie_;
278 static Class Object_;
280 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
282 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
284 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
285 else if (meta && !class_isMetaClass(self))
286 return CYGetCachedObject(context, CYJSString("ClassInstance_prototype"));
288 JSObjectRef global(CYGetGlobalObject(context));
289 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
292 sprintf(label, "i%p", self);
293 CYJSString name(label);
295 JSValueRef value(CYGetProperty(context, cy, name));
296 if (!JSValueIsUndefined(context, value))
299 JSClassRef _class(NULL);
300 JSValueRef prototype;
303 if (self == NSCFBoolean_)
305 if (self == NSBoolNumber_)
307 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
308 else if (self == NSArray_)
309 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
310 else if (self == NSBlock_)
311 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
312 else if (self == NSNumber_)
313 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
314 else if (self == NSDictionary_)
315 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
316 else if (self == NSString_)
317 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
319 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
321 JSObjectRef object(JSObjectMake(context, _class, NULL));
322 CYSetPrototype(context, object, prototype);
323 CYSetProperty(context, cy, name, object);
328 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
329 return CYGetClassPrototype(context, self, class_isMetaClass(self));
332 JSValueRef Messages::GetPrototype(JSContextRef context) const {
333 if (Class super = class_getSuperclass(GetValue()))
334 return Messages::Make(context, super);
338 bool CYIsKindOfClass(id object, Class _class) {
339 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
345 JSValueRef Instance::GetPrototype(JSContextRef context) const {
346 return CYGetClassPrototype(context, object_getClass(GetValue()));
349 JSClassRef Instance::GetClass(id object, Flags flags) {
350 return CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance::Class_;
353 Instance::Instance(id value, Flags flags) :
357 if ((flags & Instance::Permanent) == 0)
358 value_ = [GetValue() retain];
361 Instance::~Instance() {
362 if ((flags_ & Permanent) == 0)
363 [GetValue() release];
366 struct Message_privateData :
369 static JSClassRef Class_;
373 Message_privateData(SEL sel, const char *type, IMP value) :
374 cy::Functor(reinterpret_cast<void (*)()>(value), type),
379 static JSObjectRef Make(JSContextRef context, SEL sel, const char *type, IMP value);
382 JSClassRef Message_privateData::Class_;
384 JSObjectRef CYMakeInstance(JSContextRef context, id object, Instance::Flags flags = Instance::None) {
385 _assert(object != nil);
388 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
390 if (weak != NULL && &JSWeakObjectMapGet != NULL)
391 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
395 JSObjectRef instance(Instance::Make(context, object, flags));
398 if (weak != NULL && &JSWeakObjectMapSet != NULL)
399 JSWeakObjectMapSet(context, weak, object, instance);
405 @interface NSMethodSignature (Cycript)
406 - (NSString *) _typeString;
409 @interface NSObject (Cycript)
411 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
412 - (JSType) cy$JSType;
414 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
415 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
417 - (bool) cy$hasProperty:(NSString *)name;
418 - (NSObject *) cy$getProperty:(NSString *)name;
419 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
420 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
421 - (bool) cy$deleteProperty:(NSString *)name;
422 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
424 + (bool) cy$hasImplicitProperties;
430 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
433 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
434 _assert(value != nil);
436 Class _class(object_getClass(value));
438 if (class_isMetaClass(_class)) {
439 const char *name(class_getName(value));
440 if (class_isMetaClass(value))
441 return [NSString stringWithFormat:@"object_getClass(%s)", name];
443 return [NSString stringWithUTF8String:name];
446 if (_class == NSZombie_)
447 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
449 SEL sel(@selector(cy$toCYON:inSet:));
451 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
452 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
453 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
454 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
455 return [value cy$toCYON:objective inSet:objects];
457 return [NSString stringWithFormat:@"%@", value];
460 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
462 return CYCastNSCYON(value, objective, *objects);
464 std::set<void *> objects;
465 return CYCastNSCYON(value, objective, objects);
469 struct PropertyAttributes {
474 const char *variable;
487 PropertyAttributes(objc_property_t property) :
499 name = property_getName(property);
500 const char *attributes(property_getAttributes(property));
502 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
503 if ((next = strchr(token, ',')) != NULL)
506 case 'R': readonly = true; break;
507 case 'C': copy = true; break;
508 case '&': retain = true; break;
509 case 'N': nonatomic = true; break;
510 case 'G': getter_ = token + 1; break;
511 case 'S': setter_ = token + 1; break;
512 case 'V': variable = token + 1; break;
516 /*if (variable == NULL) {
517 variable = property_getName(property);
518 size_t size(strlen(variable));
519 char *name(new(pool_) char[size + 2]);
521 memcpy(name + 1, variable, size);
522 name[size + 1] = '\0';
527 const char *Getter() {
529 getter_ = pool_.strdup(name);
533 const char *Setter() {
534 if (setter_ == NULL && !readonly) {
535 size_t length(strlen(name));
537 char *temp(new(pool_) char[length + 5]);
543 temp[3] = toupper(name[0]);
544 memcpy(temp + 4, name + 1, length - 1);
547 temp[length + 3] = ':';
548 temp[length + 4] = '\0';
557 @interface CYWebUndefined : NSObject {
560 + (CYWebUndefined *) undefined;
564 @implementation CYWebUndefined
566 + (CYWebUndefined *) undefined {
567 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
573 #define WebUndefined CYWebUndefined
575 /* Bridge: CYJSObject {{{ */
576 @interface CYJSObject : NSMutableDictionary {
578 JSGlobalContextRef context_;
581 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
583 - (NSUInteger) count;
584 - (id) objectForKey:(id)key;
585 - (NSEnumerator *) keyEnumerator;
586 - (void) setObject:(id)object forKey:(id)key;
587 - (void) removeObjectForKey:(id)key;
591 /* Bridge: CYJSArray {{{ */
592 @interface CYJSArray : NSMutableArray {
594 JSGlobalContextRef context_;
597 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
599 - (NSUInteger) count;
600 - (id) objectAtIndex:(NSUInteger)index;
602 - (void) addObject:(id)anObject;
603 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
604 - (void) removeLastObject;
605 - (void) removeObjectAtIndex:(NSUInteger)index;
606 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
611 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
612 return JSValueIsObjectOfClass(context, value, Instance::Class_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
615 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
616 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
620 struct CYBlockDescriptor {
622 BlockDescriptor1 one_;
623 BlockDescriptor2 two_;
624 BlockDescriptor3 three_;
627 Closure_privateData *internal_;
630 void CYDisposeBlock(BlockLiteral *literal) {
631 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
634 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
635 JSObjectRef _this(CYCastJSObject(context, values[0]));
636 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
639 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
640 _assert(__NSMallocBlock__ != Nil);
641 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
643 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
644 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
646 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockAdapter_);
647 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
649 literal->isa = __NSMallocBlock__;
650 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
651 literal->reserved = 0;
652 literal->descriptor = descriptor;
654 descriptor->d_.one_.size = sizeof(descriptor->d_);
655 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
656 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
658 return reinterpret_cast<NSBlock *>(literal);
662 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
663 if (CYJSValueIsNSObject(context, object)) {
664 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
665 return internal->GetValue();
668 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
669 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
670 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
673 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
674 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
678 @interface NSBoolNumber : NSNumber {
683 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
687 switch (JSType type = JSValueGetType(context, value)) {
688 case kJSTypeUndefined:
689 object = [WebUndefined undefined];
699 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
702 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
708 object = CYCopyNSNumber(context, value);
713 object = CYCopyNSString(context, value);
718 // XXX: this might could be more efficient
719 object = CYCastNSObject(pool, context, (JSObjectRef) value);
724 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
731 return CYPoolRelease(pool, object);
733 return [object retain];
736 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
737 return CYNSObject(pool, context, value, true);
740 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
741 return CYNSObject(&pool, context, value, false);
744 /* Bridge: NSArray {{{ */
745 @implementation NSArray (Cycript)
748 return [[self mutableCopy] autorelease];
751 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
752 _oassert(objects.insert(self).second);
754 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
755 [json appendString:@"@["];
759 for (id object in self) {
761 for (size_t index(0), count([self count]); index != count; ++index) {
762 id object([self objectAtIndex:index]);
765 [json appendString:@","];
768 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
769 [json appendString:CYCastNSCYON(object, true, objects)];
771 [json appendString:@","];
776 [json appendString:@"]"];
780 - (bool) cy$hasProperty:(NSString *)name {
781 if ([name isEqualToString:@"length"])
784 size_t index(CYGetIndex(name));
785 if (index == _not(size_t) || index >= [self count])
786 return [super cy$hasProperty:name];
791 - (NSObject *) cy$getProperty:(NSString *)name {
792 size_t index(CYGetIndex(name));
793 if (index == _not(size_t) || index >= [self count])
794 return [super cy$getProperty:name];
796 return [self objectAtIndex:index];
799 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
801 if ([name isEqualToString:@"length"])
802 return CYCastJSValue(context, [self count]);
805 return [super cy$getProperty:name inContext:context];
808 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
809 [super cy$getPropertyNames:names inContext:context];
811 for (size_t index(0), count([self count]); index != count; ++index) {
812 id object([self objectAtIndex:index]);
813 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
815 sprintf(name, "%zu", index);
816 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
821 + (bool) cy$hasImplicitProperties {
827 /* Bridge: NSBlock {{{ */
829 @interface NSBlock : NSObject
833 static const char *CYBlockEncoding(NSBlock *self);
834 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature);
836 @implementation NSBlock (Cycript)
838 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
842 if (!CYBlockSignature(pool, self, type.signature))
843 return [super cy$toCYON:objective inSet:objects];
844 _oassert(objects.insert(self).second);
846 CYTypedIdentifier *typed((new(pool) CYTypeExpression(CYDecodeType(pool, &type)))->typed_);
847 CYTypeModifier *&modifier(CYGetLast(typed->modifier_));
848 CYTypeBlockWith *with(dynamic_cast<CYTypeBlockWith *>(modifier));
849 _assert(with != NULL);
850 CYObjCBlock *block(new(pool) CYObjCBlock(typed, with->parameters_, NULL));
853 std::ostringstream str;
855 CYOutput out(*str.rdbuf(), options);
856 block->Output(out, CYNoFlags);
858 std::string value(str.str());
859 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
865 /* Bridge: NSBoolNumber {{{ */
867 @implementation NSBoolNumber (Cycript)
869 - (JSType) cy$JSType {
870 return kJSTypeBoolean;
873 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
874 NSString *value([self boolValue] ? @"true" : @"false");
875 return objective ? value : [NSString stringWithFormat:@"@%@", value];
878 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
879 return CYCastJSValue(context, (bool) [self boolValue]);
885 /* Bridge: NSDictionary {{{ */
886 @implementation NSDictionary (Cycript)
889 return [[self mutableCopy] autorelease];
892 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
893 _oassert(objects.insert(self).second);
895 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
896 [json appendString:@"@{"];
900 for (NSObject *key in self) {
902 NSEnumerator *keys([self keyEnumerator]);
903 while (NSObject *key = [keys nextObject]) {
906 [json appendString:@","];
909 [json appendString:CYCastNSCYON(key, true, objects)];
910 [json appendString:@":"];
911 NSObject *object([self objectForKey:key]);
912 [json appendString:CYCastNSCYON(object, true, objects)];
915 [json appendString:@"}"];
919 - (bool) cy$hasProperty:(NSString *)name {
920 return [self objectForKey:name] != nil;
923 - (NSObject *) cy$getProperty:(NSString *)name {
924 return [self objectForKey:name];
927 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
928 [super cy$getPropertyNames:names inContext:context];
931 for (NSObject *key in self) {
933 NSEnumerator *keys([self keyEnumerator]);
934 while (NSObject *key = [keys nextObject]) {
936 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
940 + (bool) cy$hasImplicitProperties {
946 /* Bridge: NSMutableArray {{{ */
947 @implementation NSMutableArray (Cycript)
949 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
950 if ([name isEqualToString:@"length"]) {
951 // XXX: is this not intelligent?
952 NSNumber *number(reinterpret_cast<NSNumber *>(value));
953 NSUInteger size([number unsignedIntegerValue]);
954 NSUInteger count([self count]);
956 [self removeObjectsInRange:NSMakeRange(size, count - size)];
957 else if (size != count) {
958 WebUndefined *undefined([WebUndefined undefined]);
959 for (size_t i(count); i != size; ++i)
960 [self addObject:undefined];
965 size_t index(CYGetIndex(name));
966 if (index == _not(size_t))
967 return [super cy$setProperty:name to:value];
969 id object(value ?: [NSNull null]);
971 size_t count([self count]);
973 [self replaceObjectAtIndex:index withObject:object];
975 if (index != count) {
976 WebUndefined *undefined([WebUndefined undefined]);
977 for (size_t i(count); i != index; ++i)
978 [self addObject:undefined];
981 [self addObject:object];
987 - (bool) cy$deleteProperty:(NSString *)name {
988 size_t index(CYGetIndex(name));
989 if (index == _not(size_t) || index >= [self count])
990 return [super cy$deleteProperty:name];
991 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
997 /* Bridge: NSMutableDictionary {{{ */
998 @implementation NSMutableDictionary (Cycript)
1000 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1001 [self setObject:(value ?: [NSNull null]) forKey:name];
1005 - (bool) cy$deleteProperty:(NSString *)name {
1006 if ([self objectForKey:name] == nil)
1009 [self removeObjectForKey:name];
1016 /* Bridge: NSNumber {{{ */
1017 @implementation NSNumber (Cycript)
1019 - (JSType) cy$JSType {
1021 // XXX: this just seems stupid
1022 if ([self class] == NSCFBoolean_)
1023 return kJSTypeBoolean;
1025 return kJSTypeNumber;
1028 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1029 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1030 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1033 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1034 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1035 } CYObjectiveCatch }
1039 /* Bridge: NSNull {{{ */
1040 @implementation NSNull (Cycript)
1042 - (JSType) cy$JSType {
1046 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1047 NSString *value(@"null");
1048 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1051 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1052 return CYJSNull(context);
1053 } CYObjectiveCatch }
1057 /* Bridge: NSObject {{{ */
1058 @implementation NSObject (Cycript)
1064 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1065 return [self cy$valueOfInContext:context];
1068 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1070 } CYObjectiveCatch }
1072 - (JSType) cy$JSType {
1073 return kJSTypeObject;
1076 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1077 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1080 - (bool) cy$hasProperty:(NSString *)name {
1084 - (NSObject *) cy$getProperty:(NSString *)name {
1088 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1089 if (NSObject *value = [self cy$getProperty:name])
1090 return CYCastJSValue(context, value);
1092 } CYObjectiveCatch }
1094 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1098 - (bool) cy$deleteProperty:(NSString *)name {
1102 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1105 + (bool) cy$hasImplicitProperties {
1111 /* Bridge: NSOrderedSet {{{ */
1113 @implementation NSOrderedSet (Cycript)
1115 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1116 _oassert(objects.insert(self).second);
1118 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1119 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1120 [json appendString:CYCastNSCYON([self array], true, objects)];
1121 [json appendString:@"]]"];
1128 /* Bridge: NSProxy {{{ */
1129 @implementation NSProxy (Cycript)
1131 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1132 return [[self description] cy$toCYON:objective inSet:objects];
1137 /* Bridge: NSSet {{{ */
1138 @implementation NSSet (Cycript)
1140 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1141 _oassert(objects.insert(self).second);
1143 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1144 [json appendString:@"[NSSet setWithArray:"];
1145 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1146 [json appendString:@"]]"];
1152 /* Bridge: NSString {{{ */
1153 @implementation NSString (Cycript)
1156 return [[self copy] autorelease];
1159 - (JSType) cy$JSType {
1160 return kJSTypeString;
1163 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1164 std::ostringstream str;
1167 CYUTF8String string(CYCastUTF8String(self));
1168 CYStringify(str, string.data, string.size, true);
1169 std::string value(str.str());
1170 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1173 - (bool) cy$hasProperty:(NSString *)name {
1174 size_t index(CYGetIndex(name));
1175 if (index == _not(size_t) || index >= [self length])
1176 return [super cy$hasProperty:name];
1181 - (NSObject *) cy$getProperty:(NSString *)name {
1182 size_t index(CYGetIndex(name));
1183 if (index == _not(size_t) || index >= [self length])
1184 return [super cy$getProperty:name];
1186 return [self substringWithRange:NSMakeRange(index, 1)];
1189 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1190 [super cy$getPropertyNames:names inContext:context];
1192 for (size_t index(0), length([self length]); index != length; ++index) {
1194 sprintf(name, "%zu", index);
1195 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1199 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1200 return CYCastJSValue(context, CYJSString(context, self));
1201 } CYObjectiveCatch }
1205 /* Bridge: WebUndefined {{{ */
1206 @implementation WebUndefined (Cycript)
1208 - (JSType) cy$JSType {
1209 return kJSTypeUndefined;
1212 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1213 NSString *value(@"undefined");
1214 return value; // XXX: maybe use the below code, adding @undefined?
1215 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1218 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1219 return CYJSUndefined(context);
1220 } CYObjectiveCatch }
1225 static bool CYIsClass(id self) {
1226 return class_isMetaClass(object_getClass(self));
1229 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1230 id self(CYCastNSObject(&pool, context, value));
1231 if (CYIsClass(self))
1232 return (Class) self;
1233 throw CYJSError(context, "got something that is not a Class");
1237 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1239 size_t size(JSPropertyNameArrayGetCount(names));
1240 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1241 for (size_t index(0); index != size; ++index)
1242 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1246 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) {
1248 return CYJSNull(context);
1249 return CYMakeInstance(context, value);
1252 @implementation CYJSObject
1254 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1255 if ((self = [super init]) != nil) {
1257 context_ = CYGetJSContext(context);
1258 JSGlobalContextRetain(context_);
1259 JSValueProtect(context_, object_);
1261 } CYObjectiveCatch }
1263 - (void) dealloc { CYObjectiveTry {
1264 JSValueUnprotect(context_, object_);
1265 JSGlobalContextRelease(context_);
1267 } CYObjectiveCatch }
1269 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1271 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1273 return [super cy$toCYON:objective inSet:objects];
1275 return [NSString stringWithUTF8String:cyon];
1276 } CYObjectiveCatch }
1278 - (NSUInteger) count { CYObjectiveTry {
1279 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1280 size_t size(JSPropertyNameArrayGetCount(names));
1281 JSPropertyNameArrayRelease(names);
1283 } CYObjectiveCatch }
1285 - (id) objectForKey:(id)key { CYObjectiveTry {
1286 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1287 if (JSValueIsUndefined(context, value))
1289 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1290 } CYObjectiveCatch }
1292 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1293 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1294 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1295 JSPropertyNameArrayRelease(names);
1297 } CYObjectiveCatch }
1299 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1300 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1301 } CYObjectiveCatch }
1303 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1304 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1305 } CYObjectiveCatch }
1309 @implementation CYJSArray
1311 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1313 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1314 } CYObjectiveCatch }
1316 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1317 if ((self = [super init]) != nil) {
1319 context_ = CYGetJSContext(context);
1320 JSGlobalContextRetain(context_);
1321 JSValueProtect(context_, object_);
1323 } CYObjectiveCatch }
1325 - (void) dealloc { CYObjectiveTry {
1326 JSValueUnprotect(context_, object_);
1327 JSGlobalContextRelease(context_);
1329 } CYObjectiveCatch }
1331 - (NSUInteger) count { CYObjectiveTry {
1332 return CYArrayLength(context, object_);
1333 } CYObjectiveCatch }
1335 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1336 size_t bounds([self count]);
1337 if (index >= bounds)
1338 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1339 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1340 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1341 } CYObjectiveCatch }
1343 - (void) addObject:(id)object { CYObjectiveTry {
1344 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1345 } CYObjectiveCatch }
1347 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1348 size_t bounds([self count] + 1);
1349 if (index >= bounds)
1350 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1351 JSValueRef arguments[3];
1352 arguments[0] = CYCastJSValue(context, index);
1353 arguments[1] = CYCastJSValue(context, 0);
1354 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1355 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1356 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1357 } CYObjectiveCatch }
1359 - (void) removeLastObject { CYObjectiveTry {
1360 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1361 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1362 } CYObjectiveCatch }
1364 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1365 size_t bounds([self count]);
1366 if (index >= bounds)
1367 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1368 JSValueRef arguments[2];
1369 arguments[0] = CYCastJSValue(context, index);
1370 arguments[1] = CYCastJSValue(context, 1);
1371 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1372 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1373 } CYObjectiveCatch }
1375 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1376 size_t bounds([self count]);
1377 if (index >= bounds)
1378 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1379 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1380 } CYObjectiveCatch }
1384 // XXX: inherit from or replace with CYJSObject
1385 @interface CYInternal : NSObject {
1386 JSGlobalContextRef context_;
1387 JSObjectRef object_;
1392 @implementation CYInternal
1394 - (void) dealloc { CYObjectiveTry {
1395 JSValueUnprotect(context_, object_);
1396 JSGlobalContextRelease(context_);
1398 } CYObjectiveCatch }
1400 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1401 if ((self = [super init]) != nil) {
1402 context_ = CYGetJSContext(context);
1403 JSGlobalContextRetain(context_);
1405 } CYObjectiveCatch }
1407 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1408 if (object_ == NULL)
1411 return JSObjectHasProperty(context, object_, name);
1414 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1415 if (object_ == NULL)
1418 return CYGetProperty(context, object_, name);
1421 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1422 @synchronized (self) {
1423 if (object_ == NULL) {
1424 object_ = JSObjectMake(context, NULL, NULL);
1425 JSValueProtect(context, object_);
1429 CYSetProperty(context, object_, name, value);
1432 + (CYInternal *) get:(id)object {
1434 if (&objc_getAssociatedObject == NULL)
1437 @synchronized (object) {
1438 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1446 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1448 if (&objc_getAssociatedObject == NULL)
1451 @synchronized (object) {
1452 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1455 if (&objc_setAssociatedObject == NULL)
1458 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1459 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1469 static JSValueRef CYCastJSValue(JSContextRef context, SEL sel) {
1471 return CYJSNull(context);
1472 return Selector_privateData::Make(context, sel);
1475 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1476 if (JSValueIsObjectOfClass(context, value, Selector_privateData::Class_)) {
1477 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1478 return reinterpret_cast<SEL>(internal->value_);
1481 return sel_registerName(CYPoolCString(pool, context, value));
1485 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1486 return (void *) [[NSAutoreleasePool alloc] init];
1487 } CYSadCatch(NULL) }
1489 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1490 return [(NSAutoreleasePool *) handle release];
1493 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1494 CYCallFunction(pool, context, cif, function, value, values);
1497 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, const sig::Signature *signature) {
1499 if (JSValueIsNull(context, value))
1501 JSObjectRef object(CYCastJSObject(context, value));
1503 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1504 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1506 if (JSValueIsObjectOfClass(context, object, Instance::Class_)) {
1507 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1511 _assert(JSObjectIsFunction(context, object));
1513 _assert(signature != NULL);
1514 _assert(signature->count != 0);
1516 sig::Signature modified;
1517 modified.count = signature->count + 1;
1518 modified.elements = new(pool) sig::Element[modified.count];
1520 modified.elements[0] = signature->elements[0];
1521 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1523 modified.elements[1].name = NULL;
1524 modified.elements[1].type = new(pool) sig::Object();
1525 modified.elements[1].offset = _not(size_t);
1527 return CYMakeBlock(context, object, modified);
1535 void Block::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1536 // XXX: this function might not handle the idea of a null pool
1537 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &signature);
1540 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1541 void Object::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1542 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1545 void Meta::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1546 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1549 void Selector::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1550 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1553 JSValueRef Object::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1554 NSObject *value(*reinterpret_cast<NSObject **>(data));
1556 return CYJSNull(context);
1557 JSObjectRef object(CYMakeInstance(context, value));
1560 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1562 if ((internal->flags_ & Instance::Uninitialized) != 0) {
1563 internal->flags_ = static_cast<Instance::Flags>(internal->flags_ & ~Instance::Uninitialized);
1564 _assert(internal->value_ == nil);
1565 internal->value_ = value;
1574 JSValueRef Meta::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1575 if (Class value = *reinterpret_cast<Class *>(data))
1576 return CYMakeInstance(context, value, Instance::Permanent);
1577 return CYJSNull(context);
1580 JSValueRef Selector::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1581 return CYCastJSValue(context, *reinterpret_cast<SEL *>(data));
1584 JSValueRef Block::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1585 return CYCastJSValue(context, *reinterpret_cast<NSObject **>(data));
1590 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1591 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1595 method_getReturnType(method, type, sizeof(type));
1600 // XXX: possibly use a more "awesome" check?
1604 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1605 JSObjectRef _this(CYCastJSObject(context, values[0]));
1606 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1609 JSObjectRef Message_privateData::Make(JSContextRef context, SEL sel, const char *type, IMP value) {
1610 Message_privateData *internal(new Message_privateData(sel, type, value));
1611 return JSObjectMake(context, Message_privateData::Class_, 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, &MessageAdapter_));
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 Message_privateData::Make(context, sel, method_getTypeEncoding(method), method_getImplementation(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_privateData::Class_)) {
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());
1667 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1668 type = method_getTypeEncoding(method);
1669 imp = CYMakeMessage(context, value, type);
1670 } else _assert(false);
1672 objc_method *method(NULL);
1674 objc_method **methods(class_copyMethodList(_class, &size));
1675 for (size_t i(0); i != size; ++i)
1676 if (sel_isEqual(method_getName(methods[i]), sel)) {
1677 method = methods[i];
1683 method_setImplementation(method, imp);
1685 class_addMethod(_class, sel, imp, type);
1690 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1691 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1692 Class _class(internal->GetValue());
1695 objc_method **data(class_copyMethodList(_class, &size));
1696 for (size_t i(0); i != size; ++i)
1697 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1701 static bool CYHasImplicitProperties(Class _class) {
1702 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1703 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1705 return [_class cy$hasImplicitProperties];
1708 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1709 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1710 id self(internal->GetValue());
1712 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1716 NSString *name(CYCastNSString(&pool, context, property));
1718 if (CYInternal *internal = [CYInternal get:self])
1719 if ([internal hasProperty:property inContext:context])
1722 Class _class(object_getClass(self));
1725 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1726 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1727 if ([self cy$hasProperty:name])
1729 } CYPoolCatch(false)
1731 const char *string(CYPoolCString(pool, context, name));
1733 if (class_getProperty(_class, string) != NULL)
1736 if (CYHasImplicitProperties(_class))
1737 if (SEL sel = sel_getUid(string))
1738 if (CYImplements(self, _class, sel, true))
1744 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1745 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1746 id self(internal->GetValue());
1748 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1749 return Internal::Make(context, self, context, object);
1752 NSString *name(CYCastNSString(&pool, context, property));
1754 if (CYInternal *internal = [CYInternal get:self])
1755 if (JSValueRef value = [internal getProperty:property inContext:context])
1759 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1763 const char *string(CYPoolCString(pool, context, name));
1764 Class _class(object_getClass(self));
1766 if (objc_property_t property = class_getProperty(_class, string)) {
1767 PropertyAttributes attributes(property);
1768 SEL sel(sel_registerName(attributes.Getter()));
1769 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1772 if (CYHasImplicitProperties(_class))
1773 if (SEL sel = sel_getUid(string))
1774 if (CYImplements(self, _class, sel, true))
1775 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1780 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1781 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1782 id self(internal->GetValue());
1786 NSString *name(CYCastNSString(&pool, context, property));
1787 NSObject *data(CYCastNSObject(&pool, context, value));
1790 if ([self cy$setProperty:name to:data])
1792 } CYPoolCatch(false)
1794 const char *string(CYPoolCString(pool, context, name));
1795 Class _class(object_getClass(self));
1797 if (objc_property_t property = class_getProperty(_class, string)) {
1798 PropertyAttributes attributes(property);
1799 if (const char *setter = attributes.Setter()) {
1800 SEL sel(sel_registerName(setter));
1801 JSValueRef arguments[1] = {value};
1802 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1807 size_t length(strlen(string));
1809 char set[length + 5];
1815 if (string[0] != '\0') {
1816 set[3] = toupper(string[0]);
1817 memcpy(set + 4, string + 1, length - 1);
1820 set[length + 3] = ':';
1821 set[length + 4] = '\0';
1823 if (SEL sel = sel_getUid(set))
1824 if (CYImplements(self, _class, sel)) {
1825 JSValueRef arguments[1] = {value};
1826 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1830 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1831 [internal setProperty:property toValue:value inContext:context];
1838 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1839 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1840 id self(internal->GetValue());
1843 NSString *name(CYCastNSString(NULL, context, property));
1844 return [self cy$deleteProperty:name];
1845 } CYPoolCatch(false)
1846 } CYCatch(false) return /*XXX*/ false; }
1848 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1849 const char *name(sel_getName(method_getName(method)));
1850 if (strchr(name, ':') != NULL)
1853 const char *type(method_getTypeEncoding(method));
1854 if (type == NULL || *type == '\0' || *type == 'v')
1857 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1860 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1861 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1862 id self(internal->GetValue());
1865 Class _class(object_getClass(self));
1869 objc_property_t *data(class_copyPropertyList(_class, &size));
1870 for (size_t i(0); i != size; ++i)
1871 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1875 if (CYHasImplicitProperties(_class))
1876 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1878 objc_method **data(class_copyMethodList(current, &size));
1879 for (size_t i(0); i != size; ++i)
1880 Instance_getPropertyNames_message(names, data[i]);
1885 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1886 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1887 [self cy$getPropertyNames:names inContext:context];
1891 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1892 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1893 JSObjectRef value(CYMakeInstance(context, [internal->GetValue() alloc], Instance::Uninitialized));
1897 static const char *CYBlockEncoding(NSBlock *self) {
1898 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1899 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1901 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1902 descriptor += sizeof(BlockDescriptor1);
1903 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1904 descriptor += sizeof(BlockDescriptor2);
1905 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1906 return descriptor3->signature;
1909 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature) {
1910 const char *encoding(CYBlockEncoding(self));
1911 if (encoding == NULL)
1914 sig::Parse(pool, &signature, encoding, &Structor_);
1915 _assert(signature.count >= 2);
1917 _assert(dynamic_cast<sig::Object *>(signature.elements[1].type) != NULL);
1918 signature.elements[1] = signature.elements[0];
1920 ++signature.elements;
1926 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1927 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1928 id self(internal->GetValue());
1930 if (const char *encoding = CYBlockEncoding(self)) {
1936 sig::Signature signature;
1937 sig::Parse(pool, &signature, encoding, &Structor_);
1940 sig::sig_ffi_cif(pool, 0, signature, &cif);
1942 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1943 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1944 return CYCallFunction(pool, context, 1, setup, count, arguments, false, false, signature, &cif, function);
1948 CYThrow("NSBlock without signature field passed arguments");
1952 } CYPoolCatch(NULL);
1957 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1958 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1959 Class _class(internal->GetValue());
1960 if (!CYIsClass(_class))
1963 if (CYJSValueIsNSObject(context, instance)) {
1964 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1965 // XXX: this isn't always safe
1966 return [linternal->GetValue() isKindOfClass:_class];
1972 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1974 throw CYJSError(context, "incorrect number of arguments to Instance");
1976 id value(CYCastNSObject(&pool, context, arguments[0]));
1978 value = [NSNull null];
1979 return CYCastJSValue(context, [value cy$box]);
1982 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1983 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1986 id self(internal->GetValue());
1987 const char *name(CYPoolCString(pool, context, property));
1989 if (object_getInstanceVariable(self, name, NULL) != NULL)
1995 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
1996 length = CYCastDouble(encoding + 1);
2000 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2001 for (size_t i(0); i != size; ++i)
2002 if (ivars[i] == ivar)
2004 else if (ivar_getOffset(ivars[i]) == offset) {
2005 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2006 _assert(encoding != NULL);
2007 _assert(encoding[0] == 'b');
2008 shift += CYCastDouble(encoding + 1);
2013 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2014 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2017 id self(internal->GetValue());
2018 const char *name(CYPoolCString(pool, context, property));
2020 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2021 ptrdiff_t offset(ivar_getOffset(ivar));
2022 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2024 const char *encoding(ivar_getTypeEncoding(ivar));
2025 _assert(encoding != NULL);
2026 _assert(encoding[0] != '\0');
2027 if (encoding[0] == 'b') {
2028 unsigned length, shift;
2029 CYBitField(length, shift, self, ivar, encoding, offset);
2030 _assert(shift + length <= sizeof(uintptr_t) * 8);
2031 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2032 uintptr_t mask((1 << length) - 1);
2033 return CYCastJSValue(context, (field >> shift) & mask);
2035 #if defined(__APPLE__) && defined(__LP64__)
2036 // XXX: maybe do even more verifications here
2037 if (strcmp(name, "isa") == 0)
2038 return CYCastJSValue(context, object_getClass(self));
2041 auto type(new(pool) Type_privateData(encoding));
2042 return type->type_->FromFFI(context, type->GetFFI(), data);
2049 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2050 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2053 id self(internal->GetValue());
2054 const char *name(CYPoolCString(pool, context, property));
2056 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2057 ptrdiff_t offset(ivar_getOffset(ivar));
2058 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2060 const char *encoding(ivar_getTypeEncoding(ivar));
2061 _assert(encoding != NULL);
2062 if (encoding[0] == 'b') {
2063 unsigned length, shift;
2064 CYBitField(length, shift, self, ivar, encoding, offset);
2065 _assert(shift + length <= sizeof(uintptr_t) * 8);
2066 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2067 uintptr_t mask((1 << length) - 1);
2068 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2070 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2071 type->type_->PoolFFI(&pool, context, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2079 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2080 if (Class super = class_getSuperclass(_class))
2081 Internal_getPropertyNames_(super, names);
2084 objc_ivar **data(class_copyIvarList(_class, &size));
2085 for (size_t i(0); i != size; ++i)
2086 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2090 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2091 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2094 id self(internal->GetValue());
2095 Class _class(object_getClass(self));
2097 Internal_getPropertyNames_(_class, names);
2100 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2101 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2102 return internal->owner_;
2105 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2107 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2110 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2112 NSString *name(CYCastNSString(&pool, context, property));
2113 if (Class _class = NSClassFromString(name))
2114 return CYMakeInstance(context, _class, Instance::Permanent);
2118 static Class *CYCopyClassList(size_t &size) {
2119 size = objc_getClassList(NULL, 0);
2120 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2123 size_t writ(objc_getClassList(data, size));
2129 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2140 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2142 if (Class *data = CYCopyClassList(size)) {
2143 for (size_t i(0); i != size; ++i)
2144 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2150 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2151 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2154 const char *name(CYPoolCString(pool, context, property));
2156 const char **data(objc_copyClassNamesForImage(internal, &size));
2158 for (size_t i(0); i != size; ++i)
2159 if (strcmp(name, data[i]) == 0) {
2160 if (Class _class = objc_getClass(name)) {
2161 value = CYMakeInstance(context, _class, Instance::Permanent);
2172 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2173 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2175 const char **data(objc_copyClassNamesForImage(internal, &size));
2176 for (size_t i(0); i != size; ++i)
2177 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2181 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2183 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2186 const char **data(objc_copyImageNames(&size));
2187 pool.atexit(free, data);
2189 for (size_t i(0); i != size; ++i)
2190 if (name == data[i]) {
2191 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2192 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2199 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2201 const char **data(objc_copyImageNames(&size));
2202 for (size_t i(0); i != size; ++i)
2203 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2208 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2210 const char *name(CYPoolCString(pool, context, property));
2211 if (Protocol *protocol = objc_getProtocol(name))
2212 return CYMakeInstance(context, protocol, Instance::Permanent);
2216 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2218 Protocol **data(objc_copyProtocolList(&size));
2219 for (size_t i(0); i != size; ++i)
2220 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2224 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2226 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2228 return CYJSNull(context);
2232 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2233 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2237 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2238 *data = reinterpret_cast<void *>(address);
2239 return KERN_SUCCESS;
2243 std::set<Class> query_;
2244 JSContextRef context_;
2245 JSObjectRef results_;
2248 struct CYObjectStruct {
2252 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2253 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2254 JSContextRef context(choice->context_);
2256 for (unsigned i(0); i != count; ++i) {
2257 vm_range_t &range(ranges[i]);
2258 void *data(reinterpret_cast<void *>(range.address));
2259 size_t size(range.size);
2261 if (size < sizeof(CYObjectStruct))
2264 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2265 #if defined(__APPLE__) && defined(__LP64__)
2266 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2268 Class isa(reinterpret_cast<Class>(pointers[0]));
2271 std::set<Class>::const_iterator result(choice->query_.find(isa));
2272 if (result == choice->query_.end())
2275 size_t needed(class_getInstanceSize(*result));
2276 // XXX: if (size < needed)
2278 size_t boundary(496);
2282 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2284 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2288 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2290 throw CYJSError(context, "choose() takes a class argument");
2292 CYGarbageCollect(context);
2295 id _class(CYCastNSObject(&pool, context, arguments[0]));
2297 vm_address_t *zones(NULL);
2299 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2300 _assert(error == KERN_SUCCESS);
2302 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2303 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2306 choice.context_ = context;
2307 choice.results_ = results;
2310 Class *classes(CYCopyClassList(number));
2311 _assert(classes != NULL);
2313 for (size_t i(0); i != number; ++i)
2314 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2315 if (current == _class) {
2316 choice.query_.insert(classes[i]);
2322 for (unsigned i(0); i != size; ++i) {
2323 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2324 if (zone == NULL || zone->introspect == NULL)
2327 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2335 #if defined(__i386__) || defined(__x86_64__)
2336 #define OBJC_MAX_STRUCT_BY_VALUE 8
2337 static int struct_forward_array[] = {
2338 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2339 #elif defined(__arm__)
2340 #define OBJC_MAX_STRUCT_BY_VALUE 1
2341 static int struct_forward_array[] = {
2343 #elif defined(__arm64__)
2346 #error missing objc-runtime-info
2350 static bool stret(ffi_type *ffi_type) {
2351 return ffi_type->type == FFI_TYPE_STRUCT && (
2352 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2353 struct_forward_array[ffi_type->size] != 0
2361 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2365 _class = object_getClass(self);
2369 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2370 imp = method_getImplementation(method);
2371 type = method_getTypeEncoding(method);
2376 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2377 type = CYPoolCString(pool, context, [method _typeString]);
2383 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2390 sig::Signature signature;
2391 sig::Parse(pool, &signature, type, &Structor_);
2394 sig::sig_ffi_cif(pool, 0, signature, &cif);
2398 if (stret(cif.rtype))
2399 imp = class_getMethodImplementation_stret(_class, _cmd);
2402 imp = class_getMethodImplementation(_class, _cmd);
2405 void (*function)() = reinterpret_cast<void (*)()>(imp);
2406 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, true, signature, &cif, function);
2409 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2411 throw CYJSError(context, "too few arguments to objc_msgSend");
2421 if (JSValueIsObjectOfClass(context, arguments[0], cy::Super::Class_)) {
2422 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2423 self = internal->GetValue();
2424 _class = internal->class_;;
2425 uninitialized = false;
2426 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2427 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2428 self = internal->GetValue();
2430 uninitialized = internal->IsUninitialized();
2432 internal->value_ = nil;
2434 self = CYCastNSObject(&pool, context, arguments[0]);
2436 uninitialized = false;
2440 return CYJSNull(context);
2442 _cmd = CYCastSEL(context, arguments[1]);
2444 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2447 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2448 return $objc_msgSend(context, object, _this, count, arguments);
2451 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2452 JSValueRef setup[count + 2];
2455 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2456 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2459 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2461 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2463 // XXX: handle Instance::Uninitialized?
2464 id self(CYCastNSObject(&pool, context, _this));
2468 setup[1] = &internal->sel_;
2470 return CYCallFunction(pool, context, 2, setup, count, arguments, false, true, internal->signature_, &internal->cif_, internal->GetValue());
2473 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2475 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2477 id self(CYCastNSObject(&pool, context, arguments[0]));
2478 Class _class(CYCastClass(pool, context, arguments[1]));
2479 return cy::Super::Make(context, self, _class);
2482 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2484 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2486 const char *name(CYPoolCString(pool, context, arguments[0]));
2487 return Selector_privateData::Make(context, sel_registerName(name));
2490 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2492 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2493 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2496 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2497 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2498 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2501 static JSValueRef Selector_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2502 return CYMakeType(context, sig::Selector());
2505 static JSValueRef Instance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2506 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2507 id self(internal->GetValue());
2508 if (CYIsClass(self))
2509 return CYMakeType(context, sig::Meta());
2510 return CYMakeType(context, sig::Object(class_getName(object_getClass(self))));
2513 static JSValueRef FunctionInstance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2514 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2517 if (!CYBlockSignature(pool, internal->GetValue(), type.signature))
2518 return CYJSNull(context);
2519 return CYMakeType(context, type);
2522 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2523 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2524 return CYMakeInstance(context, object_getClass(internal->GetValue()), Instance::Permanent);
2527 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2528 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2529 id self(internal->GetValue());
2530 if (!CYIsClass(self))
2531 return CYJSUndefined(context);
2532 return CYGetClassPrototype(context, self);
2535 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2536 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2537 id self(internal->GetValue());
2538 if (!CYIsClass(self))
2539 return CYJSUndefined(context);
2540 return Messages::Make(context, (Class) self);
2543 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2544 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2546 if (!CYJSValueIsNSObject(context, _this))
2549 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2550 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2553 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2554 if (!CYJSValueIsNSObject(context, _this))
2557 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2558 id value(internal->GetValue());
2565 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2567 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2568 return CYJSUndefined(context);
2569 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2572 return CYCastJSValue(context, CYJSString(context, [value description]));
2574 } CYCatch(NULL) return /*XXX*/ NULL; }
2576 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2577 if (!CYJSValueIsNSObject(context, _this))
2580 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2581 id value(internal->GetValue());
2582 _assert(value != nil);
2584 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2587 if (JSValueRef result = [value cy$valueOfInContext:context])
2591 } CYCatch(NULL) return /*XXX*/ NULL; }
2593 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2594 if (!CYJSValueIsNSObject(context, _this))
2597 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2598 // XXX: but... but... THIS ISN'T A POINTER! :(
2599 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2600 } CYCatch(NULL) return /*XXX*/ NULL; }
2602 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2603 if (!CYJSValueIsNSObject(context, _this))
2606 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2607 id value(internal->GetValue());
2610 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2611 return CYCastJSValue(context, CYJSString(context, [value description]));
2613 } CYCatch(NULL) return /*XXX*/ NULL; }
2615 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2616 if (!CYJSValueIsNSObject(context, _this))
2619 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2620 id value(internal->GetValue());
2622 if (!CYIsClass(value))
2623 CYThrow("non-Class object cannot be used as Type");
2625 sig::Object type(class_getName(value));
2626 return CYMakeType(context, type);
2627 } CYCatch(NULL) return /*XXX*/ NULL; }
2629 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2630 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2631 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2634 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2635 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2638 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2639 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2640 const char *name(sel_getName(internal->GetValue()));
2643 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2644 return CYCastJSValue(context, CYJSString(context, string));
2646 } CYCatch(NULL) return /*XXX*/ NULL; }
2648 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2650 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2653 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2654 SEL sel(internal->GetValue());
2656 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2657 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2658 const char *encoding(method_getTypeEncoding(method));
2660 sig::Function type(false);
2661 sig::Parse(pool, &type.signature, encoding, &Structor_);
2662 return CYMakeType(context, type);
2665 static JSStaticValue Selector_staticValues[3] = {
2666 {"$cyt", &Selector_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2667 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2668 {NULL, NULL, NULL, 0}
2671 static JSStaticValue Instance_staticValues[6] = {
2672 {"$cyt", &Instance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2673 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2674 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2675 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2676 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2677 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2678 {NULL, NULL, NULL, 0}
2681 static JSStaticValue FunctionInstance_staticValues[6] = {
2682 {"$cyt", &FunctionInstance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2683 // XXX: this is sadly a duplicate of Instance_staticValues
2684 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2685 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2686 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2687 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2688 {NULL, NULL, NULL, 0}
2691 static JSStaticFunction Instance_staticFunctions[6] = {
2692 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2693 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2694 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2695 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2696 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2700 static JSStaticFunction Class_staticFunctions[2] = {
2701 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2705 static JSStaticFunction Internal_staticFunctions[2] = {
2706 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2710 static JSStaticFunction Selector_staticFunctions[5] = {
2711 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2712 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2713 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2714 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2719 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2720 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2721 } CYObjectiveCatch }
2724 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2725 NSArray_ = objc_getClass("NSArray");
2726 NSBlock_ = objc_getClass("NSBlock");
2727 NSDictionary_ = objc_getClass("NSDictionary");
2728 NSNumber_ = objc_getClass("NSNumber");
2729 NSString_ = objc_getClass("NSString");
2730 Object_ = objc_getClass("Object");
2733 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2735 // XXX: apparently, iOS now has both of these
2736 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2737 if (NSCFBoolean_ == nil)
2738 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2740 NSCFType_ = objc_getClass("NSCFType");
2742 NSZombie_ = objc_getClass("_NSZombie_");
2744 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2745 NSZombie_ = objc_getClass("NSZombie");
2748 JSClassDefinition definition;
2750 definition = kJSClassDefinitionEmpty;
2751 definition.className = "Instance";
2752 definition.staticValues = Instance_staticValues;
2753 definition.staticFunctions = Instance_staticFunctions;
2754 definition.hasProperty = &Instance_hasProperty;
2755 definition.getProperty = &Instance_getProperty;
2756 definition.setProperty = &Instance_setProperty;
2757 definition.deleteProperty = &Instance_deleteProperty;
2758 definition.getPropertyNames = &Instance_getPropertyNames;
2759 definition.callAsConstructor = &Instance_callAsConstructor;
2760 definition.hasInstance = &Instance_hasInstance;
2761 definition.finalize = &CYFinalize;
2762 Instance::Class_ = JSClassCreate(&definition);
2764 definition.className = "ArrayInstance";
2765 ArrayInstance_ = JSClassCreate(&definition);
2767 definition.className = "BooleanInstance";
2768 BooleanInstance_ = JSClassCreate(&definition);
2770 definition.className = "NumberInstance";
2771 NumberInstance_ = JSClassCreate(&definition);
2773 definition.className = "ObjectInstance";
2774 ObjectInstance_ = JSClassCreate(&definition);
2776 definition.className = "StringInstance";
2777 StringInstance_ = JSClassCreate(&definition);
2779 definition.className = "FunctionInstance";
2780 definition.staticValues = FunctionInstance_staticValues;
2781 definition.callAsFunction = &FunctionInstance_callAsFunction;
2782 FunctionInstance_ = JSClassCreate(&definition);
2784 definition = kJSClassDefinitionEmpty;
2785 definition.className = "Class";
2786 definition.staticFunctions = Class_staticFunctions;
2787 ClassInstance_ = JSClassCreate(&definition);
2789 definition = kJSClassDefinitionEmpty;
2790 definition.className = "Internal";
2791 definition.staticFunctions = Internal_staticFunctions;
2792 definition.hasProperty = &Internal_hasProperty;
2793 definition.getProperty = &Internal_getProperty;
2794 definition.setProperty = &Internal_setProperty;
2795 definition.getPropertyNames = &Internal_getPropertyNames;
2796 definition.finalize = &CYFinalize;
2797 Internal::Class_ = JSClassCreate(&definition);
2799 definition = kJSClassDefinitionEmpty;
2800 definition.className = "Message";
2801 definition.staticFunctions = cy::Functor::StaticFunctions;
2802 definition.staticValues = cy::Functor::StaticValues;
2803 definition.callAsFunction = &Message_callAsFunction;
2804 definition.finalize = &CYFinalize;
2805 Message_privateData::Class_ = JSClassCreate(&definition);
2807 definition = kJSClassDefinitionEmpty;
2808 definition.className = "Messages";
2809 definition.hasProperty = &Messages_hasProperty;
2810 definition.getProperty = &Messages_getProperty;
2811 definition.setProperty = &Messages_setProperty;
2812 definition.getPropertyNames = &Messages_getPropertyNames;
2813 definition.finalize = &CYFinalize;
2814 Messages::Class_ = JSClassCreate(&definition);
2816 definition = kJSClassDefinitionEmpty;
2817 definition.className = "Selector";
2818 definition.staticValues = Selector_staticValues;
2819 definition.staticFunctions = Selector_staticFunctions;
2820 definition.callAsFunction = &Selector_callAsFunction;
2821 definition.finalize = &CYFinalize;
2822 Selector_privateData::Class_ = JSClassCreate(&definition);
2824 definition = kJSClassDefinitionEmpty;
2825 definition.className = "Super";
2826 definition.finalize = &CYFinalize;
2827 cy::Super::Class_ = JSClassCreate(&definition);
2829 definition = kJSClassDefinitionEmpty;
2830 definition.className = "ObjectiveC::Classes";
2831 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2832 definition.getProperty = &ObjectiveC_Classes_getProperty;
2833 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2834 ObjectiveC_Classes_ = JSClassCreate(&definition);
2836 definition = kJSClassDefinitionEmpty;
2837 definition.className = "ObjectiveC::Constants";
2838 definition.getProperty = &ObjectiveC_Constants_getProperty;
2839 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2840 ObjectiveC_Constants_ = JSClassCreate(&definition);
2843 definition = kJSClassDefinitionEmpty;
2844 definition.className = "ObjectiveC::Images";
2845 definition.getProperty = &ObjectiveC_Images_getProperty;
2846 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2847 ObjectiveC_Images_ = JSClassCreate(&definition);
2849 definition = kJSClassDefinitionEmpty;
2850 definition.className = "ObjectiveC::Image::Classes";
2851 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2852 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2853 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2856 definition = kJSClassDefinitionEmpty;
2857 definition.className = "ObjectiveC::Protocols";
2858 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2859 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2860 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2863 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2864 // XXX: this is horrible; there has to be a better way to do this
2866 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2868 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2874 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2875 JSObjectRef global(CYGetGlobalObject(context));
2876 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2877 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2878 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2879 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2881 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2882 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2884 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2885 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2886 CYArrayPush(context, alls, protocols);
2888 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2889 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2890 CYArrayPush(context, alls, classes);
2892 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2893 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2894 CYArrayPush(context, alls, constants);
2897 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2900 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance::Class_, &Instance_new));
2901 JSObjectRef Message(JSObjectMakeConstructor(context, Message_privateData::Class_, NULL));
2902 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_privateData::Class_, &Selector_new));
2903 JSObjectRef Super(JSObjectMakeConstructor(context, cy::Super::Class_, &Super_new));
2905 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2906 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2908 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2909 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2910 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2911 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2912 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2914 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2915 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2916 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2917 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2918 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2920 JSObjectRef ClassInstance(JSObjectMakeConstructor(context, ClassInstance_, NULL));
2921 JSObjectRef ClassInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ClassInstance, prototype_s)));
2922 CYSetProperty(context, cy, CYJSString("ClassInstance_prototype"), ClassInstance_prototype);
2923 // XXX: this doesn't fit the pattern of the other ones; maybe it sort of should?
2924 CYSetPrototype(context, ClassInstance_prototype, Instance_prototype);
2926 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2927 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2928 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2929 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2930 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2932 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2933 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2934 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2935 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2936 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2938 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2939 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2940 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2941 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2942 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2944 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2945 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2946 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2947 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2948 CYSetPrototype(context, StringInstance_prototype, String_prototype);
2950 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2951 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2952 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
2954 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2955 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
2958 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2961 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2963 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2964 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2966 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
2967 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
2968 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
2969 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::Object()), kJSPropertyAttributeDontEnum);
2970 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::Meta()), kJSPropertyAttributeDontEnum);
2971 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::Selector()), kJSPropertyAttributeDontEnum);
2974 static void *CYObjectiveC_CastSymbol(const char *name) {
2976 #ifdef __GNU_LIBOBJC__
2977 else if (strcmp(name, "object_getClass") == 0)
2978 return reinterpret_cast<void *>(&object_getClass);
2983 static CYHook CYObjectiveCHook = {
2984 &CYObjectiveC_ExecuteStart,
2985 &CYObjectiveC_ExecuteEnd,
2986 &CYObjectiveC_CallFunction,
2987 &CYObjectiveC_Initialize,
2988 &CYObjectiveC_SetupContext,
2989 &CYObjectiveC_CastSymbol,
2992 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
2994 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
2995 CYSetupContext(context);
2996 } CYObjectiveCatch }
2998 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3001 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3002 utf8 = CYPoolCode(pool, utf8);
3004 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3005 size_t bytes(utf16.size * sizeof(uint16_t));
3006 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3007 memcpy(copy, utf16.data, bytes);
3011 } catch (const CYException &exception) {
3013 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];