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);
864 // XXX: maybe move this id check into Decode's implementation for block_P
865 _assert(signature->count >= 2);
866 _assert(signature->elements[1].type->primitive == sig::object_P);
872 type.primitive = sig::function_P; // XXX: sig::block_P
873 sig::Copy(pool, type.data.signature, *signature);
875 CYTypedIdentifier *typed((new(pool) CYTypeExpression(Decode(pool, &type)))->typed_);
876 CYTypeFunctionWith *function(typed->Function());
877 _assert(function != NULL);
879 _assert(function->parameters_ != NULL);
880 CYObjCBlock *block(new(pool) CYObjCBlock(typed, function->parameters_->next_, NULL));
882 std::ostringstream str;
884 CYOutput out(*str.rdbuf(), options);
885 block->Output(out, CYNoFlags);
887 std::string value(str.str());
888 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
894 /* Bridge: NSBoolNumber {{{ */
896 @implementation NSBoolNumber (Cycript)
898 - (JSType) cy$JSType {
899 return kJSTypeBoolean;
902 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
903 NSString *value([self boolValue] ? @"true" : @"false");
904 return objective ? value : [NSString stringWithFormat:@"@%@", value];
907 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
908 return CYCastJSValue(context, (bool) [self boolValue]);
914 /* Bridge: NSDictionary {{{ */
915 @implementation NSDictionary (Cycript)
918 return [[self mutableCopy] autorelease];
921 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
922 _oassert(objects.insert(self).second);
924 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
925 [json appendString:@"@{"];
929 for (NSObject *key in self) {
931 NSEnumerator *keys([self keyEnumerator]);
932 while (NSObject *key = [keys nextObject]) {
935 [json appendString:@","];
938 [json appendString:CYCastNSCYON(key, true, objects)];
939 [json appendString:@":"];
940 NSObject *object([self objectForKey:key]);
941 [json appendString:CYCastNSCYON(object, true, objects)];
944 [json appendString:@"}"];
948 - (bool) cy$hasProperty:(NSString *)name {
949 return [self objectForKey:name] != nil;
952 - (NSObject *) cy$getProperty:(NSString *)name {
953 return [self objectForKey:name];
956 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
957 [super cy$getPropertyNames:names inContext:context];
960 for (NSObject *key in self) {
962 NSEnumerator *keys([self keyEnumerator]);
963 while (NSObject *key = [keys nextObject]) {
965 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
969 + (bool) cy$hasImplicitProperties {
975 /* Bridge: NSMutableArray {{{ */
976 @implementation NSMutableArray (Cycript)
978 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
979 if ([name isEqualToString:@"length"]) {
980 // XXX: is this not intelligent?
981 NSNumber *number(reinterpret_cast<NSNumber *>(value));
982 NSUInteger size([number unsignedIntegerValue]);
983 NSUInteger count([self count]);
985 [self removeObjectsInRange:NSMakeRange(size, count - size)];
986 else if (size != count) {
987 WebUndefined *undefined([WebUndefined undefined]);
988 for (size_t i(count); i != size; ++i)
989 [self addObject:undefined];
994 size_t index(CYGetIndex(name));
995 if (index == _not(size_t))
996 return [super cy$setProperty:name to:value];
998 id object(value ?: [NSNull null]);
1000 size_t count([self count]);
1002 [self replaceObjectAtIndex:index withObject:object];
1004 if (index != count) {
1005 WebUndefined *undefined([WebUndefined undefined]);
1006 for (size_t i(count); i != index; ++i)
1007 [self addObject:undefined];
1010 [self addObject:object];
1016 - (bool) cy$deleteProperty:(NSString *)name {
1017 size_t index(CYGetIndex(name));
1018 if (index == _not(size_t) || index >= [self count])
1019 return [super cy$deleteProperty:name];
1020 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1026 /* Bridge: NSMutableDictionary {{{ */
1027 @implementation NSMutableDictionary (Cycript)
1029 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1030 [self setObject:(value ?: [NSNull null]) forKey:name];
1034 - (bool) cy$deleteProperty:(NSString *)name {
1035 if ([self objectForKey:name] == nil)
1038 [self removeObjectForKey:name];
1045 /* Bridge: NSNumber {{{ */
1046 @implementation NSNumber (Cycript)
1048 - (JSType) cy$JSType {
1050 // XXX: this just seems stupid
1051 if ([self class] == NSCFBoolean_)
1052 return kJSTypeBoolean;
1054 return kJSTypeNumber;
1057 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1058 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1059 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1062 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1063 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1064 } CYObjectiveCatch }
1068 /* Bridge: NSNull {{{ */
1069 @implementation NSNull (Cycript)
1071 - (JSType) cy$JSType {
1075 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1076 NSString *value(@"null");
1077 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1080 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1081 return CYJSNull(context);
1082 } CYObjectiveCatch }
1086 /* Bridge: NSObject {{{ */
1087 @implementation NSObject (Cycript)
1093 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1094 return [self cy$valueOfInContext:context];
1097 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1099 } CYObjectiveCatch }
1101 - (JSType) cy$JSType {
1102 return kJSTypeObject;
1105 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1106 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1109 - (bool) cy$hasProperty:(NSString *)name {
1113 - (NSObject *) cy$getProperty:(NSString *)name {
1117 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1118 if (NSObject *value = [self cy$getProperty:name])
1119 return CYCastJSValue(context, value);
1121 } CYObjectiveCatch }
1123 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1127 - (bool) cy$deleteProperty:(NSString *)name {
1131 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1134 + (bool) cy$hasImplicitProperties {
1140 /* Bridge: NSOrderedSet {{{ */
1142 @implementation NSOrderedSet (Cycript)
1144 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1145 _oassert(objects.insert(self).second);
1147 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1148 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1149 [json appendString:CYCastNSCYON([self array], true, objects)];
1150 [json appendString:@"]]"];
1157 /* Bridge: NSProxy {{{ */
1158 @implementation NSProxy (Cycript)
1160 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1161 return [[self description] cy$toCYON:objective inSet:objects];
1166 /* Bridge: NSSet {{{ */
1167 @implementation NSSet (Cycript)
1169 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1170 _oassert(objects.insert(self).second);
1172 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1173 [json appendString:@"[NSSet setWithArray:"];
1174 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1175 [json appendString:@"]]"];
1181 /* Bridge: NSString {{{ */
1182 @implementation NSString (Cycript)
1185 return [[self copy] autorelease];
1188 - (JSType) cy$JSType {
1189 return kJSTypeString;
1192 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1193 std::ostringstream str;
1196 CYUTF8String string(CYCastUTF8String(self));
1197 CYStringify(str, string.data, string.size, true);
1198 std::string value(str.str());
1199 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1202 - (bool) cy$hasProperty:(NSString *)name {
1203 size_t index(CYGetIndex(name));
1204 if (index == _not(size_t) || index >= [self length])
1205 return [super cy$hasProperty:name];
1210 - (NSObject *) cy$getProperty:(NSString *)name {
1211 size_t index(CYGetIndex(name));
1212 if (index == _not(size_t) || index >= [self length])
1213 return [super cy$getProperty:name];
1215 return [self substringWithRange:NSMakeRange(index, 1)];
1218 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1219 [super cy$getPropertyNames:names inContext:context];
1221 for (size_t index(0), length([self length]); index != length; ++index) {
1223 sprintf(name, "%zu", index);
1224 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1228 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1229 return CYCastJSValue(context, CYJSString(context, self));
1230 } CYObjectiveCatch }
1234 /* Bridge: WebUndefined {{{ */
1235 @implementation WebUndefined (Cycript)
1237 - (JSType) cy$JSType {
1238 return kJSTypeUndefined;
1241 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1242 NSString *value(@"undefined");
1243 return value; // XXX: maybe use the below code, adding @undefined?
1244 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1247 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1248 return CYJSUndefined(context);
1249 } CYObjectiveCatch }
1254 static bool CYIsClass(id self) {
1255 return class_isMetaClass(object_getClass(self));
1258 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1259 id self(CYCastNSObject(&pool, context, value));
1260 if (CYIsClass(self))
1261 return (Class) self;
1262 throw CYJSError(context, "got something that is not a Class");
1266 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1268 size_t size(JSPropertyNameArrayGetCount(names));
1269 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1270 for (size_t index(0); index != size; ++index)
1271 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1275 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1277 return CYJSNull(context);
1279 return CYMakeInstance(context, value);
1280 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1282 @implementation CYJSObject
1284 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1285 if ((self = [super init]) != nil) {
1287 context_ = CYGetJSContext(context);
1288 JSGlobalContextRetain(context_);
1289 JSValueProtect(context_, object_);
1291 } CYObjectiveCatch }
1293 - (void) dealloc { CYObjectiveTry {
1294 JSValueUnprotect(context_, object_);
1295 JSGlobalContextRelease(context_);
1297 } CYObjectiveCatch }
1299 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1301 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1303 return [super cy$toCYON:objective inSet:objects];
1305 return [NSString stringWithUTF8String:cyon];
1306 } CYObjectiveCatch }
1308 - (NSUInteger) count { CYObjectiveTry {
1309 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1310 size_t size(JSPropertyNameArrayGetCount(names));
1311 JSPropertyNameArrayRelease(names);
1313 } CYObjectiveCatch }
1315 - (id) objectForKey:(id)key { CYObjectiveTry {
1316 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1317 if (JSValueIsUndefined(context, value))
1319 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1320 } CYObjectiveCatch }
1322 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1323 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1324 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1325 JSPropertyNameArrayRelease(names);
1327 } CYObjectiveCatch }
1329 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1330 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1331 } CYObjectiveCatch }
1333 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1334 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1335 } CYObjectiveCatch }
1339 @implementation CYJSArray
1341 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1343 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1344 } CYObjectiveCatch }
1346 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1347 if ((self = [super init]) != nil) {
1349 context_ = CYGetJSContext(context);
1350 JSGlobalContextRetain(context_);
1351 JSValueProtect(context_, object_);
1353 } CYObjectiveCatch }
1355 - (void) dealloc { CYObjectiveTry {
1356 JSValueUnprotect(context_, object_);
1357 JSGlobalContextRelease(context_);
1359 } CYObjectiveCatch }
1361 - (NSUInteger) count { CYObjectiveTry {
1362 return CYArrayLength(context, object_);
1363 } CYObjectiveCatch }
1365 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1366 size_t bounds([self count]);
1367 if (index >= bounds)
1368 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1369 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1370 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1371 } CYObjectiveCatch }
1373 - (void) addObject:(id)object { CYObjectiveTry {
1374 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1375 } CYObjectiveCatch }
1377 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1378 size_t bounds([self count] + 1);
1379 if (index >= bounds)
1380 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1381 JSValueRef arguments[3];
1382 arguments[0] = CYCastJSValue(context, index);
1383 arguments[1] = CYCastJSValue(context, 0);
1384 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1385 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1386 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1387 } CYObjectiveCatch }
1389 - (void) removeLastObject { CYObjectiveTry {
1390 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1391 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1392 } CYObjectiveCatch }
1394 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1395 size_t bounds([self count]);
1396 if (index >= bounds)
1397 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1398 JSValueRef arguments[2];
1399 arguments[0] = CYCastJSValue(context, index);
1400 arguments[1] = CYCastJSValue(context, 1);
1401 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1402 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1403 } CYObjectiveCatch }
1405 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1406 size_t bounds([self count]);
1407 if (index >= bounds)
1408 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1409 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1410 } CYObjectiveCatch }
1414 // XXX: inherit from or replace with CYJSObject
1415 @interface CYInternal : NSObject {
1416 JSGlobalContextRef context_;
1417 JSObjectRef object_;
1422 @implementation CYInternal
1424 - (void) dealloc { CYObjectiveTry {
1425 JSValueUnprotect(context_, object_);
1426 JSGlobalContextRelease(context_);
1428 } CYObjectiveCatch }
1430 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1431 if ((self = [super init]) != nil) {
1432 context_ = CYGetJSContext(context);
1433 JSGlobalContextRetain(context_);
1435 } CYObjectiveCatch }
1437 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1438 if (object_ == NULL)
1441 return JSObjectHasProperty(context, object_, name);
1444 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1445 if (object_ == NULL)
1448 return CYGetProperty(context, object_, name);
1451 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1452 @synchronized (self) {
1453 if (object_ == NULL) {
1454 object_ = JSObjectMake(context, NULL, NULL);
1455 JSValueProtect(context, object_);
1459 CYSetProperty(context, object_, name, value);
1462 + (CYInternal *) get:(id)object {
1464 if (&objc_getAssociatedObject == NULL)
1467 @synchronized (object) {
1468 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1476 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1478 if (&objc_getAssociatedObject == NULL)
1481 @synchronized (object) {
1482 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1485 if (&objc_setAssociatedObject == NULL)
1488 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1489 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1499 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1500 Selector_privateData *internal(new Selector_privateData(sel));
1501 return JSObjectMake(context, Selector_, internal);
1504 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1505 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1506 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1507 return reinterpret_cast<SEL>(internal->value_);
1510 return sel_registerName(CYPoolCString(pool, context, value));
1514 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1515 return (void *) [[NSAutoreleasePool alloc] init];
1516 } CYSadCatch(NULL) }
1518 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1519 return [(NSAutoreleasePool *) handle release];
1522 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1523 CYCallFunction(pool, context, cif, function, value, values);
1527 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, sig::Signature *signature) {
1528 if (JSValueIsNull(context, value))
1530 JSObjectRef object(CYCastJSObject(context, value));
1532 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1533 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1535 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1536 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1540 _assert(JSObjectIsFunction(context, object));
1542 _assert(signature != NULL);
1543 _assert(signature->count != 0);
1545 sig::Signature modified;
1546 modified.count = signature->count + 1;
1547 modified.elements = new(pool) sig::Element[modified.count];
1549 modified.elements[0] = signature->elements[0];
1550 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1552 modified.elements[1].name = NULL;
1553 modified.elements[1].type = new(pool) sig::Type();
1554 modified.elements[1].offset = _not(size_t);
1556 memset(modified.elements[1].type, 0, sizeof(sig::Type));
1557 modified.elements[1].type->primitive = sig::object_P;
1559 return CYMakeBlock(context, object, modified);
1563 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1564 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1566 switch (type->primitive) {
1569 // XXX: this function might not handle the idea of a null pool
1570 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &type->data.signature);
1575 case sig::typename_P:
1576 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1579 case sig::selector_P:
1580 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1588 } CYSadCatch(false) }
1590 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1591 switch (type->primitive) {
1592 // XXX: do something epic about blocks
1595 if (NSObject *value = *reinterpret_cast<NSObject **>(data)) {
1596 JSObjectRef object(CYMakeInstance(context, value));
1599 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1601 if ((internal->flags_ & Instance::Uninitialized) != 0) {
1602 internal->flags_ = static_cast<Instance::Flags>(internal->flags_ & ~Instance::Uninitialized);
1603 _assert(internal->value_ == nil);
1604 internal->value_ = value;
1613 case sig::typename_P:
1614 if (Class value = *reinterpret_cast<Class *>(data))
1615 return CYMakeInstance(context, value, Instance::Permanent);
1618 case sig::selector_P:
1619 if (SEL value = *reinterpret_cast<SEL *>(data))
1620 return CYMakeSelector(context, value);
1624 return CYJSNull(context);
1628 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1630 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1631 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1635 method_getReturnType(method, type, sizeof(type));
1640 // XXX: possibly use a more "awesome" check?
1644 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1645 JSObjectRef _this(CYCastJSObject(context, values[0]));
1646 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1649 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1650 Message_privateData *internal(new Message_privateData(sel, type, imp));
1651 return JSObjectMake(context, Message_, internal);
1654 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1655 JSObjectRef function(CYCastJSObject(context, value));
1657 sig::Signature signature;
1658 sig::Parse(pool, &signature, encoding, &Structor_);
1659 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1660 // XXX: see notes in Library.cpp about needing to leak
1661 return reinterpret_cast<IMP>(internal->GetValue());
1664 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
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 (class_getInstanceMethod(_class, sel) != NULL)
1678 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1679 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1680 Class _class(internal->GetValue());
1683 const char *name(CYPoolCString(pool, context, property));
1685 if (SEL sel = sel_getUid(name))
1686 if (objc_method *method = class_getInstanceMethod(_class, sel))
1687 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1692 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1693 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1694 Class _class(internal->GetValue());
1697 const char *name(CYPoolCString(pool, context, property));
1698 SEL sel(sel_registerName(name));
1703 if (JSValueIsObjectOfClass(context, value, Message_)) {
1704 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1705 type = sig::Unparse(pool, &message->signature_);
1706 imp = reinterpret_cast<IMP>(message->GetValue());
1707 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1708 type = method_getTypeEncoding(method);
1709 imp = CYMakeMessage(context, value, type);
1710 } else _assert(false);
1712 objc_method *method(NULL);
1714 objc_method **methods(class_copyMethodList(_class, &size));
1715 for (size_t i(0); i != size; ++i)
1716 if (sel_isEqual(method_getName(methods[i]), sel)) {
1717 method = methods[i];
1723 method_setImplementation(method, imp);
1725 class_addMethod(_class, sel, imp, type);
1730 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1731 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1732 Class _class(internal->GetValue());
1735 objc_method **data(class_copyMethodList(_class, &size));
1736 for (size_t i(0); i != size; ++i)
1737 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1741 static bool CYHasImplicitProperties(Class _class) {
1742 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1743 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1745 return [_class cy$hasImplicitProperties];
1748 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1749 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1750 id self(internal->GetValue());
1752 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1756 NSString *name(CYCastNSString(&pool, context, property));
1758 if (CYInternal *internal = [CYInternal get:self])
1759 if ([internal hasProperty:property inContext:context])
1762 Class _class(object_getClass(self));
1765 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1766 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1767 if ([self cy$hasProperty:name])
1769 } CYPoolCatch(false)
1771 const char *string(CYPoolCString(pool, context, name));
1773 if (class_getProperty(_class, string) != NULL)
1776 if (CYHasImplicitProperties(_class))
1777 if (SEL sel = sel_getUid(string))
1778 if (CYImplements(self, _class, sel, true))
1784 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1785 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1786 id self(internal->GetValue());
1788 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1789 return Internal::Make(context, self, object);
1792 NSString *name(CYCastNSString(&pool, context, property));
1794 if (CYInternal *internal = [CYInternal get:self])
1795 if (JSValueRef value = [internal getProperty:property inContext:context])
1799 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1803 const char *string(CYPoolCString(pool, context, name));
1804 Class _class(object_getClass(self));
1806 if (objc_property_t property = class_getProperty(_class, string)) {
1807 PropertyAttributes attributes(property);
1808 SEL sel(sel_registerName(attributes.Getter()));
1809 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1812 if (CYHasImplicitProperties(_class))
1813 if (SEL sel = sel_getUid(string))
1814 if (CYImplements(self, _class, sel, true))
1815 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1820 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1821 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1822 id self(internal->GetValue());
1826 NSString *name(CYCastNSString(&pool, context, property));
1827 NSObject *data(CYCastNSObject(&pool, context, value));
1830 if ([self cy$setProperty:name to:data])
1832 } CYPoolCatch(false)
1834 const char *string(CYPoolCString(pool, context, name));
1835 Class _class(object_getClass(self));
1837 if (objc_property_t property = class_getProperty(_class, string)) {
1838 PropertyAttributes attributes(property);
1839 if (const char *setter = attributes.Setter()) {
1840 SEL sel(sel_registerName(setter));
1841 JSValueRef arguments[1] = {value};
1842 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1847 size_t length(strlen(string));
1849 char set[length + 5];
1855 if (string[0] != '\0') {
1856 set[3] = toupper(string[0]);
1857 memcpy(set + 4, string + 1, length - 1);
1860 set[length + 3] = ':';
1861 set[length + 4] = '\0';
1863 if (SEL sel = sel_getUid(set))
1864 if (CYImplements(self, _class, sel)) {
1865 JSValueRef arguments[1] = {value};
1866 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1870 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1871 [internal setProperty:property toValue:value inContext:context];
1878 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1879 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1880 id self(internal->GetValue());
1883 NSString *name(CYCastNSString(NULL, context, property));
1884 return [self cy$deleteProperty:name];
1885 } CYPoolCatch(false)
1886 } CYCatch(false) return /*XXX*/ false; }
1888 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1889 const char *name(sel_getName(method_getName(method)));
1890 if (strchr(name, ':') != NULL)
1893 const char *type(method_getTypeEncoding(method));
1894 if (type == NULL || *type == '\0' || *type == 'v')
1897 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1900 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1901 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1902 id self(internal->GetValue());
1905 Class _class(object_getClass(self));
1909 objc_property_t *data(class_copyPropertyList(_class, &size));
1910 for (size_t i(0); i != size; ++i)
1911 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1915 if (CYHasImplicitProperties(_class))
1916 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1918 objc_method **data(class_copyMethodList(current, &size));
1919 for (size_t i(0); i != size; ++i)
1920 Instance_getPropertyNames_message(names, data[i]);
1925 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1926 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1927 [self cy$getPropertyNames:names inContext:context];
1931 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1932 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1933 JSObjectRef value(CYMakeInstance(context, [internal->GetValue() alloc], Instance::Uninitialized));
1937 static const char *CYBlockEncoding(NSBlock *self) {
1938 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1939 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1941 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1942 descriptor += sizeof(BlockDescriptor1);
1943 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1944 descriptor += sizeof(BlockDescriptor2);
1945 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1946 return descriptor3->signature;
1949 static sig::Signature *CYBlockSignature(CYPool &pool, NSBlock *self) {
1950 const char *encoding(CYBlockEncoding(self));
1951 if (encoding == NULL)
1953 // XXX: this should be stored on a FunctionInstance private value subclass
1954 sig::Signature *signature(new(pool) sig::Signature());
1955 sig::Parse(pool, signature, encoding, &Structor_);
1959 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1960 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1961 id self(internal->GetValue());
1963 if (const char *encoding = CYBlockEncoding(self)) {
1969 sig::Signature signature;
1970 sig::Parse(pool, &signature, encoding, &Structor_);
1973 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1975 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1976 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1977 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1981 CYThrow("NSBlock without signature field passed arguments");
1985 } CYPoolCatch(NULL);
1990 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1991 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1992 Class _class(internal->GetValue());
1993 if (!CYIsClass(_class))
1996 if (CYJSValueIsNSObject(context, instance)) {
1997 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1998 // XXX: this isn't always safe
1999 return [linternal->GetValue() isKindOfClass:_class];
2005 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2007 throw CYJSError(context, "incorrect number of arguments to Instance");
2009 id value(CYCastNSObject(&pool, context, arguments[0]));
2011 value = [NSNull null];
2012 return CYCastJSValue(context, [value cy$box]);
2015 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2016 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2019 id self(internal->GetValue());
2020 const char *name(CYPoolCString(pool, context, property));
2022 if (object_getInstanceVariable(self, name, NULL) != NULL)
2028 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2029 length = CYCastDouble(encoding + 1);
2033 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2034 for (size_t i(0); i != size; ++i)
2035 if (ivars[i] == ivar)
2037 else if (ivar_getOffset(ivars[i]) == offset) {
2038 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2039 _assert(encoding != NULL);
2040 _assert(encoding[0] == 'b');
2041 shift += CYCastDouble(encoding + 1);
2046 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2047 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2050 id self(internal->GetValue());
2051 const char *name(CYPoolCString(pool, context, property));
2053 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2054 ptrdiff_t offset(ivar_getOffset(ivar));
2055 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2057 const char *encoding(ivar_getTypeEncoding(ivar));
2058 _assert(encoding != NULL);
2059 _assert(encoding[0] != '\0');
2060 if (encoding[0] == 'b') {
2061 unsigned length, shift;
2062 CYBitField(length, shift, self, ivar, encoding, offset);
2063 _assert(shift + length <= sizeof(uintptr_t) * 8);
2064 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2065 uintptr_t mask((1 << length) - 1);
2066 return CYCastJSValue(context, (field >> shift) & mask);
2068 #if defined(__APPLE__) && defined(__LP64__)
2069 // XXX: maybe do even more verifications here
2070 if (strcmp(name, "isa") == 0)
2071 return CYCastJSValue(context, object_getClass(self));
2074 auto type(new(pool) Type_privateData(encoding));
2075 return CYFromFFI(context, type->type_, type->GetFFI(), data);
2082 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2083 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2086 id self(internal->GetValue());
2087 const char *name(CYPoolCString(pool, context, property));
2089 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2090 ptrdiff_t offset(ivar_getOffset(ivar));
2091 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2093 const char *encoding(ivar_getTypeEncoding(ivar));
2094 _assert(encoding != NULL);
2095 if (encoding[0] == 'b') {
2096 unsigned length, shift;
2097 CYBitField(length, shift, self, ivar, encoding, offset);
2098 _assert(shift + length <= sizeof(uintptr_t) * 8);
2099 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2100 uintptr_t mask((1 << length) - 1);
2101 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2103 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2104 CYPoolFFI(&pool, context, type->type_, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2112 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2113 if (Class super = class_getSuperclass(_class))
2114 Internal_getPropertyNames_(super, names);
2117 objc_ivar **data(class_copyIvarList(_class, &size));
2118 for (size_t i(0); i != size; ++i)
2119 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2123 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2124 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2127 id self(internal->GetValue());
2128 Class _class(object_getClass(self));
2130 Internal_getPropertyNames_(_class, names);
2133 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2134 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2135 return internal->GetOwner();
2138 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2140 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2143 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2145 NSString *name(CYCastNSString(&pool, context, property));
2146 if (Class _class = NSClassFromString(name))
2147 return CYMakeInstance(context, _class, Instance::Permanent);
2151 static Class *CYCopyClassList(size_t &size) {
2152 size = objc_getClassList(NULL, 0);
2153 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2156 size_t writ(objc_getClassList(data, size));
2162 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2173 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2175 if (Class *data = CYCopyClassList(size)) {
2176 for (size_t i(0); i != size; ++i)
2177 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2183 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2184 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2187 const char *name(CYPoolCString(pool, context, property));
2189 const char **data(objc_copyClassNamesForImage(internal, &size));
2191 for (size_t i(0); i != size; ++i)
2192 if (strcmp(name, data[i]) == 0) {
2193 if (Class _class = objc_getClass(name)) {
2194 value = CYMakeInstance(context, _class, Instance::Permanent);
2205 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2206 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2208 const char **data(objc_copyClassNamesForImage(internal, &size));
2209 for (size_t i(0); i != size; ++i)
2210 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2214 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2216 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2219 const char **data(objc_copyImageNames(&size));
2220 pool.atexit(free, data);
2222 for (size_t i(0); i != size; ++i)
2223 if (name == data[i]) {
2224 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2225 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2232 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2234 const char **data(objc_copyImageNames(&size));
2235 for (size_t i(0); i != size; ++i)
2236 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2241 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2243 const char *name(CYPoolCString(pool, context, property));
2244 if (Protocol *protocol = objc_getProtocol(name))
2245 return CYMakeInstance(context, protocol, Instance::Permanent);
2249 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2251 Protocol **data(objc_copyProtocolList(&size));
2252 for (size_t i(0); i != size; ++i)
2253 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2257 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2259 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2261 return CYJSNull(context);
2265 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2266 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2270 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2271 *data = reinterpret_cast<void *>(address);
2272 return KERN_SUCCESS;
2276 std::set<Class> query_;
2277 JSContextRef context_;
2278 JSObjectRef results_;
2281 struct CYObjectStruct {
2285 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2286 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2287 JSContextRef context(choice->context_);
2289 for (unsigned i(0); i != count; ++i) {
2290 vm_range_t &range(ranges[i]);
2291 void *data(reinterpret_cast<void *>(range.address));
2292 size_t size(range.size);
2294 if (size < sizeof(CYObjectStruct))
2297 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2298 #if defined(__APPLE__) && defined(__LP64__)
2299 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2301 Class isa(reinterpret_cast<Class>(pointers[0]));
2304 std::set<Class>::const_iterator result(choice->query_.find(isa));
2305 if (result == choice->query_.end())
2308 size_t needed(class_getInstanceSize(*result));
2309 // XXX: if (size < needed)
2311 size_t boundary(496);
2315 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2317 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2321 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2323 throw CYJSError(context, "choose() takes a class argument");
2325 CYGarbageCollect(context);
2328 id _class(CYCastNSObject(&pool, context, arguments[0]));
2330 vm_address_t *zones(NULL);
2332 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2333 _assert(error == KERN_SUCCESS);
2335 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2336 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2339 choice.context_ = context;
2340 choice.results_ = results;
2343 Class *classes(CYCopyClassList(number));
2344 _assert(classes != NULL);
2346 for (size_t i(0); i != number; ++i)
2347 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2348 if (current == _class) {
2349 choice.query_.insert(classes[i]);
2355 for (unsigned i(0); i != size; ++i) {
2356 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2357 if (zone == NULL || zone->introspect == NULL)
2360 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2368 #if defined(__i386__) || defined(__x86_64__)
2369 #define OBJC_MAX_STRUCT_BY_VALUE 8
2370 static int struct_forward_array[] = {
2371 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2372 #elif defined(__arm__)
2373 #define OBJC_MAX_STRUCT_BY_VALUE 1
2374 static int struct_forward_array[] = {
2376 #elif defined(__arm64__)
2379 #error missing objc-runtime-info
2383 static bool stret(ffi_type *ffi_type) {
2384 return ffi_type->type == FFI_TYPE_STRUCT && (
2385 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2386 struct_forward_array[ffi_type->size] != 0
2394 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2398 _class = object_getClass(self);
2402 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2403 imp = method_getImplementation(method);
2404 type = method_getTypeEncoding(method);
2409 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2410 type = CYPoolCString(pool, context, [method _typeString]);
2416 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2423 sig::Signature signature;
2424 sig::Parse(pool, &signature, type, &Structor_);
2426 size_t used(count + 3);
2427 if (used > signature.count) {
2428 sig::Element *elements(new (pool) sig::Element[used]);
2429 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2431 for (size_t index(signature.count); index != used; ++index) {
2432 sig::Element *element(&elements[index]);
2433 element->name = NULL;
2434 element->offset = _not(size_t);
2436 sig::Type *type(new (pool) sig::Type);
2437 memset(type, 0, sizeof(*type));
2438 type->primitive = sig::object_P;
2439 element->type = type;
2442 signature.elements = elements;
2443 signature.count = used;
2447 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2451 if (stret(cif.rtype))
2452 imp = class_getMethodImplementation_stret(_class, _cmd);
2455 imp = class_getMethodImplementation(_class, _cmd);
2458 void (*function)() = reinterpret_cast<void (*)()>(imp);
2459 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2462 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2464 throw CYJSError(context, "too few arguments to objc_msgSend");
2474 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2475 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2476 self = internal->GetValue();
2477 _class = internal->class_;;
2478 uninitialized = false;
2479 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2480 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2481 self = internal->GetValue();
2483 uninitialized = internal->IsUninitialized();
2485 internal->value_ = nil;
2487 self = CYCastNSObject(&pool, context, arguments[0]);
2489 uninitialized = false;
2493 return CYJSNull(context);
2495 _cmd = CYCastSEL(context, arguments[1]);
2497 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2500 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2501 return $objc_msgSend(context, object, _this, count, arguments);
2504 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2505 JSValueRef setup[count + 2];
2508 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2509 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2512 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2514 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2516 // XXX: handle Instance::Uninitialized?
2517 id self(CYCastNSObject(&pool, context, _this));
2521 setup[1] = &internal->sel_;
2523 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2526 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2528 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2530 id self(CYCastNSObject(&pool, context, arguments[0]));
2531 Class _class(CYCastClass(pool, context, arguments[1]));
2532 return cy::Super::Make(context, self, _class);
2535 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2537 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2539 const char *name(CYPoolCString(pool, context, arguments[0]));
2540 return CYMakeSelector(context, sel_registerName(name));
2543 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2545 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2546 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2549 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2550 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2551 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2554 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2555 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2556 Type_privateData *typical(internal->GetType());
2561 if (typical == NULL) {
2565 type = typical->type_;
2566 ffi = typical->ffi_;
2569 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2572 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2573 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2575 sig::Signature *signature(CYBlockSignature(pool, internal->GetValue()));
2576 if (signature == NULL)
2577 return CYJSNull(context);
2578 return CYMakeType(context, signature);
2581 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2582 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2583 return CYMakeInstance(context, object_getClass(internal->GetValue()), Instance::Permanent);
2586 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2587 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2588 id self(internal->GetValue());
2589 if (!CYIsClass(self))
2590 return CYJSUndefined(context);
2591 return CYGetClassPrototype(context, self);
2594 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2595 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2596 id self(internal->GetValue());
2597 if (!CYIsClass(self))
2598 return CYJSUndefined(context);
2599 return Messages::Make(context, (Class) self);
2602 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2603 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2605 if (!CYJSValueIsNSObject(context, _this))
2608 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2609 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2612 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2613 if (!CYJSValueIsNSObject(context, _this))
2616 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2617 id value(internal->GetValue());
2624 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2626 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2627 return CYJSUndefined(context);
2628 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2631 return CYCastJSValue(context, CYJSString(context, [value description]));
2633 } CYCatch(NULL) return /*XXX*/ NULL; }
2635 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2636 if (!CYJSValueIsNSObject(context, _this))
2639 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2640 id value(internal->GetValue());
2641 _assert(value != nil);
2643 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2646 if (JSValueRef result = [value cy$valueOfInContext:context])
2650 } CYCatch(NULL) return /*XXX*/ NULL; }
2652 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2653 if (!CYJSValueIsNSObject(context, _this))
2656 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2657 // XXX: but... but... THIS ISN'T A POINTER! :(
2658 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2659 } CYCatch(NULL) return /*XXX*/ NULL; }
2661 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2662 if (!CYJSValueIsNSObject(context, _this))
2665 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2666 id value(internal->GetValue());
2669 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2670 return CYCastJSValue(context, CYJSString(context, [value description]));
2672 } CYCatch(NULL) return /*XXX*/ NULL; }
2674 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2675 if (!CYJSValueIsNSObject(context, _this))
2678 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2679 id value(internal->GetValue());
2681 if (!CYIsClass(value))
2682 CYThrow("non-Class object cannot be used as Type");
2685 memset(&type, 0, sizeof(type));
2686 type.primitive = sig::object_P;
2687 type.name = class_getName(value);
2688 return CYMakeType(context, &type);
2689 } CYCatch(NULL) return /*XXX*/ NULL; }
2691 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2692 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2693 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2696 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2697 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2700 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2701 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2702 const char *name(sel_getName(internal->GetValue()));
2705 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2706 return CYCastJSValue(context, CYJSString(context, string));
2708 } CYCatch(NULL) return /*XXX*/ NULL; }
2710 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2712 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2715 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2716 SEL sel(internal->GetValue());
2718 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2719 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2720 const char *encoding(method_getTypeEncoding(method));
2722 sig::Signature signature;
2723 sig::Parse(pool, &signature, encoding, &Structor_);
2724 return CYMakeType(context, &signature);
2727 static JSStaticValue Selector_staticValues[2] = {
2728 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2729 {NULL, NULL, NULL, 0}
2732 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2733 static JSStaticValue Instance_staticValues[5] = {
2734 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2735 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2736 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2737 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2738 {NULL, NULL, NULL, 0}
2741 static JSStaticValue FunctionInstance_staticValues[6] = {
2742 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2743 // XXX: this is sadly a duplicate of Instance_staticValues
2744 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2745 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2746 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2747 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2748 {NULL, NULL, NULL, 0}
2751 static JSStaticFunction Instance_staticFunctions[7] = {
2752 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2753 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2754 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2755 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2756 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2757 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2761 static JSStaticFunction Class_staticFunctions[2] = {
2762 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2766 static JSStaticFunction Internal_staticFunctions[2] = {
2767 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2771 static JSStaticFunction Selector_staticFunctions[5] = {
2772 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2773 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2774 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2775 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2780 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2781 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2782 } CYObjectiveCatch }
2785 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2786 CYPool &pool(CYGetGlobalPool());
2788 Object_type = new(pool) Type_privateData(sig::object_P);
2789 Selector_type = new(pool) Type_privateData(sig::selector_P);
2791 NSArray_ = objc_getClass("NSArray");
2792 NSBlock_ = objc_getClass("NSBlock");
2793 NSDictionary_ = objc_getClass("NSDictionary");
2794 NSNumber_ = objc_getClass("NSNumber");
2795 NSString_ = objc_getClass("NSString");
2796 Object_ = objc_getClass("Object");
2799 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2801 // XXX: apparently, iOS now has both of these
2802 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2803 if (NSCFBoolean_ == nil)
2804 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2806 NSCFType_ = objc_getClass("NSCFType");
2808 NSZombie_ = objc_getClass("_NSZombie_");
2810 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2811 NSZombie_ = objc_getClass("NSZombie");
2814 JSClassDefinition definition;
2816 definition = kJSClassDefinitionEmpty;
2817 definition.className = "Instance";
2818 definition.staticValues = Instance_staticValues;
2819 definition.staticFunctions = Instance_staticFunctions;
2820 definition.hasProperty = &Instance_hasProperty;
2821 definition.getProperty = &Instance_getProperty;
2822 definition.setProperty = &Instance_setProperty;
2823 definition.deleteProperty = &Instance_deleteProperty;
2824 definition.getPropertyNames = &Instance_getPropertyNames;
2825 definition.callAsConstructor = &Instance_callAsConstructor;
2826 definition.hasInstance = &Instance_hasInstance;
2827 definition.finalize = &CYFinalize;
2828 Instance_ = JSClassCreate(&definition);
2830 definition.className = "ArrayInstance";
2831 ArrayInstance_ = JSClassCreate(&definition);
2833 definition.className = "BooleanInstance";
2834 BooleanInstance_ = JSClassCreate(&definition);
2836 definition.className = "NumberInstance";
2837 NumberInstance_ = JSClassCreate(&definition);
2839 definition.className = "ObjectInstance";
2840 ObjectInstance_ = JSClassCreate(&definition);
2842 definition.className = "StringInstance";
2843 StringInstance_ = JSClassCreate(&definition);
2845 definition.className = "FunctionInstance";
2846 definition.staticValues = FunctionInstance_staticValues;
2847 definition.callAsFunction = &FunctionInstance_callAsFunction;
2848 FunctionInstance_ = JSClassCreate(&definition);
2850 definition = kJSClassDefinitionEmpty;
2851 definition.className = "Class";
2852 definition.staticFunctions = Class_staticFunctions;
2853 Class_ = JSClassCreate(&definition);
2855 definition = kJSClassDefinitionEmpty;
2856 definition.className = "Internal";
2857 definition.staticFunctions = Internal_staticFunctions;
2858 definition.hasProperty = &Internal_hasProperty;
2859 definition.getProperty = &Internal_getProperty;
2860 definition.setProperty = &Internal_setProperty;
2861 definition.getPropertyNames = &Internal_getPropertyNames;
2862 definition.finalize = &CYFinalize;
2863 Internal_ = JSClassCreate(&definition);
2865 definition = kJSClassDefinitionEmpty;
2866 definition.className = "Message";
2867 definition.staticFunctions = cy::Functor::StaticFunctions;
2868 definition.staticValues = cy::Functor::StaticValues;
2869 definition.callAsFunction = &Message_callAsFunction;
2870 definition.finalize = &CYFinalize;
2871 Message_ = JSClassCreate(&definition);
2873 definition = kJSClassDefinitionEmpty;
2874 definition.className = "Messages";
2875 definition.hasProperty = &Messages_hasProperty;
2876 definition.getProperty = &Messages_getProperty;
2877 definition.setProperty = &Messages_setProperty;
2878 definition.getPropertyNames = &Messages_getPropertyNames;
2879 definition.finalize = &CYFinalize;
2880 Messages_ = JSClassCreate(&definition);
2882 definition = kJSClassDefinitionEmpty;
2883 definition.className = "Selector";
2884 definition.staticValues = Selector_staticValues;
2885 definition.staticFunctions = Selector_staticFunctions;
2886 definition.callAsFunction = &Selector_callAsFunction;
2887 definition.finalize = &CYFinalize;
2888 Selector_ = JSClassCreate(&definition);
2890 definition = kJSClassDefinitionEmpty;
2891 definition.className = "Super";
2892 definition.staticFunctions = Internal_staticFunctions;
2893 definition.finalize = &CYFinalize;
2894 Super_ = JSClassCreate(&definition);
2896 definition = kJSClassDefinitionEmpty;
2897 definition.className = "ObjectiveC::Classes";
2898 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2899 definition.getProperty = &ObjectiveC_Classes_getProperty;
2900 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2901 ObjectiveC_Classes_ = JSClassCreate(&definition);
2903 definition = kJSClassDefinitionEmpty;
2904 definition.className = "ObjectiveC::Constants";
2905 definition.getProperty = &ObjectiveC_Constants_getProperty;
2906 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2907 ObjectiveC_Constants_ = JSClassCreate(&definition);
2910 definition = kJSClassDefinitionEmpty;
2911 definition.className = "ObjectiveC::Images";
2912 definition.getProperty = &ObjectiveC_Images_getProperty;
2913 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2914 ObjectiveC_Images_ = JSClassCreate(&definition);
2916 definition = kJSClassDefinitionEmpty;
2917 definition.className = "ObjectiveC::Image::Classes";
2918 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2919 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2920 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2923 definition = kJSClassDefinitionEmpty;
2924 definition.className = "ObjectiveC::Protocols";
2925 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2926 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2927 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2930 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2931 // XXX: this is horrible; there has to be a better way to do this
2933 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2935 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2941 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2942 JSObjectRef global(CYGetGlobalObject(context));
2943 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2944 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2945 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2946 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2948 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2949 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2951 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2952 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2953 CYArrayPush(context, alls, protocols);
2955 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2956 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2957 CYArrayPush(context, alls, classes);
2959 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2960 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2961 CYArrayPush(context, alls, constants);
2964 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2967 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2968 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2969 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2970 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2971 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2973 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2974 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2976 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2977 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2978 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2979 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2980 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2982 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2983 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2984 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2985 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2986 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2988 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2989 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2990 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2991 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2992 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2994 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2995 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2996 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2997 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2998 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
3000 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3001 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3002 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3003 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3004 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3006 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3007 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3008 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3009 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3010 CYSetPrototype(context, StringInstance_prototype, String_prototype);
3012 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
3013 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
3014 CYSetPrototype(context, Class_prototype, Instance_prototype);
3016 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3017 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3018 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3020 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3021 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3024 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3027 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3029 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3030 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3032 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
3033 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
3034 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
3035 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::object_P), kJSPropertyAttributeDontEnum);
3036 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::typename_P), kJSPropertyAttributeDontEnum);
3037 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::selector_P), kJSPropertyAttributeDontEnum);
3040 static void *CYObjectiveC_CastSymbol(const char *name) {
3042 #ifdef __GNU_LIBOBJC__
3043 else if (strcmp(name, "object_getClass") == 0)
3044 return reinterpret_cast<void *>(&object_getClass);
3049 static CYHook CYObjectiveCHook = {
3050 &CYObjectiveC_ExecuteStart,
3051 &CYObjectiveC_ExecuteEnd,
3052 &CYObjectiveC_CallFunction,
3053 &CYObjectiveC_Initialize,
3054 &CYObjectiveC_SetupContext,
3055 &CYObjectiveC_PoolFFI,
3056 &CYObjectiveC_FromFFI,
3057 &CYObjectiveC_CastSymbol,
3060 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3062 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3063 CYSetupContext(context);
3064 } CYObjectiveCatch }
3066 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3069 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3070 utf8 = CYPoolCode(pool, utf8);
3072 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3073 size_t bytes(utf16.size * sizeof(uint16_t));
3074 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3075 memcpy(copy, utf16.data, bytes);
3079 } catch (const CYException &exception) {
3081 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];