1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2015 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "cycript.hpp"
32 #include <malloc/malloc.h>
33 #include <mach/mach.h>
36 #include <objc/message.h>
37 #include <objc/runtime.h>
40 #include <CoreFoundation/CoreFoundation.h>
41 #include <JavaScriptCore/JSStringRefCF.h>
44 #include <Foundation/Foundation.h>
49 #include "JavaScript.hpp"
51 #include "Execute.hpp"
53 #include "ObjectiveC/Internal.hpp"
54 #include "ObjectiveC/Syntax.hpp"
56 #define CYObjectiveTry_ { \
58 #define CYObjectiveTry { \
59 JSContextRef context(context_); \
61 #define CYObjectiveCatch \
62 catch (const CYException &error) { \
63 @throw CYCastNSObject(NULL, context, error.CastJSValue(context, "Error")); \
69 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
71 #define CYPoolCatch(value) \
72 @catch (NSException *error) { \
73 _saved = [error retain]; \
74 throw CYJSError(context, CYCastJSValue(context, error)); \
79 [_saved autorelease]; \
85 #define CYSadCatch(value) \
86 @catch (NSException *error ) { \
87 throw CYJSError(context, CYCastJSValue(context, error)); \
91 #define _oassert(test) \
93 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"_assert(" #test ")" userInfo:nil];
101 void (*invoke)(void *, ...);
105 struct BlockDescriptor1 {
106 unsigned long int reserved;
107 unsigned long int size;
110 struct BlockDescriptor2 {
111 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
112 void (*dispose_helper)(BlockLiteral *src);
115 struct BlockDescriptor3 {
116 const char *signature;
121 BLOCK_DEALLOCATING = 0x0001,
122 BLOCK_REFCOUNT_MASK = 0xfffe,
123 BLOCK_NEEDS_FREE = 1 << 24,
124 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
125 BLOCK_HAS_CTOR = 1 << 26,
126 BLOCK_IS_GC = 1 << 27,
127 BLOCK_IS_GLOBAL = 1 << 28,
128 BLOCK_HAS_STRET = 1 << 29,
129 BLOCK_HAS_SIGNATURE = 1 << 30,
132 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
134 /* Objective-C Pool Release {{{ */
135 void CYPoolRelease_(void *data) {
136 id object(reinterpret_cast<id>(data));
140 id CYPoolRelease_(CYPool *pool, id object) {
143 else if (pool == NULL)
144 return [object autorelease];
146 pool->atexit(CYPoolRelease_);
151 template <typename Type_>
152 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
153 return (Type_) CYPoolRelease_(pool, (id) object);
156 /* Objective-C Strings {{{ */
157 CYUTF8String CYPoolUTF8String(CYPool &pool, JSContextRef context, NSString *value) {
158 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
159 char *string(new(pool) char[size + 1]);
160 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
161 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
162 return CYUTF8String(string, [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
165 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
166 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
167 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
172 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
173 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
177 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
180 // XXX: this definition scares me; is anyone using this?!
181 NSString *string([value description]);
183 return CYCopyJSString(context, string);
186 return CYCopyJSString(CYPoolUTF8String(pool, context, string));
190 NSString *CYCopyNSString(const CYUTF8String &value) {
192 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
194 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
198 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
200 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
203 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
207 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
208 return CYCopyNSString(context, CYJSString(context, value));
211 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
212 return CYPoolRelease(pool, CYCopyNSString(value));
215 NSString *CYCastNSString(CYPool *pool, SEL sel) {
216 const char *name(sel_getName(sel));
217 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
220 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
221 return CYPoolRelease(pool, CYCopyNSString(context, value));
224 CYUTF8String CYCastUTF8String(NSString *value) {
225 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
226 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
230 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
232 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
233 if (exception == NULL)
235 *exception = CYCastJSValue(context, error);
238 size_t CYGetIndex(NSString *value) {
239 return CYGetIndex(CYCastUTF8String(value));
242 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
243 return CYGetOffset(CYPoolCString(pool, context, value), index);
246 static JSClassRef Instance_;
248 static JSClassRef ArrayInstance_;
249 static JSClassRef BooleanInstance_;
250 static JSClassRef FunctionInstance_;
251 static JSClassRef NumberInstance_;
252 static JSClassRef ObjectInstance_;
253 static JSClassRef StringInstance_;
255 static JSClassRef Class_;
256 static JSClassRef Internal_;
257 static JSClassRef Message_;
258 static JSClassRef Messages_;
259 static JSClassRef Selector_;
260 static JSClassRef Super_;
262 static JSClassRef ObjectiveC_Classes_;
263 static JSClassRef ObjectiveC_Constants_;
264 static JSClassRef ObjectiveC_Protocols_;
267 static JSClassRef ObjectiveC_Image_Classes_;
268 static JSClassRef ObjectiveC_Images_;
272 static Class __NSMallocBlock__;
273 static Class NSCFBoolean_;
274 static Class NSCFType_;
275 static Class NSGenericDeallocHandler_;
277 static Class NSBoolNumber_;
280 static Class NSArray_;
281 static Class NSBlock_;
282 static Class NSDictionary_;
283 static Class NSNumber_;
284 static Class NSString_;
285 static Class NSZombie_;
286 static Class Object_;
288 static Type_privateData *Object_type;
289 static Type_privateData *Selector_type;
291 Type_privateData *Instance::GetType() const {
295 Type_privateData *Selector_privateData::GetType() const {
296 return Selector_type;
299 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
301 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
303 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
304 else if (meta && !class_isMetaClass(self))
305 return CYGetCachedObject(context, CYJSString("Class_prototype"));
307 JSObjectRef global(CYGetGlobalObject(context));
308 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
311 sprintf(label, "i%p", self);
312 CYJSString name(label);
314 JSValueRef value(CYGetProperty(context, cy, name));
315 if (!JSValueIsUndefined(context, value))
318 JSClassRef _class(NULL);
319 JSValueRef prototype;
322 if (self == NSCFBoolean_)
324 if (self == NSBoolNumber_)
326 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
327 else if (self == NSArray_)
328 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
329 else if (self == NSBlock_)
330 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
331 else if (self == NSNumber_)
332 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
333 else if (self == NSDictionary_)
334 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
335 else if (self == NSString_)
336 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
338 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
340 JSObjectRef object(JSObjectMake(context, _class, NULL));
341 CYSetPrototype(context, object, prototype);
342 CYSetProperty(context, cy, name, object);
347 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
348 return CYGetClassPrototype(context, self, class_isMetaClass(self));
351 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
352 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
353 if (Class super = class_getSuperclass(_class))
354 CYSetPrototype(context, value, Messages::Make(context, super));
358 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
359 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
363 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
364 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
368 bool CYIsKindOfClass(id object, Class _class) {
369 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
375 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
376 JSObjectRef value(JSObjectMake(context, CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance_, new Instance(object, flags)));
377 CYSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
381 Instance::~Instance() {
382 if ((flags_ & Permanent) == 0)
383 [GetValue() release];
386 struct Message_privateData :
391 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
392 cy::Functor(reinterpret_cast<void (*)()>(value), type),
398 JSObjectRef CYMakeInstance(JSContextRef context, id object, Instance::Flags flags = Instance::None) {
399 _assert(object != nil);
402 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
404 if (weak != NULL && &JSWeakObjectMapGet != NULL)
405 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
409 if ((flags & Instance::Permanent) == 0)
410 object = [object retain];
412 JSObjectRef instance(Instance::Make(context, object, flags));
415 if (weak != NULL && &JSWeakObjectMapSet != NULL)
416 JSWeakObjectMapSet(context, weak, object, instance);
422 @interface NSMethodSignature (Cycript)
423 - (NSString *) _typeString;
426 @interface NSObject (Cycript)
428 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
429 - (JSType) cy$JSType;
431 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
432 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
434 - (bool) cy$hasProperty:(NSString *)name;
435 - (NSObject *) cy$getProperty:(NSString *)name;
436 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
437 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
438 - (bool) cy$deleteProperty:(NSString *)name;
439 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
441 + (bool) cy$hasImplicitProperties;
447 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
450 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
451 _assert(value != nil);
453 Class _class(object_getClass(value));
455 if (class_isMetaClass(_class)) {
456 const char *name(class_getName(value));
457 if (class_isMetaClass(value))
458 return [NSString stringWithFormat:@"object_getClass(%s)", name];
460 return [NSString stringWithUTF8String:name];
463 if (_class == NSZombie_)
464 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
466 SEL sel(@selector(cy$toCYON:inSet:));
468 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
469 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
470 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
471 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
472 return [value cy$toCYON:objective inSet:objects];
474 return [NSString stringWithFormat:@"%@", value];
477 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
479 return CYCastNSCYON(value, objective, *objects);
481 std::set<void *> objects;
482 return CYCastNSCYON(value, objective, objects);
486 struct PropertyAttributes {
491 const char *variable;
504 PropertyAttributes(objc_property_t property) :
516 name = property_getName(property);
517 const char *attributes(property_getAttributes(property));
519 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
520 if ((next = strchr(token, ',')) != NULL)
523 case 'R': readonly = true; break;
524 case 'C': copy = true; break;
525 case '&': retain = true; break;
526 case 'N': nonatomic = true; break;
527 case 'G': getter_ = token + 1; break;
528 case 'S': setter_ = token + 1; break;
529 case 'V': variable = token + 1; break;
533 /*if (variable == NULL) {
534 variable = property_getName(property);
535 size_t size(strlen(variable));
536 char *name(new(pool_) char[size + 2]);
538 memcpy(name + 1, variable, size);
539 name[size + 1] = '\0';
544 const char *Getter() {
546 getter_ = pool_.strdup(name);
550 const char *Setter() {
551 if (setter_ == NULL && !readonly) {
552 size_t length(strlen(name));
554 char *temp(new(pool_) char[length + 5]);
560 temp[3] = toupper(name[0]);
561 memcpy(temp + 4, name + 1, length - 1);
564 temp[length + 3] = ':';
565 temp[length + 4] = '\0';
574 @interface CYWebUndefined : NSObject {
577 + (CYWebUndefined *) undefined;
581 @implementation CYWebUndefined
583 + (CYWebUndefined *) undefined {
584 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
590 #define WebUndefined CYWebUndefined
592 /* Bridge: CYJSObject {{{ */
593 @interface CYJSObject : NSMutableDictionary {
595 JSGlobalContextRef context_;
598 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
600 - (NSUInteger) count;
601 - (id) objectForKey:(id)key;
602 - (NSEnumerator *) keyEnumerator;
603 - (void) setObject:(id)object forKey:(id)key;
604 - (void) removeObjectForKey:(id)key;
608 /* Bridge: CYJSArray {{{ */
609 @interface CYJSArray : NSMutableArray {
611 JSGlobalContextRef context_;
614 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
616 - (NSUInteger) count;
617 - (id) objectAtIndex:(NSUInteger)index;
619 - (void) addObject:(id)anObject;
620 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
621 - (void) removeLastObject;
622 - (void) removeObjectAtIndex:(NSUInteger)index;
623 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
628 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
629 return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
632 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
633 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
637 struct CYBlockDescriptor {
639 BlockDescriptor1 one_;
640 BlockDescriptor2 two_;
641 BlockDescriptor3 three_;
644 Closure_privateData *internal_;
647 void CYDisposeBlock(BlockLiteral *literal) {
648 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
651 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
652 JSObjectRef _this(CYCastJSObject(context, values[0]));
653 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
656 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
657 _assert(__NSMallocBlock__ != Nil);
658 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
660 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
661 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
663 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockAdapter_);
664 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
666 literal->isa = __NSMallocBlock__;
667 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
668 literal->reserved = 0;
669 literal->descriptor = descriptor;
671 descriptor->d_.one_.size = sizeof(descriptor->d_);
672 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
673 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
675 return reinterpret_cast<NSBlock *>(literal);
679 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
680 if (CYJSValueIsNSObject(context, object)) {
681 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
682 return internal->GetValue();
685 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
686 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
687 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
690 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
691 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
695 @interface NSBoolNumber : NSNumber {
700 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
704 switch (JSType type = JSValueGetType(context, value)) {
705 case kJSTypeUndefined:
706 object = [WebUndefined undefined];
716 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
719 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
725 object = CYCopyNSNumber(context, value);
730 object = CYCopyNSString(context, value);
735 // XXX: this might could be more efficient
736 object = CYCastNSObject(pool, context, (JSObjectRef) value);
741 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
748 return CYPoolRelease(pool, object);
750 return [object retain];
753 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
754 return CYNSObject(pool, context, value, true);
757 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
758 return CYNSObject(&pool, context, value, false);
761 /* Bridge: NSArray {{{ */
762 @implementation NSArray (Cycript)
765 return [[self mutableCopy] autorelease];
768 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
769 _oassert(objects.insert(self).second);
771 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
772 [json appendString:@"@["];
776 for (id object in self) {
778 for (size_t index(0), count([self count]); index != count; ++index) {
779 id object([self objectAtIndex:index]);
782 [json appendString:@","];
785 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
786 [json appendString:CYCastNSCYON(object, true, objects)];
788 [json appendString:@","];
793 [json appendString:@"]"];
797 - (bool) cy$hasProperty:(NSString *)name {
798 if ([name isEqualToString:@"length"])
801 size_t index(CYGetIndex(name));
802 if (index == _not(size_t) || index >= [self count])
803 return [super cy$hasProperty:name];
808 - (NSObject *) cy$getProperty:(NSString *)name {
809 size_t index(CYGetIndex(name));
810 if (index == _not(size_t) || index >= [self count])
811 return [super cy$getProperty:name];
813 return [self objectAtIndex:index];
816 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
818 if ([name isEqualToString:@"length"])
819 return CYCastJSValue(context, [self count]);
822 return [super cy$getProperty:name inContext:context];
825 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
826 [super cy$getPropertyNames:names inContext:context];
828 for (size_t index(0), count([self count]); index != count; ++index) {
829 id object([self objectAtIndex:index]);
830 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
832 sprintf(name, "%zu", index);
833 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
838 + (bool) cy$hasImplicitProperties {
844 /* Bridge: NSBlock {{{ */
846 @interface NSBlock : NSObject
850 static const char *CYBlockEncoding(NSBlock *self);
851 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature);
853 @implementation NSBlock (Cycript)
855 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
859 if (!CYBlockSignature(pool, self, type.signature))
860 return [super cy$toCYON:objective inSet:objects];
861 _oassert(objects.insert(self).second);
863 CYTypedIdentifier *typed((new(pool) CYTypeExpression(CYDecodeType(pool, &type)))->typed_);
864 CYTypeModifier *&modifier(CYGetLast(typed->modifier_));
865 CYTypeBlockWith *with(dynamic_cast<CYTypeBlockWith *>(modifier));
866 _assert(with != NULL);
867 CYObjCBlock *block(new(pool) CYObjCBlock(typed, with->parameters_, NULL));
870 std::ostringstream str;
872 CYOutput out(*str.rdbuf(), options);
873 block->Output(out, CYNoFlags);
875 std::string value(str.str());
876 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
882 /* Bridge: NSBoolNumber {{{ */
884 @implementation NSBoolNumber (Cycript)
886 - (JSType) cy$JSType {
887 return kJSTypeBoolean;
890 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
891 NSString *value([self boolValue] ? @"true" : @"false");
892 return objective ? value : [NSString stringWithFormat:@"@%@", value];
895 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
896 return CYCastJSValue(context, (bool) [self boolValue]);
902 /* Bridge: NSDictionary {{{ */
903 @implementation NSDictionary (Cycript)
906 return [[self mutableCopy] autorelease];
909 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
910 _oassert(objects.insert(self).second);
912 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
913 [json appendString:@"@{"];
917 for (NSObject *key in self) {
919 NSEnumerator *keys([self keyEnumerator]);
920 while (NSObject *key = [keys nextObject]) {
923 [json appendString:@","];
926 [json appendString:CYCastNSCYON(key, true, objects)];
927 [json appendString:@":"];
928 NSObject *object([self objectForKey:key]);
929 [json appendString:CYCastNSCYON(object, true, objects)];
932 [json appendString:@"}"];
936 - (bool) cy$hasProperty:(NSString *)name {
937 return [self objectForKey:name] != nil;
940 - (NSObject *) cy$getProperty:(NSString *)name {
941 return [self objectForKey:name];
944 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
945 [super cy$getPropertyNames:names inContext:context];
948 for (NSObject *key in self) {
950 NSEnumerator *keys([self keyEnumerator]);
951 while (NSObject *key = [keys nextObject]) {
953 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
957 + (bool) cy$hasImplicitProperties {
963 /* Bridge: NSMutableArray {{{ */
964 @implementation NSMutableArray (Cycript)
966 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
967 if ([name isEqualToString:@"length"]) {
968 // XXX: is this not intelligent?
969 NSNumber *number(reinterpret_cast<NSNumber *>(value));
970 NSUInteger size([number unsignedIntegerValue]);
971 NSUInteger count([self count]);
973 [self removeObjectsInRange:NSMakeRange(size, count - size)];
974 else if (size != count) {
975 WebUndefined *undefined([WebUndefined undefined]);
976 for (size_t i(count); i != size; ++i)
977 [self addObject:undefined];
982 size_t index(CYGetIndex(name));
983 if (index == _not(size_t))
984 return [super cy$setProperty:name to:value];
986 id object(value ?: [NSNull null]);
988 size_t count([self count]);
990 [self replaceObjectAtIndex:index withObject:object];
992 if (index != count) {
993 WebUndefined *undefined([WebUndefined undefined]);
994 for (size_t i(count); i != index; ++i)
995 [self addObject:undefined];
998 [self addObject:object];
1004 - (bool) cy$deleteProperty:(NSString *)name {
1005 size_t index(CYGetIndex(name));
1006 if (index == _not(size_t) || index >= [self count])
1007 return [super cy$deleteProperty:name];
1008 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1014 /* Bridge: NSMutableDictionary {{{ */
1015 @implementation NSMutableDictionary (Cycript)
1017 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1018 [self setObject:(value ?: [NSNull null]) forKey:name];
1022 - (bool) cy$deleteProperty:(NSString *)name {
1023 if ([self objectForKey:name] == nil)
1026 [self removeObjectForKey:name];
1033 /* Bridge: NSNumber {{{ */
1034 @implementation NSNumber (Cycript)
1036 - (JSType) cy$JSType {
1038 // XXX: this just seems stupid
1039 if ([self class] == NSCFBoolean_)
1040 return kJSTypeBoolean;
1042 return kJSTypeNumber;
1045 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1046 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1047 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1050 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1051 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1052 } CYObjectiveCatch }
1056 /* Bridge: NSNull {{{ */
1057 @implementation NSNull (Cycript)
1059 - (JSType) cy$JSType {
1063 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1064 NSString *value(@"null");
1065 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1068 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1069 return CYJSNull(context);
1070 } CYObjectiveCatch }
1074 /* Bridge: NSObject {{{ */
1075 @implementation NSObject (Cycript)
1081 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1082 return [self cy$valueOfInContext:context];
1085 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1087 } CYObjectiveCatch }
1089 - (JSType) cy$JSType {
1090 return kJSTypeObject;
1093 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1094 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1097 - (bool) cy$hasProperty:(NSString *)name {
1101 - (NSObject *) cy$getProperty:(NSString *)name {
1105 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1106 if (NSObject *value = [self cy$getProperty:name])
1107 return CYCastJSValue(context, value);
1109 } CYObjectiveCatch }
1111 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1115 - (bool) cy$deleteProperty:(NSString *)name {
1119 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1122 + (bool) cy$hasImplicitProperties {
1128 /* Bridge: NSOrderedSet {{{ */
1130 @implementation NSOrderedSet (Cycript)
1132 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1133 _oassert(objects.insert(self).second);
1135 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1136 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1137 [json appendString:CYCastNSCYON([self array], true, objects)];
1138 [json appendString:@"]]"];
1145 /* Bridge: NSProxy {{{ */
1146 @implementation NSProxy (Cycript)
1148 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1149 return [[self description] cy$toCYON:objective inSet:objects];
1154 /* Bridge: NSSet {{{ */
1155 @implementation NSSet (Cycript)
1157 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1158 _oassert(objects.insert(self).second);
1160 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1161 [json appendString:@"[NSSet setWithArray:"];
1162 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1163 [json appendString:@"]]"];
1169 /* Bridge: NSString {{{ */
1170 @implementation NSString (Cycript)
1173 return [[self copy] autorelease];
1176 - (JSType) cy$JSType {
1177 return kJSTypeString;
1180 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1181 std::ostringstream str;
1184 CYUTF8String string(CYCastUTF8String(self));
1185 CYStringify(str, string.data, string.size, true);
1186 std::string value(str.str());
1187 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1190 - (bool) cy$hasProperty:(NSString *)name {
1191 size_t index(CYGetIndex(name));
1192 if (index == _not(size_t) || index >= [self length])
1193 return [super cy$hasProperty:name];
1198 - (NSObject *) cy$getProperty:(NSString *)name {
1199 size_t index(CYGetIndex(name));
1200 if (index == _not(size_t) || index >= [self length])
1201 return [super cy$getProperty:name];
1203 return [self substringWithRange:NSMakeRange(index, 1)];
1206 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1207 [super cy$getPropertyNames:names inContext:context];
1209 for (size_t index(0), length([self length]); index != length; ++index) {
1211 sprintf(name, "%zu", index);
1212 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1216 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1217 return CYCastJSValue(context, CYJSString(context, self));
1218 } CYObjectiveCatch }
1222 /* Bridge: WebUndefined {{{ */
1223 @implementation WebUndefined (Cycript)
1225 - (JSType) cy$JSType {
1226 return kJSTypeUndefined;
1229 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1230 NSString *value(@"undefined");
1231 return value; // XXX: maybe use the below code, adding @undefined?
1232 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1235 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1236 return CYJSUndefined(context);
1237 } CYObjectiveCatch }
1242 static bool CYIsClass(id self) {
1243 return class_isMetaClass(object_getClass(self));
1246 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1247 id self(CYCastNSObject(&pool, context, value));
1248 if (CYIsClass(self))
1249 return (Class) self;
1250 throw CYJSError(context, "got something that is not a Class");
1254 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1256 size_t size(JSPropertyNameArrayGetCount(names));
1257 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1258 for (size_t index(0); index != size; ++index)
1259 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1263 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) {
1265 return CYJSNull(context);
1266 return CYMakeInstance(context, value);
1269 @implementation CYJSObject
1271 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1272 if ((self = [super init]) != nil) {
1274 context_ = CYGetJSContext(context);
1275 JSGlobalContextRetain(context_);
1276 JSValueProtect(context_, object_);
1278 } CYObjectiveCatch }
1280 - (void) dealloc { CYObjectiveTry {
1281 JSValueUnprotect(context_, object_);
1282 JSGlobalContextRelease(context_);
1284 } CYObjectiveCatch }
1286 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1288 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1290 return [super cy$toCYON:objective inSet:objects];
1292 return [NSString stringWithUTF8String:cyon];
1293 } CYObjectiveCatch }
1295 - (NSUInteger) count { CYObjectiveTry {
1296 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1297 size_t size(JSPropertyNameArrayGetCount(names));
1298 JSPropertyNameArrayRelease(names);
1300 } CYObjectiveCatch }
1302 - (id) objectForKey:(id)key { CYObjectiveTry {
1303 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1304 if (JSValueIsUndefined(context, value))
1306 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1307 } CYObjectiveCatch }
1309 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1310 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1311 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1312 JSPropertyNameArrayRelease(names);
1314 } CYObjectiveCatch }
1316 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1317 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1318 } CYObjectiveCatch }
1320 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1321 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1322 } CYObjectiveCatch }
1326 @implementation CYJSArray
1328 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1330 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1331 } CYObjectiveCatch }
1333 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1334 if ((self = [super init]) != nil) {
1336 context_ = CYGetJSContext(context);
1337 JSGlobalContextRetain(context_);
1338 JSValueProtect(context_, object_);
1340 } CYObjectiveCatch }
1342 - (void) dealloc { CYObjectiveTry {
1343 JSValueUnprotect(context_, object_);
1344 JSGlobalContextRelease(context_);
1346 } CYObjectiveCatch }
1348 - (NSUInteger) count { CYObjectiveTry {
1349 return CYArrayLength(context, object_);
1350 } CYObjectiveCatch }
1352 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1353 size_t bounds([self count]);
1354 if (index >= bounds)
1355 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1356 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1357 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1358 } CYObjectiveCatch }
1360 - (void) addObject:(id)object { CYObjectiveTry {
1361 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1362 } CYObjectiveCatch }
1364 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1365 size_t bounds([self count] + 1);
1366 if (index >= bounds)
1367 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1368 JSValueRef arguments[3];
1369 arguments[0] = CYCastJSValue(context, index);
1370 arguments[1] = CYCastJSValue(context, 0);
1371 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1372 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1373 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1374 } CYObjectiveCatch }
1376 - (void) removeLastObject { CYObjectiveTry {
1377 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1378 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1379 } CYObjectiveCatch }
1381 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1382 size_t bounds([self count]);
1383 if (index >= bounds)
1384 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1385 JSValueRef arguments[2];
1386 arguments[0] = CYCastJSValue(context, index);
1387 arguments[1] = CYCastJSValue(context, 1);
1388 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1389 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1390 } CYObjectiveCatch }
1392 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1393 size_t bounds([self count]);
1394 if (index >= bounds)
1395 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1396 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1397 } CYObjectiveCatch }
1401 // XXX: inherit from or replace with CYJSObject
1402 @interface CYInternal : NSObject {
1403 JSGlobalContextRef context_;
1404 JSObjectRef object_;
1409 @implementation CYInternal
1411 - (void) dealloc { CYObjectiveTry {
1412 JSValueUnprotect(context_, object_);
1413 JSGlobalContextRelease(context_);
1415 } CYObjectiveCatch }
1417 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1418 if ((self = [super init]) != nil) {
1419 context_ = CYGetJSContext(context);
1420 JSGlobalContextRetain(context_);
1422 } CYObjectiveCatch }
1424 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1425 if (object_ == NULL)
1428 return JSObjectHasProperty(context, object_, name);
1431 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1432 if (object_ == NULL)
1435 return CYGetProperty(context, object_, name);
1438 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1439 @synchronized (self) {
1440 if (object_ == NULL) {
1441 object_ = JSObjectMake(context, NULL, NULL);
1442 JSValueProtect(context, object_);
1446 CYSetProperty(context, object_, name, value);
1449 + (CYInternal *) get:(id)object {
1451 if (&objc_getAssociatedObject == NULL)
1454 @synchronized (object) {
1455 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1463 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1465 if (&objc_getAssociatedObject == NULL)
1468 @synchronized (object) {
1469 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1472 if (&objc_setAssociatedObject == NULL)
1475 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1476 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1486 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1487 Selector_privateData *internal(new Selector_privateData(sel));
1488 return JSObjectMake(context, Selector_, internal);
1491 static JSValueRef CYCastJSValue(JSContextRef context, SEL sel) {
1493 return CYJSNull(context);
1494 return CYMakeSelector(context, sel);
1497 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1498 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1499 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1500 return reinterpret_cast<SEL>(internal->value_);
1503 return sel_registerName(CYPoolCString(pool, context, value));
1507 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1508 return (void *) [[NSAutoreleasePool alloc] init];
1509 } CYSadCatch(NULL) }
1511 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1512 return [(NSAutoreleasePool *) handle release];
1515 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1516 CYCallFunction(pool, context, cif, function, value, values);
1519 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, const sig::Signature *signature) {
1521 if (JSValueIsNull(context, value))
1523 JSObjectRef object(CYCastJSObject(context, value));
1525 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1526 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1528 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1529 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1533 _assert(JSObjectIsFunction(context, object));
1535 _assert(signature != NULL);
1536 _assert(signature->count != 0);
1538 sig::Signature modified;
1539 modified.count = signature->count + 1;
1540 modified.elements = new(pool) sig::Element[modified.count];
1542 modified.elements[0] = signature->elements[0];
1543 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1545 modified.elements[1].name = NULL;
1546 modified.elements[1].type = new(pool) sig::Object();
1547 modified.elements[1].offset = _not(size_t);
1549 return CYMakeBlock(context, object, modified);
1557 void Block::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1558 // XXX: this function might not handle the idea of a null pool
1559 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &signature);
1562 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1563 void Object::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1564 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1567 void Meta::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1568 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1571 void Selector::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1572 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1575 JSValueRef Object::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1576 NSObject *value(*reinterpret_cast<NSObject **>(data));
1578 return CYJSNull(context);
1579 JSObjectRef object(CYMakeInstance(context, value));
1582 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1584 if ((internal->flags_ & Instance::Uninitialized) != 0) {
1585 internal->flags_ = static_cast<Instance::Flags>(internal->flags_ & ~Instance::Uninitialized);
1586 _assert(internal->value_ == nil);
1587 internal->value_ = value;
1596 JSValueRef Meta::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1597 if (Class value = *reinterpret_cast<Class *>(data))
1598 return CYMakeInstance(context, value, Instance::Permanent);
1599 return CYJSNull(context);
1602 JSValueRef Selector::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1603 return CYCastJSValue(context, *reinterpret_cast<SEL *>(data));
1606 JSValueRef Block::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1607 return CYCastJSValue(context, *reinterpret_cast<NSObject **>(data));
1612 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1613 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1617 method_getReturnType(method, type, sizeof(type));
1622 // XXX: possibly use a more "awesome" check?
1626 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1627 JSObjectRef _this(CYCastJSObject(context, values[0]));
1628 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1631 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1632 Message_privateData *internal(new Message_privateData(sel, type, imp));
1633 return JSObjectMake(context, Message_, internal);
1636 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1637 JSObjectRef function(CYCastJSObject(context, value));
1639 sig::Signature signature;
1640 sig::Parse(pool, &signature, encoding, &Structor_);
1641 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1642 // XXX: see notes in Library.cpp about needing to leak
1643 return reinterpret_cast<IMP>(internal->GetValue());
1646 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1647 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1648 Class _class(internal->GetValue());
1651 const char *name(CYPoolCString(pool, context, property));
1653 if (SEL sel = sel_getUid(name))
1654 if (class_getInstanceMethod(_class, sel) != NULL)
1660 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1661 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1662 Class _class(internal->GetValue());
1665 const char *name(CYPoolCString(pool, context, property));
1667 if (SEL sel = sel_getUid(name))
1668 if (objc_method *method = class_getInstanceMethod(_class, sel))
1669 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1674 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1675 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1676 Class _class(internal->GetValue());
1679 const char *name(CYPoolCString(pool, context, property));
1680 SEL sel(sel_registerName(name));
1685 if (JSValueIsObjectOfClass(context, value, Message_)) {
1686 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1687 type = sig::Unparse(pool, &message->signature_);
1688 imp = reinterpret_cast<IMP>(message->GetValue());
1689 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1690 type = method_getTypeEncoding(method);
1691 imp = CYMakeMessage(context, value, type);
1692 } else _assert(false);
1694 objc_method *method(NULL);
1696 objc_method **methods(class_copyMethodList(_class, &size));
1697 for (size_t i(0); i != size; ++i)
1698 if (sel_isEqual(method_getName(methods[i]), sel)) {
1699 method = methods[i];
1705 method_setImplementation(method, imp);
1707 class_addMethod(_class, sel, imp, type);
1712 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1713 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1714 Class _class(internal->GetValue());
1717 objc_method **data(class_copyMethodList(_class, &size));
1718 for (size_t i(0); i != size; ++i)
1719 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1723 static bool CYHasImplicitProperties(Class _class) {
1724 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1725 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1727 return [_class cy$hasImplicitProperties];
1730 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1731 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1732 id self(internal->GetValue());
1734 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1738 NSString *name(CYCastNSString(&pool, context, property));
1740 if (CYInternal *internal = [CYInternal get:self])
1741 if ([internal hasProperty:property inContext:context])
1744 Class _class(object_getClass(self));
1747 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1748 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1749 if ([self cy$hasProperty:name])
1751 } CYPoolCatch(false)
1753 const char *string(CYPoolCString(pool, context, name));
1755 if (class_getProperty(_class, string) != NULL)
1758 if (CYHasImplicitProperties(_class))
1759 if (SEL sel = sel_getUid(string))
1760 if (CYImplements(self, _class, sel, true))
1766 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1767 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1768 id self(internal->GetValue());
1770 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1771 return Internal::Make(context, self, object);
1774 NSString *name(CYCastNSString(&pool, context, property));
1776 if (CYInternal *internal = [CYInternal get:self])
1777 if (JSValueRef value = [internal getProperty:property inContext:context])
1781 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1785 const char *string(CYPoolCString(pool, context, name));
1786 Class _class(object_getClass(self));
1788 if (objc_property_t property = class_getProperty(_class, string)) {
1789 PropertyAttributes attributes(property);
1790 SEL sel(sel_registerName(attributes.Getter()));
1791 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1794 if (CYHasImplicitProperties(_class))
1795 if (SEL sel = sel_getUid(string))
1796 if (CYImplements(self, _class, sel, true))
1797 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1802 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1803 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1804 id self(internal->GetValue());
1808 NSString *name(CYCastNSString(&pool, context, property));
1809 NSObject *data(CYCastNSObject(&pool, context, value));
1812 if ([self cy$setProperty:name to:data])
1814 } CYPoolCatch(false)
1816 const char *string(CYPoolCString(pool, context, name));
1817 Class _class(object_getClass(self));
1819 if (objc_property_t property = class_getProperty(_class, string)) {
1820 PropertyAttributes attributes(property);
1821 if (const char *setter = attributes.Setter()) {
1822 SEL sel(sel_registerName(setter));
1823 JSValueRef arguments[1] = {value};
1824 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1829 size_t length(strlen(string));
1831 char set[length + 5];
1837 if (string[0] != '\0') {
1838 set[3] = toupper(string[0]);
1839 memcpy(set + 4, string + 1, length - 1);
1842 set[length + 3] = ':';
1843 set[length + 4] = '\0';
1845 if (SEL sel = sel_getUid(set))
1846 if (CYImplements(self, _class, sel)) {
1847 JSValueRef arguments[1] = {value};
1848 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1852 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1853 [internal setProperty:property toValue:value inContext:context];
1860 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1861 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1862 id self(internal->GetValue());
1865 NSString *name(CYCastNSString(NULL, context, property));
1866 return [self cy$deleteProperty:name];
1867 } CYPoolCatch(false)
1868 } CYCatch(false) return /*XXX*/ false; }
1870 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1871 const char *name(sel_getName(method_getName(method)));
1872 if (strchr(name, ':') != NULL)
1875 const char *type(method_getTypeEncoding(method));
1876 if (type == NULL || *type == '\0' || *type == 'v')
1879 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1882 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1883 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1884 id self(internal->GetValue());
1887 Class _class(object_getClass(self));
1891 objc_property_t *data(class_copyPropertyList(_class, &size));
1892 for (size_t i(0); i != size; ++i)
1893 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1897 if (CYHasImplicitProperties(_class))
1898 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1900 objc_method **data(class_copyMethodList(current, &size));
1901 for (size_t i(0); i != size; ++i)
1902 Instance_getPropertyNames_message(names, data[i]);
1907 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1908 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1909 [self cy$getPropertyNames:names inContext:context];
1913 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1914 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1915 JSObjectRef value(CYMakeInstance(context, [internal->GetValue() alloc], Instance::Uninitialized));
1919 static const char *CYBlockEncoding(NSBlock *self) {
1920 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1921 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1923 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1924 descriptor += sizeof(BlockDescriptor1);
1925 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1926 descriptor += sizeof(BlockDescriptor2);
1927 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1928 return descriptor3->signature;
1931 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature) {
1932 const char *encoding(CYBlockEncoding(self));
1933 if (encoding == NULL)
1936 sig::Parse(pool, &signature, encoding, &Structor_);
1937 _assert(signature.count >= 2);
1939 _assert(dynamic_cast<sig::Object *>(signature.elements[1].type) != NULL);
1940 signature.elements[1] = signature.elements[0];
1942 ++signature.elements;
1948 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1949 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1950 id self(internal->GetValue());
1952 if (const char *encoding = CYBlockEncoding(self)) {
1958 sig::Signature signature;
1959 sig::Parse(pool, &signature, encoding, &Structor_);
1962 sig::sig_ffi_cif(pool, 0, signature, &cif);
1964 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1965 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1966 return CYCallFunction(pool, context, 1, setup, count, arguments, false, false, signature, &cif, function);
1970 CYThrow("NSBlock without signature field passed arguments");
1974 } CYPoolCatch(NULL);
1979 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1980 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1981 Class _class(internal->GetValue());
1982 if (!CYIsClass(_class))
1985 if (CYJSValueIsNSObject(context, instance)) {
1986 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1987 // XXX: this isn't always safe
1988 return [linternal->GetValue() isKindOfClass:_class];
1994 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1996 throw CYJSError(context, "incorrect number of arguments to Instance");
1998 id value(CYCastNSObject(&pool, context, arguments[0]));
2000 value = [NSNull null];
2001 return CYCastJSValue(context, [value cy$box]);
2004 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2005 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2008 id self(internal->GetValue());
2009 const char *name(CYPoolCString(pool, context, property));
2011 if (object_getInstanceVariable(self, name, NULL) != NULL)
2017 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2018 length = CYCastDouble(encoding + 1);
2022 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2023 for (size_t i(0); i != size; ++i)
2024 if (ivars[i] == ivar)
2026 else if (ivar_getOffset(ivars[i]) == offset) {
2027 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2028 _assert(encoding != NULL);
2029 _assert(encoding[0] == 'b');
2030 shift += CYCastDouble(encoding + 1);
2035 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2036 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2039 id self(internal->GetValue());
2040 const char *name(CYPoolCString(pool, context, property));
2042 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2043 ptrdiff_t offset(ivar_getOffset(ivar));
2044 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2046 const char *encoding(ivar_getTypeEncoding(ivar));
2047 _assert(encoding != NULL);
2048 _assert(encoding[0] != '\0');
2049 if (encoding[0] == 'b') {
2050 unsigned length, shift;
2051 CYBitField(length, shift, self, ivar, encoding, offset);
2052 _assert(shift + length <= sizeof(uintptr_t) * 8);
2053 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2054 uintptr_t mask((1 << length) - 1);
2055 return CYCastJSValue(context, (field >> shift) & mask);
2057 #if defined(__APPLE__) && defined(__LP64__)
2058 // XXX: maybe do even more verifications here
2059 if (strcmp(name, "isa") == 0)
2060 return CYCastJSValue(context, object_getClass(self));
2063 auto type(new(pool) Type_privateData(encoding));
2064 return type->type_->FromFFI(context, type->GetFFI(), data);
2071 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2072 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2075 id self(internal->GetValue());
2076 const char *name(CYPoolCString(pool, context, property));
2078 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2079 ptrdiff_t offset(ivar_getOffset(ivar));
2080 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2082 const char *encoding(ivar_getTypeEncoding(ivar));
2083 _assert(encoding != NULL);
2084 if (encoding[0] == 'b') {
2085 unsigned length, shift;
2086 CYBitField(length, shift, self, ivar, encoding, offset);
2087 _assert(shift + length <= sizeof(uintptr_t) * 8);
2088 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2089 uintptr_t mask((1 << length) - 1);
2090 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2092 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2093 type->type_->PoolFFI(&pool, context, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2101 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2102 if (Class super = class_getSuperclass(_class))
2103 Internal_getPropertyNames_(super, names);
2106 objc_ivar **data(class_copyIvarList(_class, &size));
2107 for (size_t i(0); i != size; ++i)
2108 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2112 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2113 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2116 id self(internal->GetValue());
2117 Class _class(object_getClass(self));
2119 Internal_getPropertyNames_(_class, names);
2122 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2123 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2124 return internal->GetOwner();
2127 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2129 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2132 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2134 NSString *name(CYCastNSString(&pool, context, property));
2135 if (Class _class = NSClassFromString(name))
2136 return CYMakeInstance(context, _class, Instance::Permanent);
2140 static Class *CYCopyClassList(size_t &size) {
2141 size = objc_getClassList(NULL, 0);
2142 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2145 size_t writ(objc_getClassList(data, size));
2151 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2162 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2164 if (Class *data = CYCopyClassList(size)) {
2165 for (size_t i(0); i != size; ++i)
2166 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2172 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2173 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2176 const char *name(CYPoolCString(pool, context, property));
2178 const char **data(objc_copyClassNamesForImage(internal, &size));
2180 for (size_t i(0); i != size; ++i)
2181 if (strcmp(name, data[i]) == 0) {
2182 if (Class _class = objc_getClass(name)) {
2183 value = CYMakeInstance(context, _class, Instance::Permanent);
2194 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2195 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2197 const char **data(objc_copyClassNamesForImage(internal, &size));
2198 for (size_t i(0); i != size; ++i)
2199 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2203 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2205 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2208 const char **data(objc_copyImageNames(&size));
2209 pool.atexit(free, data);
2211 for (size_t i(0); i != size; ++i)
2212 if (name == data[i]) {
2213 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2214 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2221 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2223 const char **data(objc_copyImageNames(&size));
2224 for (size_t i(0); i != size; ++i)
2225 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2230 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2232 const char *name(CYPoolCString(pool, context, property));
2233 if (Protocol *protocol = objc_getProtocol(name))
2234 return CYMakeInstance(context, protocol, Instance::Permanent);
2238 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2240 Protocol **data(objc_copyProtocolList(&size));
2241 for (size_t i(0); i != size; ++i)
2242 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2246 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2248 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2250 return CYJSNull(context);
2254 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2255 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2259 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2260 *data = reinterpret_cast<void *>(address);
2261 return KERN_SUCCESS;
2265 std::set<Class> query_;
2266 JSContextRef context_;
2267 JSObjectRef results_;
2270 struct CYObjectStruct {
2274 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2275 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2276 JSContextRef context(choice->context_);
2278 for (unsigned i(0); i != count; ++i) {
2279 vm_range_t &range(ranges[i]);
2280 void *data(reinterpret_cast<void *>(range.address));
2281 size_t size(range.size);
2283 if (size < sizeof(CYObjectStruct))
2286 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2287 #if defined(__APPLE__) && defined(__LP64__)
2288 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2290 Class isa(reinterpret_cast<Class>(pointers[0]));
2293 std::set<Class>::const_iterator result(choice->query_.find(isa));
2294 if (result == choice->query_.end())
2297 size_t needed(class_getInstanceSize(*result));
2298 // XXX: if (size < needed)
2300 size_t boundary(496);
2304 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2306 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2310 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2312 throw CYJSError(context, "choose() takes a class argument");
2314 CYGarbageCollect(context);
2317 id _class(CYCastNSObject(&pool, context, arguments[0]));
2319 vm_address_t *zones(NULL);
2321 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2322 _assert(error == KERN_SUCCESS);
2324 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2325 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2328 choice.context_ = context;
2329 choice.results_ = results;
2332 Class *classes(CYCopyClassList(number));
2333 _assert(classes != NULL);
2335 for (size_t i(0); i != number; ++i)
2336 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2337 if (current == _class) {
2338 choice.query_.insert(classes[i]);
2344 for (unsigned i(0); i != size; ++i) {
2345 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2346 if (zone == NULL || zone->introspect == NULL)
2349 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2357 #if defined(__i386__) || defined(__x86_64__)
2358 #define OBJC_MAX_STRUCT_BY_VALUE 8
2359 static int struct_forward_array[] = {
2360 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2361 #elif defined(__arm__)
2362 #define OBJC_MAX_STRUCT_BY_VALUE 1
2363 static int struct_forward_array[] = {
2365 #elif defined(__arm64__)
2368 #error missing objc-runtime-info
2372 static bool stret(ffi_type *ffi_type) {
2373 return ffi_type->type == FFI_TYPE_STRUCT && (
2374 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2375 struct_forward_array[ffi_type->size] != 0
2383 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2387 _class = object_getClass(self);
2391 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2392 imp = method_getImplementation(method);
2393 type = method_getTypeEncoding(method);
2398 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2399 type = CYPoolCString(pool, context, [method _typeString]);
2405 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2412 sig::Signature signature;
2413 sig::Parse(pool, &signature, type, &Structor_);
2416 sig::sig_ffi_cif(pool, 0, signature, &cif);
2420 if (stret(cif.rtype))
2421 imp = class_getMethodImplementation_stret(_class, _cmd);
2424 imp = class_getMethodImplementation(_class, _cmd);
2427 void (*function)() = reinterpret_cast<void (*)()>(imp);
2428 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, true, signature, &cif, function);
2431 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2433 throw CYJSError(context, "too few arguments to objc_msgSend");
2443 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2444 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2445 self = internal->GetValue();
2446 _class = internal->class_;;
2447 uninitialized = false;
2448 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2449 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2450 self = internal->GetValue();
2452 uninitialized = internal->IsUninitialized();
2454 internal->value_ = nil;
2456 self = CYCastNSObject(&pool, context, arguments[0]);
2458 uninitialized = false;
2462 return CYJSNull(context);
2464 _cmd = CYCastSEL(context, arguments[1]);
2466 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2469 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2470 return $objc_msgSend(context, object, _this, count, arguments);
2473 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2474 JSValueRef setup[count + 2];
2477 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2478 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2481 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2483 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2485 // XXX: handle Instance::Uninitialized?
2486 id self(CYCastNSObject(&pool, context, _this));
2490 setup[1] = &internal->sel_;
2492 return CYCallFunction(pool, context, 2, setup, count, arguments, false, true, internal->signature_, &internal->cif_, internal->GetValue());
2495 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2497 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2499 id self(CYCastNSObject(&pool, context, arguments[0]));
2500 Class _class(CYCastClass(pool, context, arguments[1]));
2501 return cy::Super::Make(context, self, _class);
2504 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2506 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2508 const char *name(CYPoolCString(pool, context, arguments[0]));
2509 return CYMakeSelector(context, sel_registerName(name));
2512 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2514 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2515 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2518 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2519 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2520 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2523 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2524 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2525 Type_privateData *typical(internal->GetType());
2532 if (typical == NULL) {
2536 type = typical->type_;
2537 ffi = typical->ffi_;
2540 return CYMakePointer(context, &internal->value_, *type, ffi, object);
2543 static JSValueRef Selector_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2544 return CYMakeType(context, sig::Selector());
2547 static JSValueRef Instance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2548 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2549 id self(internal->GetValue());
2550 if (CYIsClass(self))
2551 return CYMakeType(context, sig::Meta());
2552 return CYMakeType(context, sig::Object(class_getName(object_getClass(self))));
2555 static JSValueRef FunctionInstance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2556 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2559 if (!CYBlockSignature(pool, internal->GetValue(), type.signature))
2560 return CYJSNull(context);
2561 return CYMakeType(context, type);
2564 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2565 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2566 return CYMakeInstance(context, object_getClass(internal->GetValue()), Instance::Permanent);
2569 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2570 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2571 id self(internal->GetValue());
2572 if (!CYIsClass(self))
2573 return CYJSUndefined(context);
2574 return CYGetClassPrototype(context, self);
2577 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2578 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2579 id self(internal->GetValue());
2580 if (!CYIsClass(self))
2581 return CYJSUndefined(context);
2582 return Messages::Make(context, (Class) self);
2585 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2586 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2588 if (!CYJSValueIsNSObject(context, _this))
2591 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2592 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2595 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2596 if (!CYJSValueIsNSObject(context, _this))
2599 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2600 id value(internal->GetValue());
2607 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2609 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2610 return CYJSUndefined(context);
2611 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2614 return CYCastJSValue(context, CYJSString(context, [value description]));
2616 } CYCatch(NULL) return /*XXX*/ NULL; }
2618 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2619 if (!CYJSValueIsNSObject(context, _this))
2622 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2623 id value(internal->GetValue());
2624 _assert(value != nil);
2626 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2629 if (JSValueRef result = [value cy$valueOfInContext:context])
2633 } CYCatch(NULL) return /*XXX*/ NULL; }
2635 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2636 if (!CYJSValueIsNSObject(context, _this))
2639 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2640 // XXX: but... but... THIS ISN'T A POINTER! :(
2641 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2642 } CYCatch(NULL) return /*XXX*/ NULL; }
2644 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2645 if (!CYJSValueIsNSObject(context, _this))
2648 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2649 id value(internal->GetValue());
2652 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2653 return CYCastJSValue(context, CYJSString(context, [value description]));
2655 } CYCatch(NULL) return /*XXX*/ NULL; }
2657 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2658 if (!CYJSValueIsNSObject(context, _this))
2661 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2662 id value(internal->GetValue());
2664 if (!CYIsClass(value))
2665 CYThrow("non-Class object cannot be used as Type");
2667 sig::Object type(class_getName(value));
2668 return CYMakeType(context, type);
2669 } CYCatch(NULL) return /*XXX*/ NULL; }
2671 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2672 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2673 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2676 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2677 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2680 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2681 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2682 const char *name(sel_getName(internal->GetValue()));
2685 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2686 return CYCastJSValue(context, CYJSString(context, string));
2688 } CYCatch(NULL) return /*XXX*/ NULL; }
2690 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2692 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2695 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2696 SEL sel(internal->GetValue());
2698 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2699 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2700 const char *encoding(method_getTypeEncoding(method));
2702 sig::Function type(false);
2703 sig::Parse(pool, &type.signature, encoding, &Structor_);
2704 return CYMakeType(context, type);
2707 static JSStaticValue Selector_staticValues[3] = {
2708 {"$cyt", &Selector_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2709 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2710 {NULL, NULL, NULL, 0}
2713 static JSStaticValue Instance_staticValues[6] = {
2714 {"$cyt", &Instance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2715 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2716 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2717 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2718 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2719 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2720 {NULL, NULL, NULL, 0}
2723 static JSStaticValue FunctionInstance_staticValues[6] = {
2724 {"$cyt", &FunctionInstance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2725 // XXX: this is sadly a duplicate of Instance_staticValues
2726 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2727 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2728 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2729 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2730 {NULL, NULL, NULL, 0}
2733 static JSStaticFunction Instance_staticFunctions[7] = {
2734 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2735 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2736 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2737 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2738 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2739 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2743 static JSStaticFunction Class_staticFunctions[2] = {
2744 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2748 static JSStaticFunction Internal_staticFunctions[2] = {
2749 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2753 static JSStaticFunction Selector_staticFunctions[5] = {
2754 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2755 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2756 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2757 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2762 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2763 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2764 } CYObjectiveCatch }
2767 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2768 CYPool &pool(CYGetGlobalPool());
2770 Object_type = new(pool) Type_privateData(sig::Object());
2771 Selector_type = new(pool) Type_privateData(sig::Selector());
2773 NSArray_ = objc_getClass("NSArray");
2774 NSBlock_ = objc_getClass("NSBlock");
2775 NSDictionary_ = objc_getClass("NSDictionary");
2776 NSNumber_ = objc_getClass("NSNumber");
2777 NSString_ = objc_getClass("NSString");
2778 Object_ = objc_getClass("Object");
2781 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2783 // XXX: apparently, iOS now has both of these
2784 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2785 if (NSCFBoolean_ == nil)
2786 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2788 NSCFType_ = objc_getClass("NSCFType");
2790 NSZombie_ = objc_getClass("_NSZombie_");
2792 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2793 NSZombie_ = objc_getClass("NSZombie");
2796 JSClassDefinition definition;
2798 definition = kJSClassDefinitionEmpty;
2799 definition.className = "Instance";
2800 definition.staticValues = Instance_staticValues;
2801 definition.staticFunctions = Instance_staticFunctions;
2802 definition.hasProperty = &Instance_hasProperty;
2803 definition.getProperty = &Instance_getProperty;
2804 definition.setProperty = &Instance_setProperty;
2805 definition.deleteProperty = &Instance_deleteProperty;
2806 definition.getPropertyNames = &Instance_getPropertyNames;
2807 definition.callAsConstructor = &Instance_callAsConstructor;
2808 definition.hasInstance = &Instance_hasInstance;
2809 definition.finalize = &CYFinalize;
2810 Instance_ = JSClassCreate(&definition);
2812 definition.className = "ArrayInstance";
2813 ArrayInstance_ = JSClassCreate(&definition);
2815 definition.className = "BooleanInstance";
2816 BooleanInstance_ = JSClassCreate(&definition);
2818 definition.className = "NumberInstance";
2819 NumberInstance_ = JSClassCreate(&definition);
2821 definition.className = "ObjectInstance";
2822 ObjectInstance_ = JSClassCreate(&definition);
2824 definition.className = "StringInstance";
2825 StringInstance_ = JSClassCreate(&definition);
2827 definition.className = "FunctionInstance";
2828 definition.staticValues = FunctionInstance_staticValues;
2829 definition.callAsFunction = &FunctionInstance_callAsFunction;
2830 FunctionInstance_ = JSClassCreate(&definition);
2832 definition = kJSClassDefinitionEmpty;
2833 definition.className = "Class";
2834 definition.staticFunctions = Class_staticFunctions;
2835 Class_ = JSClassCreate(&definition);
2837 definition = kJSClassDefinitionEmpty;
2838 definition.className = "Internal";
2839 definition.staticFunctions = Internal_staticFunctions;
2840 definition.hasProperty = &Internal_hasProperty;
2841 definition.getProperty = &Internal_getProperty;
2842 definition.setProperty = &Internal_setProperty;
2843 definition.getPropertyNames = &Internal_getPropertyNames;
2844 definition.finalize = &CYFinalize;
2845 Internal_ = JSClassCreate(&definition);
2847 definition = kJSClassDefinitionEmpty;
2848 definition.className = "Message";
2849 definition.staticFunctions = cy::Functor::StaticFunctions;
2850 definition.staticValues = cy::Functor::StaticValues;
2851 definition.callAsFunction = &Message_callAsFunction;
2852 definition.finalize = &CYFinalize;
2853 Message_ = JSClassCreate(&definition);
2855 definition = kJSClassDefinitionEmpty;
2856 definition.className = "Messages";
2857 definition.hasProperty = &Messages_hasProperty;
2858 definition.getProperty = &Messages_getProperty;
2859 definition.setProperty = &Messages_setProperty;
2860 definition.getPropertyNames = &Messages_getPropertyNames;
2861 definition.finalize = &CYFinalize;
2862 Messages_ = JSClassCreate(&definition);
2864 definition = kJSClassDefinitionEmpty;
2865 definition.className = "Selector";
2866 definition.staticValues = Selector_staticValues;
2867 definition.staticFunctions = Selector_staticFunctions;
2868 definition.callAsFunction = &Selector_callAsFunction;
2869 definition.finalize = &CYFinalize;
2870 Selector_ = JSClassCreate(&definition);
2872 definition = kJSClassDefinitionEmpty;
2873 definition.className = "Super";
2874 definition.staticFunctions = Internal_staticFunctions;
2875 definition.finalize = &CYFinalize;
2876 Super_ = JSClassCreate(&definition);
2878 definition = kJSClassDefinitionEmpty;
2879 definition.className = "ObjectiveC::Classes";
2880 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2881 definition.getProperty = &ObjectiveC_Classes_getProperty;
2882 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2883 ObjectiveC_Classes_ = JSClassCreate(&definition);
2885 definition = kJSClassDefinitionEmpty;
2886 definition.className = "ObjectiveC::Constants";
2887 definition.getProperty = &ObjectiveC_Constants_getProperty;
2888 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2889 ObjectiveC_Constants_ = JSClassCreate(&definition);
2892 definition = kJSClassDefinitionEmpty;
2893 definition.className = "ObjectiveC::Images";
2894 definition.getProperty = &ObjectiveC_Images_getProperty;
2895 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2896 ObjectiveC_Images_ = JSClassCreate(&definition);
2898 definition = kJSClassDefinitionEmpty;
2899 definition.className = "ObjectiveC::Image::Classes";
2900 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2901 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2902 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2905 definition = kJSClassDefinitionEmpty;
2906 definition.className = "ObjectiveC::Protocols";
2907 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2908 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2909 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2912 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2913 // XXX: this is horrible; there has to be a better way to do this
2915 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2917 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2923 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2924 JSObjectRef global(CYGetGlobalObject(context));
2925 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2926 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2927 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2928 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2930 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2931 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2933 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2934 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2935 CYArrayPush(context, alls, protocols);
2937 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2938 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2939 CYArrayPush(context, alls, classes);
2941 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2942 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2943 CYArrayPush(context, alls, constants);
2946 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2949 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2950 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2951 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2952 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2953 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2955 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2956 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2958 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2959 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2960 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2961 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2962 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2964 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2965 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2966 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2967 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2968 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2970 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2971 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2972 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2973 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2974 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2976 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2977 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2978 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2979 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2980 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2982 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2983 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2984 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2985 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2986 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2988 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2989 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2990 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2991 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2992 CYSetPrototype(context, StringInstance_prototype, String_prototype);
2994 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2995 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2996 CYSetPrototype(context, Class_prototype, Instance_prototype);
2998 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2999 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3000 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3002 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3003 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3006 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3009 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3011 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3012 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3014 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
3015 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
3016 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
3017 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::Object()), kJSPropertyAttributeDontEnum);
3018 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::Meta()), kJSPropertyAttributeDontEnum);
3019 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::Selector()), kJSPropertyAttributeDontEnum);
3022 static void *CYObjectiveC_CastSymbol(const char *name) {
3024 #ifdef __GNU_LIBOBJC__
3025 else if (strcmp(name, "object_getClass") == 0)
3026 return reinterpret_cast<void *>(&object_getClass);
3031 static CYHook CYObjectiveCHook = {
3032 &CYObjectiveC_ExecuteStart,
3033 &CYObjectiveC_ExecuteEnd,
3034 &CYObjectiveC_CallFunction,
3035 &CYObjectiveC_Initialize,
3036 &CYObjectiveC_SetupContext,
3037 &CYObjectiveC_CastSymbol,
3040 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3042 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3043 CYSetupContext(context);
3044 } CYObjectiveCatch }
3046 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3049 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3050 utf8 = CYPoolCode(pool, utf8);
3052 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3053 size_t bytes(utf16.size * sizeof(uint16_t));
3054 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3055 memcpy(copy, utf16.data, bytes);
3059 } catch (const CYException &exception) {
3061 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];