1 /* Cycript - The Truly Universal Scripting Language
2 * Copyright (C) 2009-2016 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 JSValueRef prototype;
302 if (self == NSCFBoolean_)
304 if (self == NSBoolNumber_)
306 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
307 else if (self == NSArray_)
308 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
309 else if (self == NSBlock_)
310 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
311 else if (self == NSNumber_)
312 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
313 else if (self == NSDictionary_)
314 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
315 else if (self == NSString_)
316 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
318 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
320 JSObjectRef object(JSObjectMake(context, NULL, NULL));
321 CYSetPrototype(context, object, prototype);
322 CYSetProperty(context, cy, name, object);
327 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
328 return CYGetClassPrototype(context, self, class_isMetaClass(self));
331 JSValueRef Messages::GetPrototype(JSContextRef context) const {
332 if (Class super = class_getSuperclass(value_))
333 return Messages::Make(context, super);
337 bool CYIsKindOfClass(id object, Class _class) {
338 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
344 JSValueRef Instance::GetPrototype(JSContextRef context) const {
345 return CYGetClassPrototype(context, object_getClass(value_));
348 JSClassRef Instance::GetClass(id object, Flags flags) {
349 return CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance::Class_;
352 Instance::Instance(id value, Flags flags) :
357 /*else if ([value retainCount] == NSUInteger(-1))
358 flags_ |= Instance::Permanent;*/
360 value_ = [value_ retain];
363 Instance::~Instance() {
368 struct Message_privateData :
371 static JSClassRef Class_;
375 Message_privateData(SEL sel, const char *type, IMP value) :
376 cy::Functor(reinterpret_cast<void (*)()>(value), type),
381 static JSObjectRef Make(JSContextRef context, SEL sel, const char *type, IMP value);
384 JSClassRef Message_privateData::Class_;
386 JSObjectRef CYMakeInstance(JSContextRef context, id object, Instance::Flags flags = Instance::None) {
387 _assert(object != nil);
390 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
392 if (weak != NULL && &JSWeakObjectMapGet != NULL)
393 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
397 JSObjectRef instance(Instance::Make(context, object, flags));
400 if (weak != NULL && &JSWeakObjectMapSet != NULL)
401 JSWeakObjectMapSet(context, weak, object, instance);
407 @interface NSMethodSignature (Cycript)
408 - (NSString *) _typeString;
411 @interface NSObject (Cycript)
413 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
414 - (JSType) cy$JSType;
416 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
417 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
419 - (bool) cy$hasProperty:(NSString *)name;
420 - (NSObject *) cy$getProperty:(NSString *)name;
421 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
422 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
423 - (bool) cy$deleteProperty:(NSString *)name;
424 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
426 + (bool) cy$hasImplicitProperties;
432 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
435 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
436 _assert(value != nil);
438 Class _class(object_getClass(value));
440 if (class_isMetaClass(_class)) {
441 const char *name(class_getName(value));
442 if (class_isMetaClass(value))
443 return [NSString stringWithFormat:@"object_getClass(%s)", name];
445 return [NSString stringWithUTF8String:name];
448 if (_class == NSZombie_)
449 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
451 SEL sel(@selector(cy$toCYON:inSet:));
453 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
454 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
455 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
456 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
457 return [value cy$toCYON:objective inSet:objects];
459 return [NSString stringWithFormat:@"%@", value];
462 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
464 return CYCastNSCYON(value, objective, *objects);
466 std::set<void *> objects;
467 return CYCastNSCYON(value, objective, objects);
471 struct PropertyAttributes {
476 const char *variable;
489 PropertyAttributes(objc_property_t property) :
501 name = property_getName(property);
502 const char *attributes(property_getAttributes(property));
504 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
505 if ((next = strchr(token, ',')) != NULL)
508 case 'R': readonly = true; break;
509 case 'C': copy = true; break;
510 case '&': retain = true; break;
511 case 'N': nonatomic = true; break;
512 case 'G': getter_ = token + 1; break;
513 case 'S': setter_ = token + 1; break;
514 case 'V': variable = token + 1; break;
518 /*if (variable == NULL) {
519 variable = property_getName(property);
520 size_t size(strlen(variable));
521 char *name(new(pool_) char[size + 2]);
523 memcpy(name + 1, variable, size);
524 name[size + 1] = '\0';
529 const char *Getter() {
531 getter_ = pool_.strdup(name);
535 const char *Setter() {
536 if (setter_ == NULL && !readonly) {
537 size_t length(strlen(name));
539 char *temp(new(pool_) char[length + 5]);
545 temp[3] = toupper(name[0]);
546 memcpy(temp + 4, name + 1, length - 1);
549 temp[length + 3] = ':';
550 temp[length + 4] = '\0';
559 @interface CYWebUndefined : NSObject {
562 + (CYWebUndefined *) undefined;
566 @implementation CYWebUndefined
568 + (CYWebUndefined *) undefined {
569 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
575 #define WebUndefined CYWebUndefined
577 /* Bridge: CYJSObject {{{ */
578 @interface CYJSObject : NSMutableDictionary {
580 JSGlobalContextRef context_;
583 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
585 - (NSUInteger) count;
586 - (id) objectForKey:(id)key;
587 - (NSEnumerator *) keyEnumerator;
588 - (void) setObject:(id)object forKey:(id)key;
589 - (void) removeObjectForKey:(id)key;
593 /* Bridge: CYJSArray {{{ */
594 @interface CYJSArray : NSMutableArray {
596 JSGlobalContextRef context_;
599 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
601 - (NSUInteger) count;
602 - (id) objectAtIndex:(NSUInteger)index;
604 - (void) addObject:(id)anObject;
605 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
606 - (void) removeLastObject;
607 - (void) removeObjectAtIndex:(NSUInteger)index;
608 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
613 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
614 return JSValueIsObjectOfClass(context, value, Instance::Class_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
617 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
618 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
622 struct CYBlockDescriptor {
624 BlockDescriptor1 one_;
625 BlockDescriptor2 two_;
626 BlockDescriptor3 three_;
629 Closure_privateData *internal_;
632 void CYDisposeBlock(BlockLiteral *literal) {
633 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
636 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
637 JSObjectRef _this(CYCastJSObject(context, values[0]));
638 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
641 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
642 _assert(__NSMallocBlock__ != Nil);
643 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
645 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
646 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
648 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockAdapter_);
649 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->value_);
651 literal->isa = __NSMallocBlock__;
652 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
653 literal->reserved = 0;
654 literal->descriptor = descriptor;
656 descriptor->d_.one_.size = sizeof(descriptor->d_);
657 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
658 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
660 return reinterpret_cast<NSBlock *>(literal);
664 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
665 if (CYJSValueIsNSObject(context, object)) {
666 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
667 return internal->value_;
670 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
671 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
672 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
675 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
676 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
680 @interface NSBoolNumber : NSNumber {
685 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
689 switch (JSType type = JSValueGetType(context, value)) {
690 case kJSTypeUndefined:
691 object = [WebUndefined undefined];
701 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
704 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
710 object = CYCopyNSNumber(context, value);
715 object = CYCopyNSString(context, value);
720 // XXX: this might could be more efficient
721 object = CYCastNSObject(pool, context, (JSObjectRef) value);
726 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
733 return CYPoolRelease(pool, object);
735 return [object retain];
738 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
739 return CYNSObject(pool, context, value, true);
742 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
743 return CYNSObject(&pool, context, value, false);
746 /* Bridge: NSArray {{{ */
747 @implementation NSArray (Cycript)
750 return [[self mutableCopy] autorelease];
753 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
754 _oassert(objects.insert(self).second);
756 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
757 [json appendString:@"@["];
761 for (id object in self) {
763 for (size_t index(0), count([self count]); index != count; ++index) {
764 id object([self objectAtIndex:index]);
767 [json appendString:@","];
770 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
771 [json appendString:CYCastNSCYON(object, true, objects)];
773 [json appendString:@","];
778 [json appendString:@"]"];
782 - (bool) cy$hasProperty:(NSString *)name {
783 if ([name isEqualToString:@"length"])
786 size_t index(CYGetIndex(name));
787 if (index == _not(size_t) || index >= [self count])
788 return [super cy$hasProperty:name];
793 - (NSObject *) cy$getProperty:(NSString *)name {
794 size_t index(CYGetIndex(name));
795 if (index == _not(size_t) || index >= [self count])
796 return [super cy$getProperty:name];
798 return [self objectAtIndex:index];
801 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
803 if ([name isEqualToString:@"length"])
804 return CYCastJSValue(context, [self count]);
807 return [super cy$getProperty:name inContext:context];
810 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
811 [super cy$getPropertyNames:names inContext:context];
813 for (size_t index(0), count([self count]); index != count; ++index) {
814 id object([self objectAtIndex:index]);
815 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
817 sprintf(name, "%zu", index);
818 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
823 + (bool) cy$hasImplicitProperties {
829 /* Bridge: NSBlock {{{ */
831 @interface NSBlock : NSObject
835 static const char *CYBlockEncoding(NSBlock *self);
836 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature);
838 @implementation NSBlock (Cycript)
840 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
844 if (!CYBlockSignature(pool, self, type.signature))
845 return [super cy$toCYON:objective inSet:objects];
846 _oassert(objects.insert(self).second);
848 CYType *typed((new(pool) CYTypeExpression(CYDecodeType(pool, &type)))->typed_);
849 CYTypeModifier *&modifier(CYGetLast(typed->modifier_));
850 CYTypeBlockWith *with(dynamic_cast<CYTypeBlockWith *>(modifier));
851 _assert(with != NULL);
852 CYObjCBlock *block(new(pool) CYObjCBlock(typed, with->parameters_, NULL));
855 std::ostringstream str;
857 CYOutput out(*str.rdbuf(), options);
858 block->Output(out, CYNoFlags);
860 std::string value(str.str());
861 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
867 /* Bridge: NSBoolNumber {{{ */
869 @implementation NSBoolNumber (Cycript)
871 - (JSType) cy$JSType {
872 return kJSTypeBoolean;
875 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
876 NSString *value([self boolValue] ? @"true" : @"false");
877 return objective ? value : [NSString stringWithFormat:@"@%@", value];
880 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
881 return CYCastJSValue(context, (bool) [self boolValue]);
887 /* Bridge: NSDictionary {{{ */
888 @implementation NSDictionary (Cycript)
891 return [[self mutableCopy] autorelease];
894 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
895 _oassert(objects.insert(self).second);
897 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
898 [json appendString:@"@{"];
902 for (NSObject *key in self) {
904 NSEnumerator *keys([self keyEnumerator]);
905 while (NSObject *key = [keys nextObject]) {
908 [json appendString:@","];
911 [json appendString:CYCastNSCYON(key, true, objects)];
912 [json appendString:@":"];
913 NSObject *object([self objectForKey:key]);
914 [json appendString:CYCastNSCYON(object, true, objects)];
917 [json appendString:@"}"];
921 - (bool) cy$hasProperty:(NSString *)name {
922 return [self objectForKey:name] != nil;
925 - (NSObject *) cy$getProperty:(NSString *)name {
926 return [self objectForKey:name];
929 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
930 [super cy$getPropertyNames:names inContext:context];
933 for (NSObject *key in self) {
935 NSEnumerator *keys([self keyEnumerator]);
936 while (NSObject *key = [keys nextObject]) {
938 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
942 + (bool) cy$hasImplicitProperties {
948 /* Bridge: NSMutableArray {{{ */
949 @implementation NSMutableArray (Cycript)
951 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
952 if ([name isEqualToString:@"length"]) {
953 // XXX: is this not intelligent?
954 NSNumber *number(reinterpret_cast<NSNumber *>(value));
955 NSUInteger size([number unsignedIntegerValue]);
956 NSUInteger count([self count]);
958 [self removeObjectsInRange:NSMakeRange(size, count - size)];
959 else if (size != count) {
960 WebUndefined *undefined([WebUndefined undefined]);
961 for (size_t i(count); i != size; ++i)
962 [self addObject:undefined];
967 size_t index(CYGetIndex(name));
968 if (index == _not(size_t))
969 return [super cy$setProperty:name to:value];
971 id object(value ?: [NSNull null]);
973 size_t count([self count]);
975 [self replaceObjectAtIndex:index withObject:object];
977 if (index != count) {
978 WebUndefined *undefined([WebUndefined undefined]);
979 for (size_t i(count); i != index; ++i)
980 [self addObject:undefined];
983 [self addObject:object];
989 - (bool) cy$deleteProperty:(NSString *)name {
990 size_t index(CYGetIndex(name));
991 if (index == _not(size_t) || index >= [self count])
992 return [super cy$deleteProperty:name];
993 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
999 /* Bridge: NSMutableDictionary {{{ */
1000 @implementation NSMutableDictionary (Cycript)
1002 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1003 [self setObject:(value ?: [NSNull null]) forKey:name];
1007 - (bool) cy$deleteProperty:(NSString *)name {
1008 if ([self objectForKey:name] == nil)
1011 [self removeObjectForKey:name];
1018 /* Bridge: NSNumber {{{ */
1019 @implementation NSNumber (Cycript)
1021 - (JSType) cy$JSType {
1023 // XXX: this just seems stupid
1024 if ([self class] == NSCFBoolean_)
1025 return kJSTypeBoolean;
1027 return kJSTypeNumber;
1030 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1031 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1032 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1035 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1036 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1037 } CYObjectiveCatch }
1041 /* Bridge: NSNull {{{ */
1042 @implementation NSNull (Cycript)
1044 - (JSType) cy$JSType {
1048 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1049 NSString *value(@"null");
1050 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1053 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1054 return CYJSNull(context);
1055 } CYObjectiveCatch }
1059 /* Bridge: NSObject {{{ */
1060 @implementation NSObject (Cycript)
1066 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1067 return [self cy$valueOfInContext:context];
1070 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1072 } CYObjectiveCatch }
1074 - (JSType) cy$JSType {
1075 return kJSTypeObject;
1078 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1079 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1082 - (bool) cy$hasProperty:(NSString *)name {
1086 - (NSObject *) cy$getProperty:(NSString *)name {
1090 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1091 if (NSObject *value = [self cy$getProperty:name])
1092 return CYCastJSValue(context, value);
1094 } CYObjectiveCatch }
1096 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1100 - (bool) cy$deleteProperty:(NSString *)name {
1104 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1107 + (bool) cy$hasImplicitProperties {
1113 /* Bridge: NSOrderedSet {{{ */
1115 @implementation NSOrderedSet (Cycript)
1117 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1118 _oassert(objects.insert(self).second);
1120 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1121 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1122 [json appendString:CYCastNSCYON([self array], true, objects)];
1123 [json appendString:@"]]"];
1130 /* Bridge: NSProxy {{{ */
1131 @implementation NSProxy (Cycript)
1133 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1134 return [[self description] cy$toCYON:objective inSet:objects];
1139 /* Bridge: NSSet {{{ */
1140 @implementation NSSet (Cycript)
1142 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1143 _oassert(objects.insert(self).second);
1145 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1146 [json appendString:@"[NSSet setWithArray:"];
1147 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1148 [json appendString:@"]]"];
1154 /* Bridge: NSString {{{ */
1155 @implementation NSString (Cycript)
1158 return [[self copy] autorelease];
1161 - (JSType) cy$JSType {
1162 return kJSTypeString;
1165 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1166 std::ostringstream str;
1169 CYUTF8String string(CYCastUTF8String(self));
1170 CYStringify(str, string.data, string.size, true);
1171 std::string value(str.str());
1172 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1175 - (bool) cy$hasProperty:(NSString *)name {
1176 size_t index(CYGetIndex(name));
1177 if (index == _not(size_t) || index >= [self length])
1178 return [super cy$hasProperty:name];
1183 - (NSObject *) cy$getProperty:(NSString *)name {
1184 size_t index(CYGetIndex(name));
1185 if (index == _not(size_t) || index >= [self length])
1186 return [super cy$getProperty:name];
1188 return [self substringWithRange:NSMakeRange(index, 1)];
1191 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1192 [super cy$getPropertyNames:names inContext:context];
1194 for (size_t index(0), length([self length]); index != length; ++index) {
1196 sprintf(name, "%zu", index);
1197 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1201 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1202 return CYCastJSValue(context, CYJSString(context, self));
1203 } CYObjectiveCatch }
1207 /* Bridge: WebUndefined {{{ */
1208 @implementation WebUndefined (Cycript)
1210 - (JSType) cy$JSType {
1211 return kJSTypeUndefined;
1214 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1215 NSString *value(@"undefined");
1216 return value; // XXX: maybe use the below code, adding @undefined?
1217 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1220 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1221 return CYJSUndefined(context);
1222 } CYObjectiveCatch }
1227 static bool CYIsClass(id self) {
1228 return class_isMetaClass(object_getClass(self));
1231 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1232 id self(CYCastNSObject(&pool, context, value));
1233 if (CYIsClass(self))
1234 return (Class) self;
1235 throw CYJSError(context, "got something that is not a Class");
1239 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1241 size_t size(JSPropertyNameArrayGetCount(names));
1242 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1243 for (size_t index(0); index != size; ++index)
1244 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1248 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) {
1250 return CYJSNull(context);
1251 return CYMakeInstance(context, value);
1254 @implementation CYJSObject
1256 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1257 if ((self = [super init]) != nil) {
1259 context_ = CYGetJSContext(context);
1260 JSGlobalContextRetain(context_);
1261 JSValueProtect(context_, object_);
1263 } CYObjectiveCatch }
1265 - (void) dealloc { CYObjectiveTry {
1266 JSValueUnprotect(context_, object_);
1267 JSGlobalContextRelease(context_);
1269 } CYObjectiveCatch }
1271 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1273 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1275 return [super cy$toCYON:objective inSet:objects];
1277 return [NSString stringWithUTF8String:cyon];
1278 } CYObjectiveCatch }
1280 - (NSUInteger) count { CYObjectiveTry {
1281 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1282 size_t size(JSPropertyNameArrayGetCount(names));
1283 JSPropertyNameArrayRelease(names);
1285 } CYObjectiveCatch }
1287 - (id) objectForKey:(id)key { CYObjectiveTry {
1288 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1289 if (JSValueIsUndefined(context, value))
1291 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1292 } CYObjectiveCatch }
1294 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1295 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1296 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1297 JSPropertyNameArrayRelease(names);
1299 } CYObjectiveCatch }
1301 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1302 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1303 } CYObjectiveCatch }
1305 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1306 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1307 } CYObjectiveCatch }
1311 @implementation CYJSArray
1313 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1315 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1316 } CYObjectiveCatch }
1318 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1319 if ((self = [super init]) != nil) {
1321 context_ = CYGetJSContext(context);
1322 JSGlobalContextRetain(context_);
1323 JSValueProtect(context_, object_);
1325 } CYObjectiveCatch }
1327 - (void) dealloc { CYObjectiveTry {
1328 JSValueUnprotect(context_, object_);
1329 JSGlobalContextRelease(context_);
1331 } CYObjectiveCatch }
1333 - (NSUInteger) count { CYObjectiveTry {
1334 return CYArrayLength(context, object_);
1335 } CYObjectiveCatch }
1337 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1338 size_t bounds([self count]);
1339 if (index >= bounds)
1340 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1341 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1342 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1343 } CYObjectiveCatch }
1345 - (void) addObject:(id)object { CYObjectiveTry {
1346 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1347 } CYObjectiveCatch }
1349 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1350 size_t bounds([self count] + 1);
1351 if (index >= bounds)
1352 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1353 JSValueRef arguments[3];
1354 arguments[0] = CYCastJSValue(context, index);
1355 arguments[1] = CYCastJSValue(context, 0);
1356 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1357 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1358 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1359 } CYObjectiveCatch }
1361 - (void) removeLastObject { CYObjectiveTry {
1362 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1363 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1364 } CYObjectiveCatch }
1366 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1367 size_t bounds([self count]);
1368 if (index >= bounds)
1369 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1370 JSValueRef arguments[2];
1371 arguments[0] = CYCastJSValue(context, index);
1372 arguments[1] = CYCastJSValue(context, 1);
1373 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1374 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1375 } CYObjectiveCatch }
1377 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1378 size_t bounds([self count]);
1379 if (index >= bounds)
1380 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1381 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1382 } CYObjectiveCatch }
1386 // XXX: inherit from or replace with CYJSObject
1387 @interface CYInternal : NSObject {
1388 JSGlobalContextRef context_;
1389 JSObjectRef object_;
1394 @implementation CYInternal
1396 - (void) dealloc { CYObjectiveTry {
1397 JSValueUnprotect(context_, object_);
1398 JSGlobalContextRelease(context_);
1400 } CYObjectiveCatch }
1402 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1403 if ((self = [super init]) != nil) {
1404 context_ = CYGetJSContext(context);
1405 JSGlobalContextRetain(context_);
1407 } CYObjectiveCatch }
1409 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1410 if (object_ == NULL)
1413 return JSObjectHasProperty(context, object_, name);
1416 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1417 if (object_ == NULL)
1420 return CYGetProperty(context, object_, name);
1423 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1424 @synchronized (self) {
1425 if (object_ == NULL) {
1426 object_ = JSObjectMake(context, NULL, NULL);
1427 JSValueProtect(context, object_);
1431 CYSetProperty(context, object_, name, value);
1434 + (CYInternal *) get:(id)object {
1436 if (&objc_getAssociatedObject == NULL)
1439 @synchronized (object) {
1440 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1448 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1450 if (&objc_getAssociatedObject == NULL)
1453 @synchronized (object) {
1454 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1457 if (&objc_setAssociatedObject == NULL)
1460 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1461 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1471 static JSValueRef CYCastJSValue(JSContextRef context, SEL sel) {
1473 return CYJSNull(context);
1474 return Selector_privateData::Make(context, sel);
1477 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1478 if (JSValueIsObjectOfClass(context, value, Selector_privateData::Class_)) {
1479 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1480 return reinterpret_cast<SEL>(internal->value_);
1483 return sel_registerName(CYPoolCString(pool, context, value));
1487 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1488 return (void *) [[NSAutoreleasePool alloc] init];
1489 } CYSadCatch(NULL) }
1491 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1492 return [(NSAutoreleasePool *) handle release];
1495 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1496 CYCallFunction(pool, context, cif, function, value, values);
1499 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, const sig::Signature *signature) {
1501 if (JSValueIsNull(context, value))
1503 JSObjectRef object(CYCastJSObject(context, value));
1505 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1506 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_;
1508 if (JSValueIsObjectOfClass(context, object, Instance::Class_)) {
1509 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->value_ == nil);
1513 _assert(JSObjectIsFunction(context, object));
1515 _assert(signature != NULL);
1516 _assert(signature->count != 0);
1518 sig::Signature modified;
1519 modified.count = signature->count + 1;
1520 modified.elements = new(pool) sig::Element[modified.count];
1522 modified.elements[0] = signature->elements[0];
1523 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1525 modified.elements[1].name = NULL;
1526 modified.elements[1].type = new(pool) sig::Object();
1527 modified.elements[1].offset = _not(size_t);
1529 return CYMakeBlock(context, object, modified);
1537 void Block::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1538 // XXX: this function might not handle the idea of a null pool
1539 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &signature);
1542 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1543 void Object::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1544 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1547 void Meta::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1548 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1551 void Selector::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1552 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1555 JSValueRef Object::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1556 NSObject *value(*reinterpret_cast<NSObject **>(data));
1558 return CYJSNull(context);
1559 JSObjectRef object(CYMakeInstance(context, value));
1562 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1564 if (internal->IsUninitialized()) {
1565 internal->flags_ &= ~Instance::Uninitialized;
1566 if (internal->value_ == nil)
1567 internal->value_ = value;
1569 _assert(internal->value_ == value);
1578 JSValueRef Meta::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1579 if (Class value = *reinterpret_cast<Class *>(data))
1580 return CYMakeInstance(context, value, Instance::Permanent);
1581 return CYJSNull(context);
1584 JSValueRef Selector::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1585 return CYCastJSValue(context, *reinterpret_cast<SEL *>(data));
1588 JSValueRef Block::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1589 return CYCastJSValue(context, *reinterpret_cast<NSObject **>(data));
1594 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1595 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1599 method_getReturnType(method, type, sizeof(type));
1604 // XXX: possibly use a more "awesome" check?
1608 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1609 JSObjectRef _this(CYCastJSObject(context, values[0]));
1610 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1613 JSObjectRef Message_privateData::Make(JSContextRef context, SEL sel, const char *type, IMP value) {
1614 Message_privateData *internal(new Message_privateData(sel, type, value));
1615 return JSObjectMake(context, Message_privateData::Class_, internal);
1618 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1619 JSObjectRef function(CYCastJSObject(context, value));
1621 sig::Signature signature;
1622 sig::Parse(pool, &signature, encoding, &Structor_);
1623 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1624 // XXX: see notes in Library.cpp about needing to leak
1625 return reinterpret_cast<IMP>(internal->value_);
1628 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1629 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1630 Class _class(internal->value_);
1633 const char *name(CYPoolCString(pool, context, property));
1635 if (SEL sel = sel_getUid(name))
1636 if (class_getInstanceMethod(_class, sel) != NULL)
1642 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1643 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1644 Class _class(internal->value_);
1647 const char *name(CYPoolCString(pool, context, property));
1649 if (SEL sel = sel_getUid(name))
1650 if (objc_method *method = class_getInstanceMethod(_class, sel))
1651 return Message_privateData::Make(context, sel, method_getTypeEncoding(method), method_getImplementation(method));
1656 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1657 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1658 Class _class(internal->value_);
1661 const char *name(CYPoolCString(pool, context, property));
1662 SEL sel(sel_registerName(name));
1667 if (JSValueIsObjectOfClass(context, value, Message_privateData::Class_)) {
1668 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1669 type = sig::Unparse(pool, &message->signature_);
1670 imp = reinterpret_cast<IMP>(message->value_);
1671 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1672 type = method_getTypeEncoding(method);
1673 imp = CYMakeMessage(context, value, type);
1674 } else _assert(false);
1676 objc_method *method(NULL);
1678 objc_method **methods(class_copyMethodList(_class, &size));
1679 for (size_t i(0); i != size; ++i)
1680 if (sel_isEqual(method_getName(methods[i]), sel)) {
1681 method = methods[i];
1687 method_setImplementation(method, imp);
1689 class_addMethod(_class, sel, imp, type);
1694 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1695 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1696 Class _class(internal->value_);
1699 objc_method **data(class_copyMethodList(_class, &size));
1700 for (size_t i(0); i != size; ++i)
1701 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1705 static bool CYHasImplicitProperties(JSContextRef context, Class _class) {
1706 if (!CYCastBool(context, CYGetCachedValue(context, CYJSString("cydget"))))
1708 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1709 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1711 return [_class cy$hasImplicitProperties];
1714 static objc_property_t CYFindProperty(CYPool &pool, Class _class, const char *name) {
1717 if (objc_property_t property = class_getProperty(_class, name))
1721 /* // XXX: I don't think any of this is required
1723 Protocol **protocols(class_copyProtocolList(_class, &count));
1724 // XXX: just implement a scope guard already :/
1725 pool.atexit(free, protocols);
1727 for (unsigned int i(0); i != count; ++i)
1728 if (objc_property_t property = protocol_getProperty(protocols[i], name, true, true))
1731 return CYFindProperty(pool, class_getSuperclass(_class), name); */
1734 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1735 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1736 id self(internal->value_);
1738 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1742 NSString *name(CYCastNSString(&pool, context, property));
1744 if (CYInternal *internal = [CYInternal get:self])
1745 if ([internal hasProperty:property inContext:context])
1748 Class _class(object_getClass(self));
1751 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1752 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1753 if ([self cy$hasProperty:name])
1755 } CYPoolCatch(false)
1757 const char *string(CYPoolCString(pool, context, name));
1759 if (CYFindProperty(pool, _class, string) != NULL)
1762 if (CYHasImplicitProperties(context, _class))
1763 if (SEL sel = sel_getUid(string))
1764 if (CYImplements(self, _class, sel, true))
1770 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1771 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1772 id self(internal->value_);
1774 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1775 return Interior::Make(context, self, context, object);
1778 NSString *name(CYCastNSString(&pool, context, property));
1780 if (CYInternal *internal = [CYInternal get:self])
1781 if (JSValueRef value = [internal getProperty:property inContext:context])
1785 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1789 const char *string(CYPoolCString(pool, context, name));
1790 Class _class(object_getClass(self));
1792 if (objc_property_t property = CYFindProperty(pool, _class, string)) {
1793 PropertyAttributes attributes(property);
1794 SEL sel(sel_registerName(attributes.Getter()));
1795 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1798 if (CYHasImplicitProperties(context, _class))
1799 if (SEL sel = sel_getUid(string))
1800 if (CYImplements(self, _class, sel, true))
1801 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1806 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1807 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1808 id self(internal->value_);
1812 NSString *name(CYCastNSString(&pool, context, property));
1813 NSObject *data(CYCastNSObject(&pool, context, value));
1816 if ([self cy$setProperty:name to:data])
1818 } CYPoolCatch(false)
1820 const char *string(CYPoolCString(pool, context, name));
1821 Class _class(object_getClass(self));
1823 if (objc_property_t property = CYFindProperty(pool, _class, string)) {
1824 PropertyAttributes attributes(property);
1825 if (const char *setter = attributes.Setter()) {
1826 SEL sel(sel_registerName(setter));
1827 JSValueRef arguments[1] = {value};
1828 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1833 size_t length(strlen(string));
1835 char set[length + 5];
1841 if (string[0] != '\0') {
1842 set[3] = toupper(string[0]);
1843 memcpy(set + 4, string + 1, length - 1);
1846 set[length + 3] = ':';
1847 set[length + 4] = '\0';
1849 if (SEL sel = sel_getUid(set))
1850 if (CYImplements(self, _class, sel)) {
1851 JSValueRef arguments[1] = {value};
1852 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1856 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1857 [internal setProperty:property toValue:value inContext:context];
1864 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1865 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1866 id self(internal->value_);
1869 NSString *name(CYCastNSString(NULL, context, property));
1870 return [self cy$deleteProperty:name];
1871 } CYPoolCatch(false)
1872 } CYCatch(false) return /*XXX*/ false; }
1874 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1875 const char *name(sel_getName(method_getName(method)));
1876 if (strchr(name, ':') != NULL)
1879 const char *type(method_getTypeEncoding(method));
1880 if (type == NULL || *type == '\0' || *type == 'v')
1883 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1886 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1887 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1888 id self(internal->value_);
1891 Class _class(object_getClass(self));
1895 objc_property_t *data(class_copyPropertyList(_class, &size));
1896 for (size_t i(0); i != size; ++i)
1897 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1901 if (CYHasImplicitProperties(context, _class))
1902 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1904 objc_method **data(class_copyMethodList(current, &size));
1905 for (size_t i(0); i != size; ++i)
1906 Instance_getPropertyNames_message(names, data[i]);
1911 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1912 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1913 [self cy$getPropertyNames:names inContext:context];
1917 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1918 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1919 JSObjectRef value(CYMakeInstance(context, [internal->value_ alloc], Instance::Uninitialized));
1923 static const char *CYBlockEncoding(NSBlock *self) {
1924 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1925 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1927 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1928 descriptor += sizeof(BlockDescriptor1);
1929 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1930 descriptor += sizeof(BlockDescriptor2);
1931 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1932 return descriptor3->signature;
1935 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature) {
1936 const char *encoding(CYBlockEncoding(self));
1937 if (encoding == NULL)
1940 sig::Parse(pool, &signature, encoding, &Structor_);
1941 _assert(signature.count >= 2);
1943 _assert(dynamic_cast<sig::Object *>(signature.elements[1].type) != NULL);
1944 signature.elements[1] = signature.elements[0];
1946 ++signature.elements;
1952 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1953 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1954 id self(internal->value_);
1956 if (const char *encoding = CYBlockEncoding(self)) {
1962 sig::Signature signature;
1963 sig::Parse(pool, &signature, encoding, &Structor_);
1966 sig::sig_ffi_cif(pool, 0, signature, &cif);
1968 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1969 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1970 return CYCallFunction(pool, context, 1, setup, count, arguments, false, false, signature, &cif, function);
1974 CYThrow("NSBlock without signature field passed arguments");
1978 } CYPoolCatch(NULL);
1983 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1984 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1985 Class _class(internal->value_);
1986 if (!CYIsClass(_class))
1989 if (CYJSValueIsNSObject(context, instance)) {
1990 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1991 // XXX: this isn't always safe
1992 return [linternal->value_ isKindOfClass:_class];
1998 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2000 throw CYJSError(context, "incorrect number of arguments to Instance");
2002 id value(CYCastNSObject(&pool, context, arguments[0]));
2004 value = [NSNull null];
2005 return CYCastJSValue(context, [value cy$box]);
2008 static bool Interior_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2009 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2012 id self(internal->value_);
2013 const char *name(CYPoolCString(pool, context, property));
2015 if (object_getInstanceVariable(self, name, NULL) != NULL)
2021 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2022 length = CYCastDouble(encoding + 1);
2026 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2027 for (size_t i(0); i != size; ++i)
2028 if (ivars[i] == ivar)
2030 else if (ivar_getOffset(ivars[i]) == offset) {
2031 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2032 _assert(encoding != NULL);
2033 _assert(encoding[0] == 'b');
2034 shift += CYCastDouble(encoding + 1);
2039 static JSValueRef Interior_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2040 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2043 id self(internal->value_);
2044 const char *name(CYPoolCString(pool, context, property));
2046 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2047 ptrdiff_t offset(ivar_getOffset(ivar));
2048 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2050 const char *encoding(ivar_getTypeEncoding(ivar));
2051 _assert(encoding != NULL);
2052 _assert(encoding[0] != '\0');
2053 if (encoding[0] == 'b') {
2054 unsigned length, shift;
2055 CYBitField(length, shift, self, ivar, encoding, offset);
2056 _assert(shift + length <= sizeof(uintptr_t) * 8);
2057 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2058 uintptr_t mask((1 << length) - 1);
2059 return CYCastJSValue(context, (field >> shift) & mask);
2061 #if defined(__APPLE__) && defined(__LP64__)
2062 // XXX: maybe do even more verifications here
2063 if (strcmp(name, "isa") == 0)
2064 return CYCastJSValue(context, object_getClass(self));
2067 auto type(new(pool) Type_privateData(encoding));
2068 return type->type_->FromFFI(context, type->GetFFI(), data);
2075 static bool Interior_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2076 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2079 id self(internal->value_);
2080 const char *name(CYPoolCString(pool, context, property));
2082 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2083 ptrdiff_t offset(ivar_getOffset(ivar));
2084 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2086 const char *encoding(ivar_getTypeEncoding(ivar));
2087 _assert(encoding != NULL);
2088 if (encoding[0] == 'b') {
2089 unsigned length, shift;
2090 CYBitField(length, shift, self, ivar, encoding, offset);
2091 _assert(shift + length <= sizeof(uintptr_t) * 8);
2092 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2093 uintptr_t mask((1 << length) - 1);
2094 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2096 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2097 type->type_->PoolFFI(&pool, context, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2105 static void Interior_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2106 if (Class super = class_getSuperclass(_class))
2107 Interior_getPropertyNames_(super, names);
2110 objc_ivar **data(class_copyIvarList(_class, &size));
2111 for (size_t i(0); i != size; ++i)
2112 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2116 static void Interior_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2117 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2120 id self(internal->value_);
2121 Class _class(object_getClass(self));
2123 Interior_getPropertyNames_(_class, names);
2126 static JSValueRef Interior_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2127 Interior *internal(reinterpret_cast<Interior *>(JSObjectGetPrivate(object)));
2128 return internal->owner_;
2131 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2133 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2136 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2138 NSString *name(CYCastNSString(&pool, context, property));
2139 if (Class _class = NSClassFromString(name))
2140 return CYMakeInstance(context, _class, Instance::Permanent);
2144 static Class *CYCopyClassList(size_t &size) {
2145 size = objc_getClassList(NULL, 0);
2146 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2149 size_t writ(objc_getClassList(data, size));
2155 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2166 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2168 if (Class *data = CYCopyClassList(size)) {
2169 for (size_t i(0); i != size; ++i)
2170 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2176 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2177 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2180 const char *name(CYPoolCString(pool, context, property));
2182 const char **data(objc_copyClassNamesForImage(internal, &size));
2184 for (size_t i(0); i != size; ++i)
2185 if (strcmp(name, data[i]) == 0) {
2186 if (Class _class = objc_getClass(name)) {
2187 value = CYMakeInstance(context, _class, Instance::Permanent);
2198 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2199 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2201 const char **data(objc_copyClassNamesForImage(internal, &size));
2202 for (size_t i(0); i != size; ++i)
2203 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2207 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2209 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2212 const char **data(objc_copyImageNames(&size));
2213 pool.atexit(free, data);
2215 for (size_t i(0); i != size; ++i)
2216 if (name == data[i]) {
2217 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2218 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2225 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2227 const char **data(objc_copyImageNames(&size));
2228 for (size_t i(0); i != size; ++i)
2229 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2234 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2236 const char *name(CYPoolCString(pool, context, property));
2237 if (Protocol *protocol = objc_getProtocol(name))
2238 return CYMakeInstance(context, protocol, Instance::Permanent);
2242 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2244 Protocol **data(objc_copyProtocolList(&size));
2245 for (size_t i(0); i != size; ++i)
2246 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2250 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2252 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2254 return CYJSNull(context);
2258 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2259 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2263 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2264 *data = reinterpret_cast<void *>(address);
2265 return KERN_SUCCESS;
2269 std::set<Class> query_;
2270 JSContextRef context_;
2271 JSObjectRef results_;
2274 struct CYObjectStruct {
2278 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2279 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2280 JSContextRef context(choice->context_);
2282 for (unsigned i(0); i != count; ++i) {
2283 vm_range_t &range(ranges[i]);
2284 void *data(reinterpret_cast<void *>(range.address));
2285 size_t size(range.size);
2287 if (size < sizeof(CYObjectStruct))
2290 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2291 #if defined(__APPLE__) && defined(__LP64__)
2292 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2294 Class isa(reinterpret_cast<Class>(pointers[0]));
2297 std::set<Class>::const_iterator result(choice->query_.find(isa));
2298 if (result == choice->query_.end())
2301 size_t needed(class_getInstanceSize(*result));
2302 // XXX: if (size < needed)
2304 size_t boundary(496);
2308 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2310 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2314 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2316 throw CYJSError(context, "choose() takes a class argument");
2318 CYGarbageCollect(context);
2321 id _class(CYCastNSObject(&pool, context, arguments[0]));
2323 vm_address_t *zones(NULL);
2325 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2326 _assert(error == KERN_SUCCESS);
2328 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2329 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2332 choice.context_ = context;
2333 choice.results_ = results;
2336 Class *classes(CYCopyClassList(number));
2337 _assert(classes != NULL);
2339 for (size_t i(0); i != number; ++i)
2340 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2341 if (current == _class) {
2342 choice.query_.insert(classes[i]);
2348 for (unsigned i(0); i != size; ++i) {
2349 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2350 if (zone == NULL || zone->introspect == NULL)
2353 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2361 #if defined(__i386__) || defined(__x86_64__)
2362 #define OBJC_MAX_STRUCT_BY_VALUE 8
2363 static int struct_forward_array[] = {
2364 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2365 #elif defined(__arm__)
2366 #define OBJC_MAX_STRUCT_BY_VALUE 1
2367 static int struct_forward_array[] = {
2369 #elif defined(__arm64__)
2372 #error missing objc-runtime-info
2376 static bool stret(ffi_type *ffi_type) {
2377 return ffi_type->type == FFI_TYPE_STRUCT && (
2378 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2379 struct_forward_array[ffi_type->size] != 0
2387 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2391 _class = object_getClass(self);
2395 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2396 imp = method_getImplementation(method);
2397 type = method_getTypeEncoding(method);
2402 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2403 type = CYPoolCString(pool, context, [method _typeString]);
2409 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2416 sig::Signature signature;
2417 sig::Parse(pool, &signature, type, &Structor_);
2420 sig::sig_ffi_cif(pool, 0, signature, &cif);
2424 if (stret(cif.rtype))
2425 imp = class_getMethodImplementation_stret(_class, _cmd);
2428 imp = class_getMethodImplementation(_class, _cmd);
2431 void (*function)() = reinterpret_cast<void (*)()>(imp);
2432 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, true, signature, &cif, function);
2435 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2437 throw CYJSError(context, "too few arguments to objc_msgSend");
2447 if (JSValueIsObjectOfClass(context, arguments[0], cy::Super::Class_)) {
2448 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2449 self = internal->value_;
2450 _class = internal->class_;;
2451 uninitialized = false;
2452 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2453 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2454 self = internal->value_;
2456 uninitialized = internal->IsUninitialized();
2457 if (uninitialized && [internal->value_ retainCount] != NSUInteger(-1))
2458 internal->value_ = nil;
2460 self = CYCastNSObject(&pool, context, arguments[0]);
2462 uninitialized = false;
2466 return CYJSNull(context);
2468 _cmd = CYCastSEL(context, arguments[1]);
2470 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2473 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2474 return $objc_msgSend(context, object, _this, count, arguments);
2477 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2478 JSValueRef setup[count + 2];
2481 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2482 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2485 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2487 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2489 // XXX: handle Instance::Uninitialized?
2490 id self(CYCastNSObject(&pool, context, _this));
2494 setup[1] = &internal->sel_;
2496 return CYCallFunction(pool, context, 2, setup, count, arguments, false, true, internal->signature_, &internal->cif_, internal->value_);
2499 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2501 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2503 id self(CYCastNSObject(&pool, context, arguments[0]));
2504 Class _class(CYCastClass(pool, context, arguments[1]));
2505 return cy::Super::Make(context, self, _class);
2508 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2510 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2512 const char *name(CYPoolCString(pool, context, arguments[0]));
2513 return Selector_privateData::Make(context, sel_registerName(name));
2516 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2518 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2519 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2522 static JSValueRef Selector_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2523 return CYMakeType(context, sig::Selector());
2526 static JSValueRef Instance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2527 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2528 id self(internal->value_);
2529 if (CYIsClass(self))
2530 return CYMakeType(context, sig::Meta());
2531 return CYMakeType(context, sig::Object(class_getName(object_getClass(self))));
2534 static JSValueRef FunctionInstance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2535 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2538 if (!CYBlockSignature(pool, internal->value_, type.signature))
2539 return CYJSNull(context);
2540 return CYMakeType(context, type);
2543 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2544 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2545 return CYMakeInstance(context, object_getClass(internal->value_), Instance::Permanent);
2548 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2549 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2550 id self(internal->value_);
2551 if (!CYIsClass(self))
2552 return CYJSUndefined(context);
2553 return CYGetClassPrototype(context, self);
2556 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2557 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2558 id self(internal->value_);
2559 if (!CYIsClass(self))
2560 return CYJSUndefined(context);
2561 return Messages::Make(context, (Class) self);
2564 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2565 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2567 if (!CYJSValueIsNSObject(context, _this))
2570 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2571 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->value_, false, objects)));
2574 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2575 if (!CYJSValueIsNSObject(context, _this))
2578 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2579 id value(internal->value_);
2586 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2588 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2589 return CYJSUndefined(context);
2590 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2593 return CYCastJSValue(context, CYJSString(context, [value description]));
2595 } CYCatch(NULL) return /*XXX*/ NULL; }
2597 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2598 if (!CYJSValueIsNSObject(context, _this))
2601 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2602 id value(internal->value_);
2603 _assert(value != nil);
2605 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2608 if (JSValueRef result = [value cy$valueOfInContext:context])
2612 } CYCatch(NULL) return /*XXX*/ NULL; }
2614 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2615 if (!CYJSValueIsNSObject(context, _this))
2618 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2619 // XXX: but... but... THIS ISN'T A POINTER! :(
2620 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2621 } CYCatch(NULL) return /*XXX*/ NULL; }
2623 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2624 if (!CYJSValueIsNSObject(context, _this))
2627 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2628 id value(internal->value_);
2631 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2632 return CYCastJSValue(context, CYJSString(context, [value description]));
2634 } CYCatch(NULL) return /*XXX*/ NULL; }
2636 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2637 if (!CYJSValueIsNSObject(context, _this))
2640 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2641 id value(internal->value_);
2643 if (!CYIsClass(value))
2644 CYThrow("non-Class object cannot be used as Type");
2646 sig::Object type(class_getName(value));
2647 return CYMakeType(context, type);
2648 } CYCatch(NULL) return /*XXX*/ NULL; }
2650 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2651 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2652 return CYCastJSValue(context, sel_getName(internal->value_));
2655 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2656 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2659 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2660 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2661 const char *name(sel_getName(internal->value_));
2664 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2665 return CYCastJSValue(context, CYJSString(context, string));
2667 } CYCatch(NULL) return /*XXX*/ NULL; }
2669 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2671 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2674 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2675 SEL sel(internal->value_);
2677 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2678 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2679 const char *encoding(method_getTypeEncoding(method));
2681 sig::Function type(false);
2682 sig::Parse(pool, &type.signature, encoding, &Structor_);
2683 return CYMakeType(context, type);
2686 static JSStaticValue Selector_staticValues[2] = {
2687 {"$cyt", &Selector_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2688 {NULL, NULL, NULL, 0}
2691 static JSStaticValue Instance_staticValues[5] = {
2692 {"$cyt", &Instance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2693 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2694 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2695 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2696 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2697 {NULL, NULL, NULL, 0}
2700 static JSStaticValue FunctionInstance_staticValues[5] = {
2701 {"$cyt", &FunctionInstance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2702 // XXX: this is sadly a duplicate of Instance_staticValues
2703 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2704 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2705 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2706 {NULL, NULL, NULL, 0}
2709 static JSStaticFunction Instance_staticFunctions[6] = {
2710 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2711 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2712 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2713 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2714 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2718 static JSStaticFunction Class_staticFunctions[2] = {
2719 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2723 static JSStaticFunction Interior_staticFunctions[2] = {
2724 {"$cya", &Interior_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2728 static JSStaticFunction Selector_staticFunctions[5] = {
2729 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2730 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2731 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2732 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2737 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2738 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2739 } CYObjectiveCatch }
2742 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2743 NSArray_ = objc_getClass("NSArray");
2744 NSBlock_ = objc_getClass("NSBlock");
2745 NSDictionary_ = objc_getClass("NSDictionary");
2746 NSNumber_ = objc_getClass("NSNumber");
2747 NSString_ = objc_getClass("NSString");
2748 Object_ = objc_getClass("Object");
2751 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2753 // XXX: apparently, iOS now has both of these
2754 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2755 if (NSCFBoolean_ == nil)
2756 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2758 NSCFType_ = objc_getClass("NSCFType");
2760 NSZombie_ = objc_getClass("_NSZombie_");
2762 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2763 NSZombie_ = objc_getClass("NSZombie");
2766 JSClassDefinition definition;
2768 definition = kJSClassDefinitionEmpty;
2769 definition.className = "Instance";
2770 definition.staticValues = Instance_staticValues;
2771 definition.staticFunctions = Instance_staticFunctions;
2772 definition.hasProperty = &Instance_hasProperty;
2773 definition.getProperty = &Instance_getProperty;
2774 definition.setProperty = &Instance_setProperty;
2775 definition.deleteProperty = &Instance_deleteProperty;
2776 definition.getPropertyNames = &Instance_getPropertyNames;
2777 definition.callAsConstructor = &Instance_callAsConstructor;
2778 definition.hasInstance = &Instance_hasInstance;
2779 definition.finalize = &CYFinalize;
2780 Instance::Class_ = JSClassCreate(&definition);
2782 definition.className = "ArrayInstance";
2783 ArrayInstance_ = JSClassCreate(&definition);
2785 definition.className = "BooleanInstance";
2786 BooleanInstance_ = JSClassCreate(&definition);
2788 definition.className = "NumberInstance";
2789 NumberInstance_ = JSClassCreate(&definition);
2791 definition.className = "ObjectInstance";
2792 ObjectInstance_ = JSClassCreate(&definition);
2794 definition.className = "StringInstance";
2795 StringInstance_ = JSClassCreate(&definition);
2797 definition.className = "FunctionInstance";
2798 definition.staticValues = FunctionInstance_staticValues;
2799 definition.callAsFunction = &FunctionInstance_callAsFunction;
2800 FunctionInstance_ = JSClassCreate(&definition);
2802 definition = kJSClassDefinitionEmpty;
2803 definition.className = "Class";
2804 definition.staticFunctions = Class_staticFunctions;
2805 ClassInstance_ = JSClassCreate(&definition);
2807 definition = kJSClassDefinitionEmpty;
2808 definition.className = "Interior";
2809 definition.staticFunctions = Interior_staticFunctions;
2810 definition.hasProperty = &Interior_hasProperty;
2811 definition.getProperty = &Interior_getProperty;
2812 definition.setProperty = &Interior_setProperty;
2813 definition.getPropertyNames = &Interior_getPropertyNames;
2814 definition.finalize = &CYFinalize;
2815 Interior::Class_ = JSClassCreate(&definition);
2817 definition = kJSClassDefinitionEmpty;
2818 definition.className = "Message";
2819 definition.staticFunctions = cy::Functor::StaticFunctions;
2820 definition.staticValues = cy::Functor::StaticValues;
2821 definition.callAsFunction = &Message_callAsFunction;
2822 definition.finalize = &CYFinalize;
2823 Message_privateData::Class_ = JSClassCreate(&definition);
2825 definition = kJSClassDefinitionEmpty;
2826 definition.className = "Messages";
2827 definition.hasProperty = &Messages_hasProperty;
2828 definition.getProperty = &Messages_getProperty;
2829 definition.setProperty = &Messages_setProperty;
2830 definition.getPropertyNames = &Messages_getPropertyNames;
2831 definition.finalize = &CYFinalize;
2832 Messages::Class_ = JSClassCreate(&definition);
2834 definition = kJSClassDefinitionEmpty;
2835 definition.className = "Selector";
2836 definition.staticValues = Selector_staticValues;
2837 definition.staticFunctions = Selector_staticFunctions;
2838 definition.callAsFunction = &Selector_callAsFunction;
2839 definition.finalize = &CYFinalize;
2840 Selector_privateData::Class_ = JSClassCreate(&definition);
2842 definition = kJSClassDefinitionEmpty;
2843 definition.className = "Super";
2844 definition.finalize = &CYFinalize;
2845 cy::Super::Class_ = JSClassCreate(&definition);
2847 definition = kJSClassDefinitionEmpty;
2848 definition.className = "ObjectiveC::Classes";
2849 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2850 definition.getProperty = &ObjectiveC_Classes_getProperty;
2851 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2852 ObjectiveC_Classes_ = JSClassCreate(&definition);
2854 definition = kJSClassDefinitionEmpty;
2855 definition.className = "ObjectiveC::Constants";
2856 definition.getProperty = &ObjectiveC_Constants_getProperty;
2857 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2858 ObjectiveC_Constants_ = JSClassCreate(&definition);
2861 definition = kJSClassDefinitionEmpty;
2862 definition.className = "ObjectiveC::Images";
2863 definition.getProperty = &ObjectiveC_Images_getProperty;
2864 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2865 ObjectiveC_Images_ = JSClassCreate(&definition);
2867 definition = kJSClassDefinitionEmpty;
2868 definition.className = "ObjectiveC::Image::Classes";
2869 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2870 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2871 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2874 definition = kJSClassDefinitionEmpty;
2875 definition.className = "ObjectiveC::Protocols";
2876 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2877 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2878 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2881 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2882 // XXX: this is horrible; there has to be a better way to do this
2884 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2886 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2892 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2893 JSObjectRef global(CYGetGlobalObject(context));
2894 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2895 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2896 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2897 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2899 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2900 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2902 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2903 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2904 CYArrayPush(context, alls, protocols);
2906 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2907 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2908 CYArrayPush(context, alls, classes);
2910 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2911 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2912 CYArrayPush(context, alls, constants);
2915 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2918 JSObjectRef Message(JSObjectMakeConstructor(context, Message_privateData::Class_, NULL));
2919 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_privateData::Class_, &Selector_new));
2920 JSObjectRef Super(JSObjectMakeConstructor(context, cy::Super::Class_, &Super_new));
2922 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance::Class_, &Instance_new));
2923 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2924 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2926 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2927 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2928 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2929 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2930 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2932 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2933 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2934 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2935 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2936 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2938 JSObjectRef ClassInstance(JSObjectMakeConstructor(context, ClassInstance_, NULL));
2939 JSObjectRef ClassInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ClassInstance, prototype_s)));
2940 CYSetProperty(context, cy, CYJSString("ClassInstance_prototype"), ClassInstance_prototype);
2941 // XXX: this doesn't fit the pattern of the other ones; maybe it sort of should?
2942 CYSetPrototype(context, ClassInstance_prototype, Instance_prototype);
2944 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2945 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2946 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2947 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2948 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2950 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2951 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2952 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2953 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2954 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2956 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2957 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2958 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2959 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2960 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2962 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2963 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2964 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2965 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2966 CYSetPrototype(context, StringInstance_prototype, String_prototype);
2968 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2969 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2970 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
2972 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2973 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
2976 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2979 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2981 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2982 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2984 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
2985 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
2986 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
2987 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::Object()), kJSPropertyAttributeDontEnum);
2988 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::Meta()), kJSPropertyAttributeDontEnum);
2989 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::Selector()), kJSPropertyAttributeDontEnum);
2991 CYSetProperty(context, cy, CYJSString("cydget"), CYCastJSValue(context, false));
2994 static void *CYObjectiveC_CastSymbol(const char *name) {
2996 #ifdef __GNU_LIBOBJC__
2997 else if (strcmp(name, "object_getClass") == 0)
2998 return reinterpret_cast<void *>(&object_getClass);
3003 static CYHook CYObjectiveCHook = {
3004 &CYObjectiveC_ExecuteStart,
3005 &CYObjectiveC_ExecuteEnd,
3006 &CYObjectiveC_CallFunction,
3007 &CYObjectiveC_Initialize,
3008 &CYObjectiveC_SetupContext,
3009 &CYObjectiveC_CastSymbol,
3012 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3014 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3015 CYSetupContext(context);
3016 JSObjectRef global(CYGetGlobalObject(context));
3017 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
3018 CYSetProperty(context, cy, CYJSString("cydget"), CYCastJSValue(context, true));
3019 } CYObjectiveCatch }
3021 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3024 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3025 utf8 = CYPoolCode(pool, utf8);
3027 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3028 size_t bytes(utf16.size * sizeof(uint16_t));
3029 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3030 memcpy(copy, utf16.data, bytes);
3034 } catch (const CYException &exception) {
3036 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];