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(type, reinterpret_cast<void (*)()>(value)),
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 sig::Signature *CYBlockSignature(CYPool &pool, NSBlock *self);
853 @implementation NSBlock (Cycript)
855 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
858 sig::Signature *signature(CYBlockSignature(pool, self));
859 // XXX: I am checking signature->count due to Decode doing it for block_P
860 if (signature == NULL || signature->count == 0)
861 return [super cy$toCYON:objective inSet:objects];
862 _oassert(objects.insert(self).second);
865 sig::Copy(pool, type.signature, *signature);
867 CYTypedIdentifier *typed((new(pool) CYTypeExpression(CYDecodeType(pool, &type)))->typed_);
868 CYTypeFunctionWith *function(typed->Function());
869 _assert(function != NULL);
871 _assert(function->parameters_ != NULL);
872 CYObjCBlock *block(new(pool) CYObjCBlock(typed, function->parameters_, NULL));
874 std::ostringstream str;
876 CYOutput out(*str.rdbuf(), options);
877 block->Output(out, CYNoFlags);
879 std::string value(str.str());
880 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
886 /* Bridge: NSBoolNumber {{{ */
888 @implementation NSBoolNumber (Cycript)
890 - (JSType) cy$JSType {
891 return kJSTypeBoolean;
894 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
895 NSString *value([self boolValue] ? @"true" : @"false");
896 return objective ? value : [NSString stringWithFormat:@"@%@", value];
899 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
900 return CYCastJSValue(context, (bool) [self boolValue]);
906 /* Bridge: NSDictionary {{{ */
907 @implementation NSDictionary (Cycript)
910 return [[self mutableCopy] autorelease];
913 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
914 _oassert(objects.insert(self).second);
916 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
917 [json appendString:@"@{"];
921 for (NSObject *key in self) {
923 NSEnumerator *keys([self keyEnumerator]);
924 while (NSObject *key = [keys nextObject]) {
927 [json appendString:@","];
930 [json appendString:CYCastNSCYON(key, true, objects)];
931 [json appendString:@":"];
932 NSObject *object([self objectForKey:key]);
933 [json appendString:CYCastNSCYON(object, true, objects)];
936 [json appendString:@"}"];
940 - (bool) cy$hasProperty:(NSString *)name {
941 return [self objectForKey:name] != nil;
944 - (NSObject *) cy$getProperty:(NSString *)name {
945 return [self objectForKey:name];
948 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
949 [super cy$getPropertyNames:names inContext:context];
952 for (NSObject *key in self) {
954 NSEnumerator *keys([self keyEnumerator]);
955 while (NSObject *key = [keys nextObject]) {
957 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
961 + (bool) cy$hasImplicitProperties {
967 /* Bridge: NSMutableArray {{{ */
968 @implementation NSMutableArray (Cycript)
970 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
971 if ([name isEqualToString:@"length"]) {
972 // XXX: is this not intelligent?
973 NSNumber *number(reinterpret_cast<NSNumber *>(value));
974 NSUInteger size([number unsignedIntegerValue]);
975 NSUInteger count([self count]);
977 [self removeObjectsInRange:NSMakeRange(size, count - size)];
978 else if (size != count) {
979 WebUndefined *undefined([WebUndefined undefined]);
980 for (size_t i(count); i != size; ++i)
981 [self addObject:undefined];
986 size_t index(CYGetIndex(name));
987 if (index == _not(size_t))
988 return [super cy$setProperty:name to:value];
990 id object(value ?: [NSNull null]);
992 size_t count([self count]);
994 [self replaceObjectAtIndex:index withObject:object];
996 if (index != count) {
997 WebUndefined *undefined([WebUndefined undefined]);
998 for (size_t i(count); i != index; ++i)
999 [self addObject:undefined];
1002 [self addObject:object];
1008 - (bool) cy$deleteProperty:(NSString *)name {
1009 size_t index(CYGetIndex(name));
1010 if (index == _not(size_t) || index >= [self count])
1011 return [super cy$deleteProperty:name];
1012 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1018 /* Bridge: NSMutableDictionary {{{ */
1019 @implementation NSMutableDictionary (Cycript)
1021 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1022 [self setObject:(value ?: [NSNull null]) forKey:name];
1026 - (bool) cy$deleteProperty:(NSString *)name {
1027 if ([self objectForKey:name] == nil)
1030 [self removeObjectForKey:name];
1037 /* Bridge: NSNumber {{{ */
1038 @implementation NSNumber (Cycript)
1040 - (JSType) cy$JSType {
1042 // XXX: this just seems stupid
1043 if ([self class] == NSCFBoolean_)
1044 return kJSTypeBoolean;
1046 return kJSTypeNumber;
1049 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1050 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1051 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1054 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1055 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1056 } CYObjectiveCatch }
1060 /* Bridge: NSNull {{{ */
1061 @implementation NSNull (Cycript)
1063 - (JSType) cy$JSType {
1067 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1068 NSString *value(@"null");
1069 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1072 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1073 return CYJSNull(context);
1074 } CYObjectiveCatch }
1078 /* Bridge: NSObject {{{ */
1079 @implementation NSObject (Cycript)
1085 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1086 return [self cy$valueOfInContext:context];
1089 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1091 } CYObjectiveCatch }
1093 - (JSType) cy$JSType {
1094 return kJSTypeObject;
1097 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1098 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1101 - (bool) cy$hasProperty:(NSString *)name {
1105 - (NSObject *) cy$getProperty:(NSString *)name {
1109 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1110 if (NSObject *value = [self cy$getProperty:name])
1111 return CYCastJSValue(context, value);
1113 } CYObjectiveCatch }
1115 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1119 - (bool) cy$deleteProperty:(NSString *)name {
1123 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1126 + (bool) cy$hasImplicitProperties {
1132 /* Bridge: NSOrderedSet {{{ */
1134 @implementation NSOrderedSet (Cycript)
1136 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1137 _oassert(objects.insert(self).second);
1139 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1140 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1141 [json appendString:CYCastNSCYON([self array], true, objects)];
1142 [json appendString:@"]]"];
1149 /* Bridge: NSProxy {{{ */
1150 @implementation NSProxy (Cycript)
1152 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1153 return [[self description] cy$toCYON:objective inSet:objects];
1158 /* Bridge: NSSet {{{ */
1159 @implementation NSSet (Cycript)
1161 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1162 _oassert(objects.insert(self).second);
1164 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1165 [json appendString:@"[NSSet setWithArray:"];
1166 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1167 [json appendString:@"]]"];
1173 /* Bridge: NSString {{{ */
1174 @implementation NSString (Cycript)
1177 return [[self copy] autorelease];
1180 - (JSType) cy$JSType {
1181 return kJSTypeString;
1184 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1185 std::ostringstream str;
1188 CYUTF8String string(CYCastUTF8String(self));
1189 CYStringify(str, string.data, string.size, true);
1190 std::string value(str.str());
1191 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1194 - (bool) cy$hasProperty:(NSString *)name {
1195 size_t index(CYGetIndex(name));
1196 if (index == _not(size_t) || index >= [self length])
1197 return [super cy$hasProperty:name];
1202 - (NSObject *) cy$getProperty:(NSString *)name {
1203 size_t index(CYGetIndex(name));
1204 if (index == _not(size_t) || index >= [self length])
1205 return [super cy$getProperty:name];
1207 return [self substringWithRange:NSMakeRange(index, 1)];
1210 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1211 [super cy$getPropertyNames:names inContext:context];
1213 for (size_t index(0), length([self length]); index != length; ++index) {
1215 sprintf(name, "%zu", index);
1216 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1220 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1221 return CYCastJSValue(context, CYJSString(context, self));
1222 } CYObjectiveCatch }
1226 /* Bridge: WebUndefined {{{ */
1227 @implementation WebUndefined (Cycript)
1229 - (JSType) cy$JSType {
1230 return kJSTypeUndefined;
1233 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1234 NSString *value(@"undefined");
1235 return value; // XXX: maybe use the below code, adding @undefined?
1236 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1239 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1240 return CYJSUndefined(context);
1241 } CYObjectiveCatch }
1246 static bool CYIsClass(id self) {
1247 return class_isMetaClass(object_getClass(self));
1250 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1251 id self(CYCastNSObject(&pool, context, value));
1252 if (CYIsClass(self))
1253 return (Class) self;
1254 throw CYJSError(context, "got something that is not a Class");
1258 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1260 size_t size(JSPropertyNameArrayGetCount(names));
1261 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1262 for (size_t index(0); index != size; ++index)
1263 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1267 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) {
1269 return CYJSNull(context);
1270 return CYMakeInstance(context, value);
1273 @implementation CYJSObject
1275 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1276 if ((self = [super init]) != nil) {
1278 context_ = CYGetJSContext(context);
1279 JSGlobalContextRetain(context_);
1280 JSValueProtect(context_, object_);
1282 } CYObjectiveCatch }
1284 - (void) dealloc { CYObjectiveTry {
1285 JSValueUnprotect(context_, object_);
1286 JSGlobalContextRelease(context_);
1288 } CYObjectiveCatch }
1290 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1292 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1294 return [super cy$toCYON:objective inSet:objects];
1296 return [NSString stringWithUTF8String:cyon];
1297 } CYObjectiveCatch }
1299 - (NSUInteger) count { CYObjectiveTry {
1300 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1301 size_t size(JSPropertyNameArrayGetCount(names));
1302 JSPropertyNameArrayRelease(names);
1304 } CYObjectiveCatch }
1306 - (id) objectForKey:(id)key { CYObjectiveTry {
1307 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1308 if (JSValueIsUndefined(context, value))
1310 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1311 } CYObjectiveCatch }
1313 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1314 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1315 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1316 JSPropertyNameArrayRelease(names);
1318 } CYObjectiveCatch }
1320 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1321 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1322 } CYObjectiveCatch }
1324 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1325 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1326 } CYObjectiveCatch }
1330 @implementation CYJSArray
1332 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1334 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1335 } CYObjectiveCatch }
1337 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1338 if ((self = [super init]) != nil) {
1340 context_ = CYGetJSContext(context);
1341 JSGlobalContextRetain(context_);
1342 JSValueProtect(context_, object_);
1344 } CYObjectiveCatch }
1346 - (void) dealloc { CYObjectiveTry {
1347 JSValueUnprotect(context_, object_);
1348 JSGlobalContextRelease(context_);
1350 } CYObjectiveCatch }
1352 - (NSUInteger) count { CYObjectiveTry {
1353 return CYArrayLength(context, object_);
1354 } CYObjectiveCatch }
1356 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1357 size_t bounds([self count]);
1358 if (index >= bounds)
1359 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1360 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1361 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1362 } CYObjectiveCatch }
1364 - (void) addObject:(id)object { CYObjectiveTry {
1365 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1366 } CYObjectiveCatch }
1368 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1369 size_t bounds([self count] + 1);
1370 if (index >= bounds)
1371 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1372 JSValueRef arguments[3];
1373 arguments[0] = CYCastJSValue(context, index);
1374 arguments[1] = CYCastJSValue(context, 0);
1375 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1376 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1377 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1378 } CYObjectiveCatch }
1380 - (void) removeLastObject { CYObjectiveTry {
1381 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1382 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1383 } CYObjectiveCatch }
1385 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1386 size_t bounds([self count]);
1387 if (index >= bounds)
1388 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1389 JSValueRef arguments[2];
1390 arguments[0] = CYCastJSValue(context, index);
1391 arguments[1] = CYCastJSValue(context, 1);
1392 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1393 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1394 } CYObjectiveCatch }
1396 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1397 size_t bounds([self count]);
1398 if (index >= bounds)
1399 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1400 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1401 } CYObjectiveCatch }
1405 // XXX: inherit from or replace with CYJSObject
1406 @interface CYInternal : NSObject {
1407 JSGlobalContextRef context_;
1408 JSObjectRef object_;
1413 @implementation CYInternal
1415 - (void) dealloc { CYObjectiveTry {
1416 JSValueUnprotect(context_, object_);
1417 JSGlobalContextRelease(context_);
1419 } CYObjectiveCatch }
1421 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1422 if ((self = [super init]) != nil) {
1423 context_ = CYGetJSContext(context);
1424 JSGlobalContextRetain(context_);
1426 } CYObjectiveCatch }
1428 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1429 if (object_ == NULL)
1432 return JSObjectHasProperty(context, object_, name);
1435 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1436 if (object_ == NULL)
1439 return CYGetProperty(context, object_, name);
1442 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1443 @synchronized (self) {
1444 if (object_ == NULL) {
1445 object_ = JSObjectMake(context, NULL, NULL);
1446 JSValueProtect(context, object_);
1450 CYSetProperty(context, object_, name, value);
1453 + (CYInternal *) get:(id)object {
1455 if (&objc_getAssociatedObject == NULL)
1458 @synchronized (object) {
1459 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1467 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1469 if (&objc_getAssociatedObject == NULL)
1472 @synchronized (object) {
1473 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1476 if (&objc_setAssociatedObject == NULL)
1479 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1480 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1490 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1491 Selector_privateData *internal(new Selector_privateData(sel));
1492 return JSObjectMake(context, Selector_, internal);
1495 static JSValueRef CYCastJSValue(JSContextRef context, SEL sel) {
1497 return CYJSNull(context);
1498 return CYMakeSelector(context, sel);
1501 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1502 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1503 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1504 return reinterpret_cast<SEL>(internal->value_);
1507 return sel_registerName(CYPoolCString(pool, context, value));
1511 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1512 return (void *) [[NSAutoreleasePool alloc] init];
1513 } CYSadCatch(NULL) }
1515 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1516 return [(NSAutoreleasePool *) handle release];
1519 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1520 CYCallFunction(pool, context, cif, function, value, values);
1523 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, const sig::Signature *signature) {
1525 if (JSValueIsNull(context, value))
1527 JSObjectRef object(CYCastJSObject(context, value));
1529 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1530 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1532 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1533 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1537 _assert(JSObjectIsFunction(context, object));
1539 _assert(signature != NULL);
1540 _assert(signature->count != 0);
1542 sig::Signature modified;
1543 modified.count = signature->count + 1;
1544 modified.elements = new(pool) sig::Element[modified.count];
1546 modified.elements[0] = signature->elements[0];
1547 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1549 modified.elements[1].name = NULL;
1550 modified.elements[1].type = new(pool) sig::Object();
1551 modified.elements[1].offset = _not(size_t);
1553 return CYMakeBlock(context, object, modified);
1561 void Block::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1562 // XXX: this function might not handle the idea of a null pool
1563 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &signature);
1566 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1567 void Object::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1568 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1571 void Meta::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1572 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1575 void Selector::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
1576 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1579 JSValueRef Object::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1580 NSObject *value(*reinterpret_cast<NSObject **>(data));
1582 return CYJSNull(context);
1583 JSObjectRef object(CYMakeInstance(context, value));
1586 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1588 if ((internal->flags_ & Instance::Uninitialized) != 0) {
1589 internal->flags_ = static_cast<Instance::Flags>(internal->flags_ & ~Instance::Uninitialized);
1590 _assert(internal->value_ == nil);
1591 internal->value_ = value;
1600 JSValueRef Meta::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1601 if (Class value = *reinterpret_cast<Class *>(data))
1602 return CYMakeInstance(context, value, Instance::Permanent);
1603 return CYJSNull(context);
1606 JSValueRef Selector::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1607 return CYCastJSValue(context, *reinterpret_cast<SEL *>(data));
1610 JSValueRef Block::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
1611 return CYCastJSValue(context, *reinterpret_cast<NSObject **>(data));
1616 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1617 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1621 method_getReturnType(method, type, sizeof(type));
1626 // XXX: possibly use a more "awesome" check?
1630 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1631 JSObjectRef _this(CYCastJSObject(context, values[0]));
1632 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1635 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1636 Message_privateData *internal(new Message_privateData(sel, type, imp));
1637 return JSObjectMake(context, Message_, internal);
1640 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1641 JSObjectRef function(CYCastJSObject(context, value));
1643 sig::Signature signature;
1644 sig::Parse(pool, &signature, encoding, &Structor_);
1645 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1646 // XXX: see notes in Library.cpp about needing to leak
1647 return reinterpret_cast<IMP>(internal->GetValue());
1650 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1651 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1652 Class _class(internal->GetValue());
1655 const char *name(CYPoolCString(pool, context, property));
1657 if (SEL sel = sel_getUid(name))
1658 if (class_getInstanceMethod(_class, sel) != NULL)
1664 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1665 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1666 Class _class(internal->GetValue());
1669 const char *name(CYPoolCString(pool, context, property));
1671 if (SEL sel = sel_getUid(name))
1672 if (objc_method *method = class_getInstanceMethod(_class, sel))
1673 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1678 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1679 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1680 Class _class(internal->GetValue());
1683 const char *name(CYPoolCString(pool, context, property));
1684 SEL sel(sel_registerName(name));
1689 if (JSValueIsObjectOfClass(context, value, Message_)) {
1690 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1691 type = sig::Unparse(pool, &message->signature_);
1692 imp = reinterpret_cast<IMP>(message->GetValue());
1693 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1694 type = method_getTypeEncoding(method);
1695 imp = CYMakeMessage(context, value, type);
1696 } else _assert(false);
1698 objc_method *method(NULL);
1700 objc_method **methods(class_copyMethodList(_class, &size));
1701 for (size_t i(0); i != size; ++i)
1702 if (sel_isEqual(method_getName(methods[i]), sel)) {
1703 method = methods[i];
1709 method_setImplementation(method, imp);
1711 class_addMethod(_class, sel, imp, type);
1716 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1717 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1718 Class _class(internal->GetValue());
1721 objc_method **data(class_copyMethodList(_class, &size));
1722 for (size_t i(0); i != size; ++i)
1723 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1727 static bool CYHasImplicitProperties(Class _class) {
1728 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1729 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1731 return [_class cy$hasImplicitProperties];
1734 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1735 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1736 id self(internal->GetValue());
1738 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1742 NSString *name(CYCastNSString(&pool, context, property));
1744 if (CYInternal *internal = [CYInternal get:self])
1745 if ([internal hasProperty:property inContext:context])
1748 Class _class(object_getClass(self));
1751 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1752 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1753 if ([self cy$hasProperty:name])
1755 } CYPoolCatch(false)
1757 const char *string(CYPoolCString(pool, context, name));
1759 if (class_getProperty(_class, string) != NULL)
1762 if (CYHasImplicitProperties(_class))
1763 if (SEL sel = sel_getUid(string))
1764 if (CYImplements(self, _class, sel, true))
1770 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1771 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1772 id self(internal->GetValue());
1774 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1775 return Internal::Make(context, self, object);
1778 NSString *name(CYCastNSString(&pool, context, property));
1780 if (CYInternal *internal = [CYInternal get:self])
1781 if (JSValueRef value = [internal getProperty:property inContext:context])
1785 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1789 const char *string(CYPoolCString(pool, context, name));
1790 Class _class(object_getClass(self));
1792 if (objc_property_t property = class_getProperty(_class, string)) {
1793 PropertyAttributes attributes(property);
1794 SEL sel(sel_registerName(attributes.Getter()));
1795 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1798 if (CYHasImplicitProperties(_class))
1799 if (SEL sel = sel_getUid(string))
1800 if (CYImplements(self, _class, sel, true))
1801 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1806 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1807 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1808 id self(internal->GetValue());
1812 NSString *name(CYCastNSString(&pool, context, property));
1813 NSObject *data(CYCastNSObject(&pool, context, value));
1816 if ([self cy$setProperty:name to:data])
1818 } CYPoolCatch(false)
1820 const char *string(CYPoolCString(pool, context, name));
1821 Class _class(object_getClass(self));
1823 if (objc_property_t property = class_getProperty(_class, string)) {
1824 PropertyAttributes attributes(property);
1825 if (const char *setter = attributes.Setter()) {
1826 SEL sel(sel_registerName(setter));
1827 JSValueRef arguments[1] = {value};
1828 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1833 size_t length(strlen(string));
1835 char set[length + 5];
1841 if (string[0] != '\0') {
1842 set[3] = toupper(string[0]);
1843 memcpy(set + 4, string + 1, length - 1);
1846 set[length + 3] = ':';
1847 set[length + 4] = '\0';
1849 if (SEL sel = sel_getUid(set))
1850 if (CYImplements(self, _class, sel)) {
1851 JSValueRef arguments[1] = {value};
1852 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1856 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1857 [internal setProperty:property toValue:value inContext:context];
1864 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1865 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1866 id self(internal->GetValue());
1869 NSString *name(CYCastNSString(NULL, context, property));
1870 return [self cy$deleteProperty:name];
1871 } CYPoolCatch(false)
1872 } CYCatch(false) return /*XXX*/ false; }
1874 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1875 const char *name(sel_getName(method_getName(method)));
1876 if (strchr(name, ':') != NULL)
1879 const char *type(method_getTypeEncoding(method));
1880 if (type == NULL || *type == '\0' || *type == 'v')
1883 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1886 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1887 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1888 id self(internal->GetValue());
1891 Class _class(object_getClass(self));
1895 objc_property_t *data(class_copyPropertyList(_class, &size));
1896 for (size_t i(0); i != size; ++i)
1897 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1901 if (CYHasImplicitProperties(_class))
1902 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1904 objc_method **data(class_copyMethodList(current, &size));
1905 for (size_t i(0); i != size; ++i)
1906 Instance_getPropertyNames_message(names, data[i]);
1911 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1912 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1913 [self cy$getPropertyNames:names inContext:context];
1917 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1918 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1919 JSObjectRef value(CYMakeInstance(context, [internal->GetValue() alloc], Instance::Uninitialized));
1923 static const char *CYBlockEncoding(NSBlock *self) {
1924 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1925 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1927 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1928 descriptor += sizeof(BlockDescriptor1);
1929 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1930 descriptor += sizeof(BlockDescriptor2);
1931 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1932 return descriptor3->signature;
1935 static sig::Signature *CYBlockSignature(CYPool &pool, NSBlock *self) {
1936 const char *encoding(CYBlockEncoding(self));
1937 if (encoding == NULL)
1939 // XXX: this should be stored on a FunctionInstance private value subclass
1940 sig::Signature *signature(new(pool) sig::Signature());
1941 sig::Parse(pool, signature, encoding, &Structor_);
1945 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1946 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1947 id self(internal->GetValue());
1949 if (const char *encoding = CYBlockEncoding(self)) {
1955 sig::Signature signature;
1956 sig::Parse(pool, &signature, encoding, &Structor_);
1959 sig::sig_ffi_cif(pool, &signature, &cif);
1961 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1962 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1963 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1967 CYThrow("NSBlock without signature field passed arguments");
1971 } CYPoolCatch(NULL);
1976 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1977 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1978 Class _class(internal->GetValue());
1979 if (!CYIsClass(_class))
1982 if (CYJSValueIsNSObject(context, instance)) {
1983 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1984 // XXX: this isn't always safe
1985 return [linternal->GetValue() isKindOfClass:_class];
1991 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1993 throw CYJSError(context, "incorrect number of arguments to Instance");
1995 id value(CYCastNSObject(&pool, context, arguments[0]));
1997 value = [NSNull null];
1998 return CYCastJSValue(context, [value cy$box]);
2001 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2002 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2005 id self(internal->GetValue());
2006 const char *name(CYPoolCString(pool, context, property));
2008 if (object_getInstanceVariable(self, name, NULL) != NULL)
2014 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2015 length = CYCastDouble(encoding + 1);
2019 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2020 for (size_t i(0); i != size; ++i)
2021 if (ivars[i] == ivar)
2023 else if (ivar_getOffset(ivars[i]) == offset) {
2024 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2025 _assert(encoding != NULL);
2026 _assert(encoding[0] == 'b');
2027 shift += CYCastDouble(encoding + 1);
2032 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2033 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2036 id self(internal->GetValue());
2037 const char *name(CYPoolCString(pool, context, property));
2039 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2040 ptrdiff_t offset(ivar_getOffset(ivar));
2041 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2043 const char *encoding(ivar_getTypeEncoding(ivar));
2044 _assert(encoding != NULL);
2045 _assert(encoding[0] != '\0');
2046 if (encoding[0] == 'b') {
2047 unsigned length, shift;
2048 CYBitField(length, shift, self, ivar, encoding, offset);
2049 _assert(shift + length <= sizeof(uintptr_t) * 8);
2050 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2051 uintptr_t mask((1 << length) - 1);
2052 return CYCastJSValue(context, (field >> shift) & mask);
2054 #if defined(__APPLE__) && defined(__LP64__)
2055 // XXX: maybe do even more verifications here
2056 if (strcmp(name, "isa") == 0)
2057 return CYCastJSValue(context, object_getClass(self));
2060 auto type(new(pool) Type_privateData(encoding));
2061 return type->type_->FromFFI(context, type->GetFFI(), data);
2068 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2069 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2072 id self(internal->GetValue());
2073 const char *name(CYPoolCString(pool, context, property));
2075 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2076 ptrdiff_t offset(ivar_getOffset(ivar));
2077 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2079 const char *encoding(ivar_getTypeEncoding(ivar));
2080 _assert(encoding != NULL);
2081 if (encoding[0] == 'b') {
2082 unsigned length, shift;
2083 CYBitField(length, shift, self, ivar, encoding, offset);
2084 _assert(shift + length <= sizeof(uintptr_t) * 8);
2085 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2086 uintptr_t mask((1 << length) - 1);
2087 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2089 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2090 type->type_->PoolFFI(&pool, context, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2098 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2099 if (Class super = class_getSuperclass(_class))
2100 Internal_getPropertyNames_(super, names);
2103 objc_ivar **data(class_copyIvarList(_class, &size));
2104 for (size_t i(0); i != size; ++i)
2105 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2109 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2110 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2113 id self(internal->GetValue());
2114 Class _class(object_getClass(self));
2116 Internal_getPropertyNames_(_class, names);
2119 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2120 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2121 return internal->GetOwner();
2124 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2126 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2129 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2131 NSString *name(CYCastNSString(&pool, context, property));
2132 if (Class _class = NSClassFromString(name))
2133 return CYMakeInstance(context, _class, Instance::Permanent);
2137 static Class *CYCopyClassList(size_t &size) {
2138 size = objc_getClassList(NULL, 0);
2139 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2142 size_t writ(objc_getClassList(data, size));
2148 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2159 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2161 if (Class *data = CYCopyClassList(size)) {
2162 for (size_t i(0); i != size; ++i)
2163 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2169 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2170 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2173 const char *name(CYPoolCString(pool, context, property));
2175 const char **data(objc_copyClassNamesForImage(internal, &size));
2177 for (size_t i(0); i != size; ++i)
2178 if (strcmp(name, data[i]) == 0) {
2179 if (Class _class = objc_getClass(name)) {
2180 value = CYMakeInstance(context, _class, Instance::Permanent);
2191 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2192 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2194 const char **data(objc_copyClassNamesForImage(internal, &size));
2195 for (size_t i(0); i != size; ++i)
2196 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2200 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2202 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2205 const char **data(objc_copyImageNames(&size));
2206 pool.atexit(free, data);
2208 for (size_t i(0); i != size; ++i)
2209 if (name == data[i]) {
2210 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2211 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2218 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2220 const char **data(objc_copyImageNames(&size));
2221 for (size_t i(0); i != size; ++i)
2222 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2227 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2229 const char *name(CYPoolCString(pool, context, property));
2230 if (Protocol *protocol = objc_getProtocol(name))
2231 return CYMakeInstance(context, protocol, Instance::Permanent);
2235 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2237 Protocol **data(objc_copyProtocolList(&size));
2238 for (size_t i(0); i != size; ++i)
2239 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2243 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2245 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2247 return CYJSNull(context);
2251 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2252 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2256 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2257 *data = reinterpret_cast<void *>(address);
2258 return KERN_SUCCESS;
2262 std::set<Class> query_;
2263 JSContextRef context_;
2264 JSObjectRef results_;
2267 struct CYObjectStruct {
2271 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2272 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2273 JSContextRef context(choice->context_);
2275 for (unsigned i(0); i != count; ++i) {
2276 vm_range_t &range(ranges[i]);
2277 void *data(reinterpret_cast<void *>(range.address));
2278 size_t size(range.size);
2280 if (size < sizeof(CYObjectStruct))
2283 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2284 #if defined(__APPLE__) && defined(__LP64__)
2285 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2287 Class isa(reinterpret_cast<Class>(pointers[0]));
2290 std::set<Class>::const_iterator result(choice->query_.find(isa));
2291 if (result == choice->query_.end())
2294 size_t needed(class_getInstanceSize(*result));
2295 // XXX: if (size < needed)
2297 size_t boundary(496);
2301 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2303 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2307 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2309 throw CYJSError(context, "choose() takes a class argument");
2311 CYGarbageCollect(context);
2314 id _class(CYCastNSObject(&pool, context, arguments[0]));
2316 vm_address_t *zones(NULL);
2318 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2319 _assert(error == KERN_SUCCESS);
2321 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2322 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2325 choice.context_ = context;
2326 choice.results_ = results;
2329 Class *classes(CYCopyClassList(number));
2330 _assert(classes != NULL);
2332 for (size_t i(0); i != number; ++i)
2333 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2334 if (current == _class) {
2335 choice.query_.insert(classes[i]);
2341 for (unsigned i(0); i != size; ++i) {
2342 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2343 if (zone == NULL || zone->introspect == NULL)
2346 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2354 #if defined(__i386__) || defined(__x86_64__)
2355 #define OBJC_MAX_STRUCT_BY_VALUE 8
2356 static int struct_forward_array[] = {
2357 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2358 #elif defined(__arm__)
2359 #define OBJC_MAX_STRUCT_BY_VALUE 1
2360 static int struct_forward_array[] = {
2362 #elif defined(__arm64__)
2365 #error missing objc-runtime-info
2369 static bool stret(ffi_type *ffi_type) {
2370 return ffi_type->type == FFI_TYPE_STRUCT && (
2371 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2372 struct_forward_array[ffi_type->size] != 0
2380 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2384 _class = object_getClass(self);
2388 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2389 imp = method_getImplementation(method);
2390 type = method_getTypeEncoding(method);
2395 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2396 type = CYPoolCString(pool, context, [method _typeString]);
2402 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2409 sig::Signature signature;
2410 sig::Parse(pool, &signature, type, &Structor_);
2412 size_t used(count + 3);
2413 if (used > signature.count) {
2414 sig::Element *elements(new (pool) sig::Element[used]);
2415 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2417 for (size_t index(signature.count); index != used; ++index) {
2418 sig::Element *element(&elements[index]);
2419 element->name = NULL;
2420 element->offset = _not(size_t);
2421 element->type = new(pool) sig::Object();
2424 signature.elements = elements;
2425 signature.count = used;
2429 sig::sig_ffi_cif(pool, &signature, &cif);
2433 if (stret(cif.rtype))
2434 imp = class_getMethodImplementation_stret(_class, _cmd);
2437 imp = class_getMethodImplementation(_class, _cmd);
2440 void (*function)() = reinterpret_cast<void (*)()>(imp);
2441 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2444 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2446 throw CYJSError(context, "too few arguments to objc_msgSend");
2456 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2457 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2458 self = internal->GetValue();
2459 _class = internal->class_;;
2460 uninitialized = false;
2461 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2462 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2463 self = internal->GetValue();
2465 uninitialized = internal->IsUninitialized();
2467 internal->value_ = nil;
2469 self = CYCastNSObject(&pool, context, arguments[0]);
2471 uninitialized = false;
2475 return CYJSNull(context);
2477 _cmd = CYCastSEL(context, arguments[1]);
2479 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2482 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2483 return $objc_msgSend(context, object, _this, count, arguments);
2486 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2487 JSValueRef setup[count + 2];
2490 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2491 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2494 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2496 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2498 // XXX: handle Instance::Uninitialized?
2499 id self(CYCastNSObject(&pool, context, _this));
2503 setup[1] = &internal->sel_;
2505 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2508 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2510 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2512 id self(CYCastNSObject(&pool, context, arguments[0]));
2513 Class _class(CYCastClass(pool, context, arguments[1]));
2514 return cy::Super::Make(context, self, _class);
2517 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2519 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2521 const char *name(CYPoolCString(pool, context, arguments[0]));
2522 return CYMakeSelector(context, sel_registerName(name));
2525 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2527 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2528 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2531 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2532 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2533 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2536 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2537 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2538 Type_privateData *typical(internal->GetType());
2545 if (typical == NULL) {
2549 type = typical->type_;
2550 ffi = typical->ffi_;
2553 return CYMakePointer(context, &internal->value_, _not(size_t), *type, ffi, object);
2556 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2557 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2559 sig::Signature *signature(CYBlockSignature(pool, internal->GetValue()));
2560 if (signature == NULL)
2561 return CYJSNull(context);
2562 return CYMakeType(context, signature);
2565 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2566 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2567 return CYMakeInstance(context, object_getClass(internal->GetValue()), Instance::Permanent);
2570 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2571 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2572 id self(internal->GetValue());
2573 if (!CYIsClass(self))
2574 return CYJSUndefined(context);
2575 return CYGetClassPrototype(context, self);
2578 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2579 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2580 id self(internal->GetValue());
2581 if (!CYIsClass(self))
2582 return CYJSUndefined(context);
2583 return Messages::Make(context, (Class) self);
2586 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2587 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2589 if (!CYJSValueIsNSObject(context, _this))
2592 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2593 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2596 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2597 if (!CYJSValueIsNSObject(context, _this))
2600 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2601 id value(internal->GetValue());
2608 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2610 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2611 return CYJSUndefined(context);
2612 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2615 return CYCastJSValue(context, CYJSString(context, [value description]));
2617 } CYCatch(NULL) return /*XXX*/ NULL; }
2619 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2620 if (!CYJSValueIsNSObject(context, _this))
2623 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2624 id value(internal->GetValue());
2625 _assert(value != nil);
2627 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2630 if (JSValueRef result = [value cy$valueOfInContext:context])
2634 } CYCatch(NULL) return /*XXX*/ NULL; }
2636 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2637 if (!CYJSValueIsNSObject(context, _this))
2640 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2641 // XXX: but... but... THIS ISN'T A POINTER! :(
2642 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2643 } CYCatch(NULL) return /*XXX*/ NULL; }
2645 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2646 if (!CYJSValueIsNSObject(context, _this))
2649 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2650 id value(internal->GetValue());
2653 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2654 return CYCastJSValue(context, CYJSString(context, [value description]));
2656 } CYCatch(NULL) return /*XXX*/ NULL; }
2658 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2659 if (!CYJSValueIsNSObject(context, _this))
2662 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2663 id value(internal->GetValue());
2665 if (!CYIsClass(value))
2666 CYThrow("non-Class object cannot be used as Type");
2668 sig::Object type(class_getName(value));
2669 return CYMakeType(context, type);
2670 } CYCatch(NULL) return /*XXX*/ NULL; }
2672 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2673 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2674 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2677 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2678 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2681 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2682 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2683 const char *name(sel_getName(internal->GetValue()));
2686 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2687 return CYCastJSValue(context, CYJSString(context, string));
2689 } CYCatch(NULL) return /*XXX*/ NULL; }
2691 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2693 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2696 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2697 SEL sel(internal->GetValue());
2699 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2700 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2701 const char *encoding(method_getTypeEncoding(method));
2703 sig::Signature signature;
2704 sig::Parse(pool, &signature, encoding, &Structor_);
2705 return CYMakeType(context, &signature);
2708 static JSStaticValue Selector_staticValues[2] = {
2709 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2710 {NULL, NULL, NULL, 0}
2713 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2714 static JSStaticValue Instance_staticValues[5] = {
2715 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2716 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2717 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2718 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2719 {NULL, NULL, NULL, 0}
2722 static JSStaticValue FunctionInstance_staticValues[6] = {
2723 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2724 // XXX: this is sadly a duplicate of Instance_staticValues
2725 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2726 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2727 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2728 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2729 {NULL, NULL, NULL, 0}
2732 static JSStaticFunction Instance_staticFunctions[7] = {
2733 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2734 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2735 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2736 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2737 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2738 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2742 static JSStaticFunction Class_staticFunctions[2] = {
2743 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2747 static JSStaticFunction Internal_staticFunctions[2] = {
2748 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2752 static JSStaticFunction Selector_staticFunctions[5] = {
2753 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2754 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2755 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2756 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2761 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2762 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2763 } CYObjectiveCatch }
2766 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2767 CYPool &pool(CYGetGlobalPool());
2769 Object_type = new(pool) Type_privateData(sig::Object());
2770 Selector_type = new(pool) Type_privateData(sig::Selector());
2772 NSArray_ = objc_getClass("NSArray");
2773 NSBlock_ = objc_getClass("NSBlock");
2774 NSDictionary_ = objc_getClass("NSDictionary");
2775 NSNumber_ = objc_getClass("NSNumber");
2776 NSString_ = objc_getClass("NSString");
2777 Object_ = objc_getClass("Object");
2780 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2782 // XXX: apparently, iOS now has both of these
2783 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2784 if (NSCFBoolean_ == nil)
2785 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2787 NSCFType_ = objc_getClass("NSCFType");
2789 NSZombie_ = objc_getClass("_NSZombie_");
2791 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2792 NSZombie_ = objc_getClass("NSZombie");
2795 JSClassDefinition definition;
2797 definition = kJSClassDefinitionEmpty;
2798 definition.className = "Instance";
2799 definition.staticValues = Instance_staticValues;
2800 definition.staticFunctions = Instance_staticFunctions;
2801 definition.hasProperty = &Instance_hasProperty;
2802 definition.getProperty = &Instance_getProperty;
2803 definition.setProperty = &Instance_setProperty;
2804 definition.deleteProperty = &Instance_deleteProperty;
2805 definition.getPropertyNames = &Instance_getPropertyNames;
2806 definition.callAsConstructor = &Instance_callAsConstructor;
2807 definition.hasInstance = &Instance_hasInstance;
2808 definition.finalize = &CYFinalize;
2809 Instance_ = JSClassCreate(&definition);
2811 definition.className = "ArrayInstance";
2812 ArrayInstance_ = JSClassCreate(&definition);
2814 definition.className = "BooleanInstance";
2815 BooleanInstance_ = JSClassCreate(&definition);
2817 definition.className = "NumberInstance";
2818 NumberInstance_ = JSClassCreate(&definition);
2820 definition.className = "ObjectInstance";
2821 ObjectInstance_ = JSClassCreate(&definition);
2823 definition.className = "StringInstance";
2824 StringInstance_ = JSClassCreate(&definition);
2826 definition.className = "FunctionInstance";
2827 definition.staticValues = FunctionInstance_staticValues;
2828 definition.callAsFunction = &FunctionInstance_callAsFunction;
2829 FunctionInstance_ = JSClassCreate(&definition);
2831 definition = kJSClassDefinitionEmpty;
2832 definition.className = "Class";
2833 definition.staticFunctions = Class_staticFunctions;
2834 Class_ = JSClassCreate(&definition);
2836 definition = kJSClassDefinitionEmpty;
2837 definition.className = "Internal";
2838 definition.staticFunctions = Internal_staticFunctions;
2839 definition.hasProperty = &Internal_hasProperty;
2840 definition.getProperty = &Internal_getProperty;
2841 definition.setProperty = &Internal_setProperty;
2842 definition.getPropertyNames = &Internal_getPropertyNames;
2843 definition.finalize = &CYFinalize;
2844 Internal_ = JSClassCreate(&definition);
2846 definition = kJSClassDefinitionEmpty;
2847 definition.className = "Message";
2848 definition.staticFunctions = cy::Functor::StaticFunctions;
2849 definition.staticValues = cy::Functor::StaticValues;
2850 definition.callAsFunction = &Message_callAsFunction;
2851 definition.finalize = &CYFinalize;
2852 Message_ = JSClassCreate(&definition);
2854 definition = kJSClassDefinitionEmpty;
2855 definition.className = "Messages";
2856 definition.hasProperty = &Messages_hasProperty;
2857 definition.getProperty = &Messages_getProperty;
2858 definition.setProperty = &Messages_setProperty;
2859 definition.getPropertyNames = &Messages_getPropertyNames;
2860 definition.finalize = &CYFinalize;
2861 Messages_ = JSClassCreate(&definition);
2863 definition = kJSClassDefinitionEmpty;
2864 definition.className = "Selector";
2865 definition.staticValues = Selector_staticValues;
2866 definition.staticFunctions = Selector_staticFunctions;
2867 definition.callAsFunction = &Selector_callAsFunction;
2868 definition.finalize = &CYFinalize;
2869 Selector_ = JSClassCreate(&definition);
2871 definition = kJSClassDefinitionEmpty;
2872 definition.className = "Super";
2873 definition.staticFunctions = Internal_staticFunctions;
2874 definition.finalize = &CYFinalize;
2875 Super_ = JSClassCreate(&definition);
2877 definition = kJSClassDefinitionEmpty;
2878 definition.className = "ObjectiveC::Classes";
2879 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2880 definition.getProperty = &ObjectiveC_Classes_getProperty;
2881 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2882 ObjectiveC_Classes_ = JSClassCreate(&definition);
2884 definition = kJSClassDefinitionEmpty;
2885 definition.className = "ObjectiveC::Constants";
2886 definition.getProperty = &ObjectiveC_Constants_getProperty;
2887 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2888 ObjectiveC_Constants_ = JSClassCreate(&definition);
2891 definition = kJSClassDefinitionEmpty;
2892 definition.className = "ObjectiveC::Images";
2893 definition.getProperty = &ObjectiveC_Images_getProperty;
2894 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2895 ObjectiveC_Images_ = JSClassCreate(&definition);
2897 definition = kJSClassDefinitionEmpty;
2898 definition.className = "ObjectiveC::Image::Classes";
2899 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2900 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2901 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2904 definition = kJSClassDefinitionEmpty;
2905 definition.className = "ObjectiveC::Protocols";
2906 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2907 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2908 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2911 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2912 // XXX: this is horrible; there has to be a better way to do this
2914 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2916 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2922 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2923 JSObjectRef global(CYGetGlobalObject(context));
2924 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2925 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2926 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2927 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2929 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2930 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2932 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2933 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2934 CYArrayPush(context, alls, protocols);
2936 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2937 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2938 CYArrayPush(context, alls, classes);
2940 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2941 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2942 CYArrayPush(context, alls, constants);
2945 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2948 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2949 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2950 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2951 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2952 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2954 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2955 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2957 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2958 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2959 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2960 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2961 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2963 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2964 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2965 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2966 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2967 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2969 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2970 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2971 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2972 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2973 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2975 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2976 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2977 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2978 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2979 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2981 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2982 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2983 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2984 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2985 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2987 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2988 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2989 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2990 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2991 CYSetPrototype(context, StringInstance_prototype, String_prototype);
2993 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2994 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2995 CYSetPrototype(context, Class_prototype, Instance_prototype);
2997 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2998 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2999 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3001 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3002 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3005 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3008 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3010 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3011 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3013 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
3014 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
3015 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
3016 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::Object()), kJSPropertyAttributeDontEnum);
3017 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::Meta()), kJSPropertyAttributeDontEnum);
3018 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::Selector()), kJSPropertyAttributeDontEnum);
3021 static void *CYObjectiveC_CastSymbol(const char *name) {
3023 #ifdef __GNU_LIBOBJC__
3024 else if (strcmp(name, "object_getClass") == 0)
3025 return reinterpret_cast<void *>(&object_getClass);
3030 static CYHook CYObjectiveCHook = {
3031 &CYObjectiveC_ExecuteStart,
3032 &CYObjectiveC_ExecuteEnd,
3033 &CYObjectiveC_CallFunction,
3034 &CYObjectiveC_Initialize,
3035 &CYObjectiveC_SetupContext,
3036 &CYObjectiveC_CastSymbol,
3039 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3041 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3042 CYSetupContext(context);
3043 } CYObjectiveCatch }
3045 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3048 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3049 utf8 = CYPoolCode(pool, utf8);
3051 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3052 size_t bytes(utf16.size * sizeof(uint16_t));
3053 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3054 memcpy(copy, utf16.data, bytes);
3058 } catch (const CYException &exception) {
3060 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];