1 /* Cycript - Remove Execution Server and Disassembler
2 * Copyright (C) 2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 #include <substrate.h>
43 #include "cycript.hpp"
45 #include "sig/parse.hpp"
46 #include "sig/ffi_type.hpp"
48 #include "Pooling.hpp"
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <CoreFoundation/CFLogUtilities.h>
54 #include <WebKit/WebScriptObject.h>
59 #include <ext/stdio_filebuf.h>
67 #include "Cycript.tab.hh"
69 #include <apr-1/apr_thread_proc.h>
74 #define _assert(test) do { \
76 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
79 #define _trace() do { \
80 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
85 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
87 #define CYPoolCatch(value) \
88 @catch (NSException *error) { \
89 _saved = [error retain]; \
95 [_saved autorelease]; \
99 void CYThrow(JSContextRef context, JSValueRef value);
101 /* JavaScript Properties {{{ */
102 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
103 JSValueRef exception(NULL);
104 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
105 CYThrow(context, exception);
109 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
110 JSValueRef exception(NULL);
111 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
112 CYThrow(context, exception);
116 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
117 JSValueRef exception(NULL);
118 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
119 CYThrow(context, exception);
122 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
123 JSValueRef exception(NULL);
124 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
125 CYThrow(context, exception);
128 /* JavaScript Strings {{{ */
129 JSStringRef CYCopyJSString(id value) {
130 // XXX: this definition scares me; is anyone using this?!
131 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
134 JSStringRef CYCopyJSString(const char *value) {
135 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
138 JSStringRef CYCopyJSString(JSStringRef value) {
139 return value == NULL ? NULL : JSStringRetain(value);
142 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
143 if (JSValueIsNull(context, value))
145 JSValueRef exception(NULL);
146 JSStringRef string(JSValueToStringCopy(context, value, &exception));
147 CYThrow(context, exception);
157 JSStringRelease(string_);
161 CYJSString(const CYJSString &rhs) :
162 string_(CYCopyJSString(rhs.string_))
166 template <typename Arg0_>
167 CYJSString(Arg0_ arg0) :
168 string_(CYCopyJSString(arg0))
172 template <typename Arg0_, typename Arg1_>
173 CYJSString(Arg0_ arg0, Arg1_ arg1) :
174 string_(CYCopyJSString(arg0, arg1))
178 CYJSString &operator =(const CYJSString &rhs) {
180 string_ = CYCopyJSString(rhs.string_);
193 operator JSStringRef() const {
198 CFStringRef CYCopyCFString(JSStringRef value) {
199 return JSStringCopyCFString(kCFAllocatorDefault, value);
202 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
203 return CYCopyCFString(CYJSString(context, value));
208 static JSGlobalContextRef Context_;
209 static JSObjectRef System_;
210 static JSObjectRef ObjectiveC_;
212 static JSClassRef Functor_;
213 static JSClassRef Instance_;
214 static JSClassRef Internal_;
215 static JSClassRef Message_;
216 static JSClassRef Messages_;
217 static JSClassRef NSArrayPrototype_;
218 static JSClassRef Pointer_;
219 static JSClassRef Runtime_;
220 static JSClassRef Selector_;
221 static JSClassRef Struct_;
222 static JSClassRef Type_;
224 static JSClassRef ObjectiveC_Classes_;
225 static JSClassRef ObjectiveC_Image_Classes_;
226 static JSClassRef ObjectiveC_Images_;
227 static JSClassRef ObjectiveC_Protocols_;
229 static JSObjectRef Array_;
230 static JSObjectRef Function_;
231 static JSObjectRef String_;
233 static JSStringRef Result_;
235 static JSStringRef length_;
236 static JSStringRef message_;
237 static JSStringRef name_;
238 static JSStringRef prototype_;
239 static JSStringRef toCYON_;
240 static JSStringRef toJSON_;
242 static JSObjectRef Instance_prototype_;
243 static JSObjectRef Object_prototype_;
245 static JSObjectRef Array_prototype_;
246 static JSObjectRef Array_pop_;
247 static JSObjectRef Array_push_;
248 static JSObjectRef Array_splice_;
250 static Class NSArray_;
251 static Class NSCFBoolean_;
252 static Class NSCFType_;
253 static Class NSDictionary_;
254 static Class NSMessageBuilder_;
255 static Class NSZombie_;
256 static Class Object_;
258 static NSArray *Bridge_;
260 static void Finalize(JSObjectRef object) {
261 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
264 class Type_privateData;
274 CYValue(void *value) :
279 CYValue(const CYValue &rhs) :
284 virtual Type_privateData *GetType() const {
289 struct Selector_privateData :
292 Selector_privateData(SEL value) :
297 SEL GetValue() const {
298 return reinterpret_cast<SEL>(value_);
301 virtual Type_privateData *GetType() const;
304 // XXX: trick this out with associated objects!
305 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
307 return Instance_prototype_;
309 // XXX: I need to think through multi-context
310 typedef std::map<Class, JSValueRef> CacheMap;
311 static CacheMap cache_;
313 JSValueRef &value(cache_[self]);
317 JSClassRef _class(NULL);
318 JSValueRef prototype;
320 if (self == NSArray_)
321 prototype = Array_prototype_;
322 else if (self == NSDictionary_)
323 prototype = Object_prototype_;
325 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
327 JSObjectRef object(JSObjectMake(context, _class, NULL));
328 JSObjectSetPrototype(context, object, prototype);
330 JSValueProtect(context, object);
340 Transient = (1 << 0),
341 Uninitialized = (1 << 1),
346 Instance(id value, Flags flags) :
352 virtual ~Instance() {
353 if ((flags_ & Transient) == 0)
354 // XXX: does this handle background threads correctly?
355 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
358 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
359 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
360 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object == nil ? nil : object_getClass(object)));
364 id GetValue() const {
365 return reinterpret_cast<id>(value_);
368 bool IsUninitialized() const {
369 return (flags_ & Uninitialized) != 0;
372 virtual Type_privateData *GetType() const;
378 Messages(Class value) :
383 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
384 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
385 if (_class == NSArray_)
387 if (Class super = class_getSuperclass(_class))
388 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
390 JSObjectSetPrototype(context, value, Array_prototype_);*/
394 Class GetValue() const {
395 return reinterpret_cast<Class>(value_);
403 JSContextRef context_;
407 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
412 JSValueProtect(context_, owner_);
416 JSValueUnprotect(context_, owner_);
419 JSObjectRef GetOwner() const {
427 Internal(id value, JSContextRef context, JSObjectRef owner) :
428 CYOwned(value, context, owner)
432 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
433 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
436 id GetValue() const {
437 return reinterpret_cast<id>(value_);
443 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
445 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
446 lhs.name = apr_pstrdup(pool, rhs.name);
447 if (rhs.type == NULL)
450 lhs.type = new(pool) Type;
451 Copy(pool, *lhs.type, *rhs.type);
453 lhs.offset = rhs.offset;
456 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
457 size_t count(rhs.count);
459 lhs.elements = new(pool) Element[count];
460 for (size_t index(0); index != count; ++index)
461 Copy(pool, lhs.elements[index], rhs.elements[index]);
464 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
465 lhs.primitive = rhs.primitive;
466 lhs.name = apr_pstrdup(pool, rhs.name);
467 lhs.flags = rhs.flags;
469 if (sig::IsAggregate(rhs.primitive))
470 Copy(pool, lhs.data.signature, rhs.data.signature);
472 if (rhs.data.data.type != NULL) {
473 lhs.data.data.type = new(pool) Type;
474 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
477 lhs.data.data.size = rhs.data.data.size;
481 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
483 lhs.alignment = rhs.alignment;
485 if (rhs.elements == NULL)
489 while (rhs.elements[count] != NULL)
492 lhs.elements = new(pool) ffi_type *[count + 1];
493 lhs.elements[count] = NULL;
495 for (size_t index(0); index != count; ++index) {
496 // XXX: if these are libffi native then you can just take them
497 ffi_type *ffi(new(pool) ffi_type);
498 lhs.elements[index] = ffi;
499 sig::Copy(pool, *ffi, *rhs.elements[index]);
506 struct CStringMapLess :
507 std::binary_function<const char *, const char *, bool>
509 _finline bool operator ()(const char *lhs, const char *rhs) const {
510 return strcmp(lhs, rhs) < 0;
514 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
519 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
520 switch ([[entry objectAtIndex:0] intValue]) {
522 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
526 sig::Signature signature;
527 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
528 type = signature.elements[0].type;
534 struct Type_privateData :
537 static Type_privateData *Object;
538 static Type_privateData *Selector;
543 void Set(sig::Type *type) {
544 type_ = new(pool_) sig::Type;
545 sig::Copy(pool_, *type_, *type);
548 Type_privateData(apr_pool_t *pool, const char *type) :
554 sig::Signature signature;
555 sig::Parse(pool_, &signature, type, &Structor_);
556 type_ = signature.elements[0].type;
559 Type_privateData(sig::Type *type) :
566 Type_privateData(sig::Type *type, ffi_type *ffi) {
567 ffi_ = new(pool_) ffi_type;
568 sig::Copy(pool_, *ffi_, *ffi);
574 ffi_ = new(pool_) ffi_type;
576 sig::Element element;
578 element.type = type_;
581 sig::Signature signature;
582 signature.elements = &element;
586 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
594 Type_privateData *Type_privateData::Object;
595 Type_privateData *Type_privateData::Selector;
597 Type_privateData *Instance::GetType() const {
598 return Type_privateData::Object;
601 Type_privateData *Selector_privateData::GetType() const {
602 return Type_privateData::Selector;
608 Type_privateData *type_;
610 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
611 CYOwned(value, context, owner),
612 type_(new(pool_) Type_privateData(type))
617 struct Struct_privateData :
620 Type_privateData *type_;
622 Struct_privateData(JSContextRef context, JSObjectRef owner) :
623 CYOwned(NULL, context, owner)
628 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
629 static TypeMap Types_;
631 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
632 Struct_privateData *internal(new Struct_privateData(context, owner));
633 apr_pool_t *pool(internal->pool_);
634 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
635 internal->type_ = typical;
638 internal->value_ = data;
640 size_t size(typical->GetFFI()->size);
641 void *copy(apr_palloc(internal->pool_, size));
642 memcpy(copy, data, size);
643 internal->value_ = copy;
646 return JSObjectMake(context, Struct_, internal);
649 struct Functor_privateData :
652 sig::Signature signature_;
656 Functor_privateData(const char *type, void (*value)()) :
657 CYValue(reinterpret_cast<void *>(value))
659 sig::Parse(pool_, &signature_, type, &Structor_);
660 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
663 void (*GetValue())() const {
664 return reinterpret_cast<void (*)()>(value_);
668 struct Closure_privateData :
671 JSContextRef context_;
672 JSObjectRef function_;
674 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
675 Functor_privateData(type, NULL),
679 JSValueProtect(context_, function_);
682 virtual ~Closure_privateData() {
683 JSValueUnprotect(context_, function_);
687 struct Message_privateData :
692 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
693 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
699 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
700 Instance::Flags flags;
703 flags = Instance::Transient;
705 flags = Instance::None;
706 object = [object retain];
709 return Instance::Make(context, object, flags);
712 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
714 return [value UTF8String];
716 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
717 char *string(new(pool) char[size]);
718 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
719 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
724 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
725 return JSValueMakeBoolean(context, value);
728 JSValueRef CYCastJSValue(JSContextRef context, double value) {
729 return JSValueMakeNumber(context, value);
732 #define CYCastJSValue_(Type_) \
733 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
734 return JSValueMakeNumber(context, static_cast<double>(value)); \
738 CYCastJSValue_(unsigned int)
739 CYCastJSValue_(long int)
740 CYCastJSValue_(long unsigned int)
741 CYCastJSValue_(long long int)
742 CYCastJSValue_(long long unsigned int)
744 JSValueRef CYJSUndefined(JSContextRef context) {
745 return JSValueMakeUndefined(context);
748 size_t CYGetIndex(const char *value) {
749 if (value[0] != '0') {
751 size_t index(strtoul(value, &end, 10));
752 if (value + strlen(value) == end)
754 } else if (value[1] == '\0')
760 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value);
762 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
763 return CYGetIndex(CYPoolCString(pool, value));
766 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
767 return CYGetIndex(CYPoolCString(pool, value));
770 bool CYGetOffset(const char *value, ssize_t &index) {
771 if (value[0] != '0') {
773 index = strtol(value, &end, 10);
774 if (value + strlen(value) == end)
776 } else if (value[1] == '\0') {
784 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
785 return CYGetOffset(CYPoolCString(pool, value), index);
788 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
790 @interface NSMethodSignature (Cycript)
791 - (NSString *) _typeString;
794 @interface NSObject (Cycript)
796 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
797 - (JSType) cy$JSType;
799 - (NSObject *) cy$toJSON:(NSString *)key;
800 - (NSString *) cy$toCYON;
801 - (NSString *) cy$toKey;
803 - (bool) cy$hasProperty:(NSString *)name;
804 - (NSObject *) cy$getProperty:(NSString *)name;
805 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
806 - (bool) cy$deleteProperty:(NSString *)name;
811 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
814 @interface NSString (Cycript)
815 - (void *) cy$symbol;
818 struct PropertyAttributes {
823 const char *variable;
836 PropertyAttributes(objc_property_t property) :
848 name = property_getName(property);
849 const char *attributes(property_getAttributes(property));
851 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
853 case 'R': readonly = true; break;
854 case 'C': copy = true; break;
855 case '&': retain = true; break;
856 case 'N': nonatomic = true; break;
857 case 'G': getter_ = token + 1; break;
858 case 'S': setter_ = token + 1; break;
859 case 'V': variable = token + 1; break;
863 /*if (variable == NULL) {
864 variable = property_getName(property);
865 size_t size(strlen(variable));
866 char *name(new(pool_) char[size + 2]);
868 memcpy(name + 1, variable, size);
869 name[size + 1] = '\0';
874 const char *Getter() {
876 getter_ = apr_pstrdup(pool_, name);
880 const char *Setter() {
881 if (setter_ == NULL && !readonly) {
882 size_t length(strlen(name));
884 char *temp(new(pool_) char[length + 5]);
890 temp[3] = toupper(name[0]);
891 memcpy(temp + 4, name + 1, length - 1);
894 temp[length + 3] = ':';
895 temp[length + 4] = '\0';
904 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
905 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
908 /* Bridge: NSArray {{{ */
909 @implementation NSArray (Cycript)
911 - (NSString *) cy$toCYON {
912 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
913 [json appendString:@"["];
916 for (id object in self) {
918 [json appendString:@","];
921 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
922 [json appendString:CYPoolNSCYON(NULL, object)];
924 [json appendString:@","];
929 [json appendString:@"]"];
933 - (bool) cy$hasProperty:(NSString *)name {
934 if ([name isEqualToString:@"length"])
937 size_t index(CYGetIndex(NULL, name));
938 if (index == _not(size_t) || index >= [self count])
939 return [super cy$hasProperty:name];
944 - (NSObject *) cy$getProperty:(NSString *)name {
945 if ([name isEqualToString:@"length"])
946 return [NSNumber numberWithUnsignedInteger:[self count]];
948 size_t index(CYGetIndex(NULL, name));
949 if (index == _not(size_t) || index >= [self count])
950 return [super cy$getProperty:name];
952 return [self objectAtIndex:index];
957 /* Bridge: NSDictionary {{{ */
958 @implementation NSDictionary (Cycript)
960 - (NSString *) cy$toCYON {
961 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
962 [json appendString:@"{"];
965 for (id key in self) {
967 [json appendString:@","];
970 [json appendString:[key cy$toKey]];
971 [json appendString:@":"];
972 NSObject *object([self objectForKey:key]);
973 [json appendString:CYPoolNSCYON(NULL, object)];
976 [json appendString:@"}"];
980 - (bool) cy$hasProperty:(NSString *)name {
981 return [self objectForKey:name] != nil;
984 - (NSObject *) cy$getProperty:(NSString *)name {
985 return [self objectForKey:name];
990 /* Bridge: NSMutableArray {{{ */
991 @implementation NSMutableArray (Cycript)
993 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
994 if ([name isEqualToString:@"length"]) {
995 // XXX: is this not intelligent?
996 NSUInteger size([(NSNumber *)value unsignedIntegerValue]);
997 NSUInteger count([self count]);
999 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1000 else if (size != count) {
1001 WebUndefined *undefined([WebUndefined undefined]);
1002 for (size_t i(count); i != size; ++i)
1003 [self addObject:undefined];
1008 size_t index(CYGetIndex(NULL, name));
1009 if (index == _not(size_t))
1010 return [super cy$setProperty:name to:value];
1012 id object(value ?: [NSNull null]);
1014 size_t count([self count]);
1016 [self replaceObjectAtIndex:index withObject:object];
1018 if (index != count) {
1019 WebUndefined *undefined([WebUndefined undefined]);
1020 for (size_t i(count); i != index; ++i)
1021 [self addObject:undefined];
1024 [self addObject:object];
1030 - (bool) cy$deleteProperty:(NSString *)name {
1031 size_t index(CYGetIndex(NULL, name));
1032 if (index == _not(size_t) || index >= [self count])
1033 return [super cy$deleteProperty:name];
1034 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1040 /* Bridge: NSMutableDictionary {{{ */
1041 @implementation NSMutableDictionary (Cycript)
1043 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1044 [self setObject:(value ?: [NSNull null]) forKey:name];
1048 - (bool) cy$deleteProperty:(NSString *)name {
1049 if ([self objectForKey:name] == nil)
1052 [self removeObjectForKey:name];
1059 /* Bridge: NSNumber {{{ */
1060 @implementation NSNumber (Cycript)
1062 - (JSType) cy$JSType {
1063 // XXX: this just seems stupid
1064 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
1067 - (NSObject *) cy$toJSON:(NSString *)key {
1071 - (NSString *) cy$toCYON {
1072 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1075 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1076 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1081 /* Bridge: NSNull {{{ */
1082 @implementation NSNull (Cycript)
1084 - (JSType) cy$JSType {
1088 - (NSObject *) cy$toJSON:(NSString *)key {
1092 - (NSString *) cy$toCYON {
1098 /* Bridge: NSObject {{{ */
1099 @implementation NSObject (Cycript)
1101 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1102 return CYMakeInstance(context, self, false);
1105 - (JSType) cy$JSType {
1106 return kJSTypeObject;
1109 - (NSObject *) cy$toJSON:(NSString *)key {
1110 return [self description];
1113 - (NSString *) cy$toCYON {
1114 return [[self cy$toJSON:@""] cy$toCYON];
1117 - (NSString *) cy$toKey {
1118 return [self cy$toCYON];
1121 - (bool) cy$hasProperty:(NSString *)name {
1125 - (NSObject *) cy$getProperty:(NSString *)name {
1129 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1133 - (bool) cy$deleteProperty:(NSString *)name {
1139 /* Bridge: NSProxy {{{ */
1140 @implementation NSProxy (Cycript)
1142 - (NSObject *) cy$toJSON:(NSString *)key {
1143 return [self description];
1146 - (NSString *) cy$toCYON {
1147 return [[self cy$toJSON:@""] cy$toCYON];
1152 /* Bridge: NSString {{{ */
1153 @implementation NSString (Cycript)
1155 - (JSType) cy$JSType {
1156 return kJSTypeString;
1159 - (NSObject *) cy$toJSON:(NSString *)key {
1163 - (NSString *) cy$toCYON {
1164 // XXX: this should use the better code from Output.cpp
1165 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
1167 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
1168 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
1169 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
1170 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
1171 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
1173 CFStringInsert(json, 0, CFSTR("\""));
1174 CFStringAppend(json, CFSTR("\""));
1176 return [reinterpret_cast<const NSString *>(json) autorelease];
1179 - (NSString *) cy$toKey {
1180 const char *value([self UTF8String]);
1181 size_t size(strlen(value));
1186 if (DigitRange_[value[0]]) {
1187 size_t index(CYGetIndex(NULL, self));
1188 if (index == _not(size_t))
1191 if (!WordStartRange_[value[0]])
1193 for (size_t i(1); i != size; ++i)
1194 if (!WordEndRange_[value[i]])
1201 return [self cy$toCYON];
1204 - (void *) cy$symbol {
1206 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1211 /* Bridge: WebUndefined {{{ */
1212 @implementation WebUndefined (Cycript)
1214 - (JSType) cy$JSType {
1215 return kJSTypeUndefined;
1218 - (NSObject *) cy$toJSON:(NSString *)key {
1222 - (NSString *) cy$toCYON {
1223 return @"undefined";
1226 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1227 return CYJSUndefined(context);
1233 @interface CYJSObject : NSMutableDictionary {
1234 JSObjectRef object_;
1235 JSContextRef context_;
1238 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1240 - (NSString *) cy$toJSON:(NSString *)key;
1242 - (NSUInteger) count;
1243 - (id) objectForKey:(id)key;
1244 - (NSEnumerator *) keyEnumerator;
1245 - (void) setObject:(id)object forKey:(id)key;
1246 - (void) removeObjectForKey:(id)key;
1250 @interface CYJSArray : NSMutableArray {
1251 JSObjectRef object_;
1252 JSContextRef context_;
1255 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1257 - (NSUInteger) count;
1258 - (id) objectAtIndex:(NSUInteger)index;
1260 - (void) addObject:(id)anObject;
1261 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1262 - (void) removeLastObject;
1263 - (void) removeObjectAtIndex:(NSUInteger)index;
1264 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1268 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1269 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1270 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1275 @catch (id error) { \
1276 CYThrow(context, error, exception); \
1280 apr_status_t CYPoolRelease_(void *data) {
1281 id object(reinterpret_cast<id>(data));
1286 id CYPoolRelease(apr_pool_t *pool, id object) {
1289 else if (pool == NULL)
1290 return [object autorelease];
1292 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1297 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1298 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1301 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1302 JSValueRef exception(NULL);
1303 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1304 CYThrow(context, exception);
1305 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1306 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1309 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1310 if (!JSValueIsObjectOfClass(context, object, Instance_))
1311 return CYCastNSObject_(pool, context, object);
1313 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1314 return internal->GetValue();
1318 double CYCastDouble(const char *value, size_t size) {
1320 double number(strtod(value, &end));
1321 if (end != value + size)
1326 double CYCastDouble(const char *value) {
1327 return CYCastDouble(value, strlen(value));
1330 double CYCastDouble(JSContextRef context, JSValueRef value) {
1331 JSValueRef exception(NULL);
1332 double number(JSValueToNumber(context, value, &exception));
1333 CYThrow(context, exception);
1337 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1338 double number(CYCastDouble(context, value));
1339 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1342 CFStringRef CYCopyCFString(const char *value) {
1343 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1346 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1347 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1350 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1351 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1354 bool CYCastBool(JSContextRef context, JSValueRef value) {
1355 return JSValueToBoolean(context, value);
1358 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1362 switch (JSType type = JSValueGetType(context, value)) {
1363 case kJSTypeUndefined:
1364 object = [WebUndefined undefined];
1372 case kJSTypeBoolean:
1373 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1378 object = CYCopyCFNumber(context, value);
1383 object = CYCopyCFString(context, value);
1388 // XXX: this might could be more efficient
1389 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1394 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1401 return CYPoolRelease(pool, object);
1403 return CFRetain(object);
1406 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1407 return CYCFType(pool, context, value, true);
1410 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1411 return CYCFType(pool, context, value, false);
1414 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1416 size_t size(JSPropertyNameArrayGetCount(names));
1417 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1418 for (size_t index(0); index != size; ++index)
1419 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1423 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1424 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1427 void CYThrow(JSContextRef context, JSValueRef value) {
1430 @throw CYCastNSObject(NULL, context, value);
1433 JSValueRef CYJSNull(JSContextRef context) {
1434 return JSValueMakeNull(context);
1437 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1438 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1441 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1442 return CYCastJSValue(context, CYJSString(value));
1445 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1447 return CYJSNull(context);
1448 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1449 return [value cy$JSValueInContext:context];
1451 return CYMakeInstance(context, value, false);
1454 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1455 JSValueRef exception(NULL);
1456 JSObjectRef object(JSValueToObject(context, value, &exception));
1457 CYThrow(context, exception);
1461 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1462 if (exception == NULL)
1464 *exception = CYCastJSValue(context, error);
1467 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1468 JSValueRef exception(NULL);
1469 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1470 CYThrow(context, exception);
1474 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1475 // XXX: this isn't actually correct
1476 return value != NULL && JSValueIsObject(context, value);
1479 @implementation CYJSObject
1481 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1482 if ((self = [super init]) != nil) {
1485 JSValueProtect(context_, object_);
1490 JSValueUnprotect(context_, object_);
1494 - (NSObject *) cy$toJSON:(NSString *)key {
1495 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1496 if (!CYIsCallable(context_, toJSON))
1497 return [super cy$toJSON:key];
1499 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1500 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1501 // XXX: do I really want an NSNull here?!
1502 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1506 - (NSString *) cy$toCYON {
1507 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1508 if (!CYIsCallable(context_, toCYON)) super:
1509 return [super cy$toCYON];
1510 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1511 return CYCastNSString(NULL, CYJSString(context_, value));
1515 - (NSUInteger) count {
1516 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1517 size_t size(JSPropertyNameArrayGetCount(names));
1518 JSPropertyNameArrayRelease(names);
1522 - (id) objectForKey:(id)key {
1523 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1524 if (JSValueIsUndefined(context_, value))
1526 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1529 - (NSEnumerator *) keyEnumerator {
1530 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1531 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1532 JSPropertyNameArrayRelease(names);
1536 - (void) setObject:(id)object forKey:(id)key {
1537 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1540 - (void) removeObjectForKey:(id)key {
1541 JSValueRef exception(NULL);
1542 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1543 CYThrow(context_, exception);
1548 @implementation CYJSArray
1550 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1551 if ((self = [super init]) != nil) {
1554 JSValueProtect(context_, object_);
1559 JSValueUnprotect(context_, object_);
1563 - (NSUInteger) count {
1564 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1567 - (id) objectAtIndex:(NSUInteger)index {
1568 size_t bounds([self count]);
1569 if (index >= bounds)
1570 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1571 JSValueRef exception(NULL);
1572 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1573 CYThrow(context_, exception);
1574 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1577 - (void) addObject:(id)object {
1578 JSValueRef exception(NULL);
1579 JSValueRef arguments[1];
1580 arguments[0] = CYCastJSValue(context_, object);
1581 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1582 CYThrow(context_, exception);
1585 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1586 size_t bounds([self count] + 1);
1587 if (index >= bounds)
1588 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1589 JSValueRef exception(NULL);
1590 JSValueRef arguments[3];
1591 arguments[0] = CYCastJSValue(context_, index);
1592 arguments[1] = CYCastJSValue(context_, 0);
1593 arguments[2] = CYCastJSValue(context_, object);
1594 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1595 CYThrow(context_, exception);
1598 - (void) removeLastObject {
1599 JSValueRef exception(NULL);
1600 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1601 CYThrow(context_, exception);
1604 - (void) removeObjectAtIndex:(NSUInteger)index {
1605 size_t bounds([self count]);
1606 if (index >= bounds)
1607 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1608 JSValueRef exception(NULL);
1609 JSValueRef arguments[2];
1610 arguments[0] = CYCastJSValue(context_, index);
1611 arguments[1] = CYCastJSValue(context_, 1);
1612 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1613 CYThrow(context_, exception);
1616 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1617 size_t bounds([self count]);
1618 if (index >= bounds)
1619 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1620 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1625 NSString *CYCopyNSCYON(id value) {
1631 Class _class(object_getClass(value));
1632 SEL sel(@selector(cy$toCYON));
1634 if (Method toCYON = class_getInstanceMethod(_class, sel))
1635 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1636 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1637 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1638 string = [value cy$toCYON];
1641 if (value == NSZombie_)
1642 string = @"_NSZombie_";
1643 else if (_class == NSZombie_)
1644 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1645 // XXX: frowny /in/ the pants
1646 else if (value == NSMessageBuilder_ || value == Object_)
1649 string = [NSString stringWithFormat:@"%@", value];
1652 // XXX: frowny pants
1654 string = @"undefined";
1657 return [string retain];
1660 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1661 if (JSValueIsNull(context, value))
1662 return [@"null" retain];
1666 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1671 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1672 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1675 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1676 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1677 const char *string(CYPoolCString(pool, json));
1683 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1687 JSObjectRef object_;
1695 // XXX: delete object_? ;(
1698 static CYInternal *Get(id self) {
1699 CYInternal *internal(NULL);
1700 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1701 // XXX: do something epic? ;P
1707 static CYInternal *Set(id self) {
1708 CYInternal *internal(NULL);
1709 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1710 if (internal == NULL) {
1711 internal = new CYInternal();
1712 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1715 // XXX: do something epic? ;P
1721 bool HasProperty(JSContextRef context, JSStringRef name) {
1722 if (object_ == NULL)
1724 return JSObjectHasProperty(context, object_, name);
1727 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1728 if (object_ == NULL)
1730 return CYGetProperty(context, object_, name);
1733 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1734 if (object_ == NULL)
1735 object_ = JSObjectMake(context, NULL, NULL);
1736 CYSetProperty(context, object_, name, value);
1740 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1741 Selector_privateData *internal(new Selector_privateData(sel));
1742 return JSObjectMake(context, Selector_, internal);
1745 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1746 Pointer *internal(new Pointer(pointer, context, owner, type));
1747 return JSObjectMake(context, Pointer_, internal);
1750 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1751 Functor_privateData *internal(new Functor_privateData(type, function));
1752 return JSObjectMake(context, Functor_, internal);
1755 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1757 // XXX: this could be much more efficient
1758 const char *string([CYCastNSString(NULL, value) UTF8String]);
1761 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1762 char *string(new(pool) char[size]);
1763 JSStringGetUTF8CString(value, string, size);
1768 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1769 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1772 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1773 return CYGetOffset(CYPoolCString(pool, value), index);
1776 // XXX: this macro is unhygenic
1777 #define CYCastCString(context, value) ({ \
1779 if (value == NULL) \
1781 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1782 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1783 utf8 = reinterpret_cast<char *>(alloca(size)); \
1784 JSStringGetUTF8CString(string, utf8, size); \
1785 JSStringRelease(string); \
1791 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1792 switch (JSValueGetType(context, value)) {
1795 /*case kJSTypeString:
1796 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1798 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1799 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1800 return internal->value_;
1803 double number(CYCastDouble(context, value));
1804 if (std::isnan(number))
1805 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1806 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1810 template <typename Type_>
1811 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1812 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1815 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1816 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1817 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1818 return reinterpret_cast<SEL>(internal->value_);
1820 return CYCastPointer<SEL>(context, value);
1823 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1824 switch (type->primitive) {
1825 case sig::boolean_P:
1826 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1829 #define CYPoolFFI_(primitive, native) \
1830 case sig::primitive ## _P: \
1831 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1834 CYPoolFFI_(uchar, unsigned char)
1835 CYPoolFFI_(char, char)
1836 CYPoolFFI_(ushort, unsigned short)
1837 CYPoolFFI_(short, short)
1838 CYPoolFFI_(ulong, unsigned long)
1839 CYPoolFFI_(long, long)
1840 CYPoolFFI_(uint, unsigned int)
1841 CYPoolFFI_(int, int)
1842 CYPoolFFI_(ulonglong, unsigned long long)
1843 CYPoolFFI_(longlong, long long)
1844 CYPoolFFI_(float, float)
1845 CYPoolFFI_(double, double)
1848 case sig::typename_P:
1849 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1852 case sig::selector_P:
1853 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1856 case sig::pointer_P:
1857 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1861 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1864 case sig::struct_P: {
1865 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1866 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1867 for (size_t index(0); index != type->data.signature.count; ++index) {
1868 sig::Element *element(&type->data.signature.elements[index]);
1869 ffi_type *field(ffi->elements[index]);
1872 if (aggregate == NULL)
1875 rhs = CYGetProperty(context, aggregate, index);
1876 if (JSValueIsUndefined(context, rhs)) {
1877 if (element->name != NULL)
1878 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1881 if (JSValueIsUndefined(context, rhs)) undefined:
1882 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1886 CYPoolFFI(pool, context, element->type, field, base, rhs);
1888 base += field->size;
1896 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1901 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1904 switch (type->primitive) {
1905 case sig::boolean_P:
1906 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1909 #define CYFromFFI_(primitive, native) \
1910 case sig::primitive ## _P: \
1911 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1914 CYFromFFI_(uchar, unsigned char)
1915 CYFromFFI_(char, char)
1916 CYFromFFI_(ushort, unsigned short)
1917 CYFromFFI_(short, short)
1918 CYFromFFI_(ulong, unsigned long)
1919 CYFromFFI_(long, long)
1920 CYFromFFI_(uint, unsigned int)
1921 CYFromFFI_(int, int)
1922 CYFromFFI_(ulonglong, unsigned long long)
1923 CYFromFFI_(longlong, long long)
1924 CYFromFFI_(float, float)
1925 CYFromFFI_(double, double)
1927 case sig::object_P: {
1928 if (id object = *reinterpret_cast<id *>(data)) {
1929 value = CYCastJSValue(context, object);
1935 case sig::typename_P:
1936 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1939 case sig::selector_P:
1940 if (SEL sel = *reinterpret_cast<SEL *>(data))
1941 value = CYMakeSelector(context, sel);
1945 case sig::pointer_P:
1946 if (void *pointer = *reinterpret_cast<void **>(data))
1947 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1952 if (char *utf8 = *reinterpret_cast<char **>(data))
1953 value = CYCastJSValue(context, utf8);
1958 value = CYMakeStruct(context, data, type, ffi, owner);
1962 value = CYJSUndefined(context);
1966 value = CYJSNull(context);
1970 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1977 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1978 if (Method method = class_getInstanceMethod(_class, selector)) {
1982 method_getReturnType(method, type, sizeof(type));
1987 // XXX: possibly use a more "awesome" check?
1991 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
1993 return method_getTypeEncoding(method);
1994 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1995 return CYPoolCString(pool, type);
2000 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2001 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2003 JSContextRef context(internal->context_);
2005 size_t count(internal->cif_.nargs);
2006 JSValueRef values[count];
2008 for (size_t index(0); index != count; ++index)
2009 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2011 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2012 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2015 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2016 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2018 JSContextRef context(internal->context_);
2020 size_t count(internal->cif_.nargs);
2021 JSValueRef values[count];
2023 for (size_t index(0); index != count; ++index)
2024 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2026 JSObjectRef _this(CYCastJSObject(context, values[0]));
2028 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2029 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2032 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2033 // XXX: in case of exceptions this will leak
2034 // XXX: in point of fact, this may /need/ to leak :(
2035 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2037 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2038 NULL, sizeof(ffi_closure),
2039 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2043 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2044 _assert(status == FFI_OK);
2046 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2048 internal->value_ = closure;
2053 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2054 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2055 return JSObjectMake(context, Functor_, internal);
2058 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2059 JSValueRef exception(NULL);
2060 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2061 CYThrow(context, exception);
2064 JSObjectRef function(CYCastJSObject(context, value));
2065 return CYMakeFunctor(context, function, type);
2067 void (*function)()(CYCastPointer<void (*)()>(context, value));
2068 return CYMakeFunctor(context, function, type);
2072 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2073 Message_privateData *internal(new Message_privateData(sel, type, imp));
2074 return JSObjectMake(context, Message_, internal);
2077 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2078 JSObjectRef function(CYCastJSObject(context, value));
2079 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2080 return reinterpret_cast<IMP>(internal->GetValue());
2083 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2084 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2085 Class _class(internal->GetValue());
2088 const char *name(CYPoolCString(pool, property));
2090 if (SEL sel = sel_getUid(name))
2091 if (class_getInstanceMethod(_class, sel) != NULL)
2097 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2098 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2099 Class _class(internal->GetValue());
2102 const char *name(CYPoolCString(pool, property));
2104 if (SEL sel = sel_getUid(name))
2105 if (Method method = class_getInstanceMethod(_class, sel))
2106 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2111 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2112 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2113 Class _class(internal->GetValue());
2116 const char *name(CYPoolCString(pool, property));
2118 SEL sel(sel_registerName(name));
2120 Method method(class_getInstanceMethod(_class, sel));
2125 if (JSValueIsObjectOfClass(context, value, Message_)) {
2126 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2127 type = sig::Unparse(pool, &message->signature_);
2128 imp = reinterpret_cast<IMP>(message->GetValue());
2130 type = CYPoolTypeEncoding(pool, _class, sel, method);
2131 imp = CYMakeMessage(context, value, type);
2135 method_setImplementation(method, imp);
2137 class_replaceMethod(_class, sel, imp, type);
2143 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2144 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2145 Class _class(internal->GetValue());
2148 const char *name(CYPoolCString(pool, property));
2150 if (SEL sel = sel_getUid(name))
2151 if (Method method = class_getInstanceMethod(_class, sel)) {
2152 objc_method_list list = {NULL, 1, {method}};
2153 class_removeMethods(_class, &list);
2161 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2162 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2163 Class _class(internal->GetValue());
2166 Method *data(class_copyMethodList(_class, &size));
2167 for (size_t i(0); i != size; ++i)
2168 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2172 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2173 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2174 id self(internal->GetValue());
2176 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2180 NSString *name(CYCastNSString(pool, property));
2182 if (CYInternal *internal = CYInternal::Get(self))
2183 if (internal->HasProperty(context, property))
2186 Class _class(object_getClass(self));
2189 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2190 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2191 if ([self cy$hasProperty:name])
2193 } CYPoolCatch(false)
2195 const char *string(CYPoolCString(pool, name));
2197 if (class_getProperty(_class, string) != NULL)
2200 if (SEL sel = sel_getUid(string))
2201 if (CYImplements(self, _class, sel, true))
2207 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2208 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2209 id self(internal->GetValue());
2211 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2212 return Internal::Make(context, self, object);
2216 NSString *name(CYCastNSString(pool, property));
2218 if (CYInternal *internal = CYInternal::Get(self))
2219 if (JSValueRef value = internal->GetProperty(context, property))
2223 if (NSObject *data = [self cy$getProperty:name])
2224 return CYCastJSValue(context, data);
2227 const char *string(CYPoolCString(pool, name));
2228 Class _class(object_getClass(self));
2230 if (objc_property_t property = class_getProperty(_class, string)) {
2231 PropertyAttributes attributes(property);
2232 SEL sel(sel_registerName(attributes.Getter()));
2233 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2236 if (SEL sel = sel_getUid(string))
2237 if (CYImplements(self, _class, sel, true))
2238 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2244 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2245 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2246 id self(internal->GetValue());
2251 NSString *name(CYCastNSString(pool, property));
2252 NSString *data(CYCastNSObject(pool, context, value));
2255 if ([self cy$setProperty:name to:data])
2259 const char *string(CYPoolCString(pool, name));
2260 Class _class(object_getClass(self));
2262 if (objc_property_t property = class_getProperty(_class, string)) {
2263 PropertyAttributes attributes(property);
2264 if (const char *setter = attributes.Setter()) {
2265 SEL sel(sel_registerName(setter));
2266 JSValueRef arguments[1] = {value};
2267 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2272 size_t length(strlen(string));
2274 char set[length + 5];
2280 if (string[0] != '\0') {
2281 set[3] = toupper(string[0]);
2282 memcpy(set + 4, string + 1, length - 1);
2285 set[length + 3] = ':';
2286 set[length + 4] = '\0';
2288 if (SEL sel = sel_getUid(set))
2289 if (CYImplements(self, _class, sel, false)) {
2290 JSValueRef arguments[1] = {value};
2291 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2294 if (CYInternal *internal = CYInternal::Set(self)) {
2295 internal->SetProperty(context, property, value);
2303 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2304 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2305 id self(internal->GetValue());
2309 NSString *name(CYCastNSString(NULL, property));
2310 return [self cy$deleteProperty:name];
2315 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2316 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2317 id self(internal->GetValue());
2320 Class _class(object_getClass(self));
2324 objc_property_t *data(class_copyPropertyList(_class, &size));
2325 for (size_t i(0); i != size; ++i)
2326 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2331 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2333 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2334 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2339 static bool CYIsClass(id self) {
2340 // XXX: this is a lame object_isClass
2341 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2344 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2345 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2346 Class _class(internal->GetValue());
2347 if (!CYIsClass(_class))
2350 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2351 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2352 // XXX: this isn't always safe
2354 return [linternal->GetValue() isKindOfClass:_class];
2361 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2362 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2365 id self(internal->GetValue());
2366 const char *name(CYPoolCString(pool, property));
2368 if (object_getInstanceVariable(self, name, NULL) != NULL)
2374 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2375 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2379 id self(internal->GetValue());
2380 const char *name(CYPoolCString(pool, property));
2382 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2383 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2384 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2391 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2392 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2396 id self(internal->GetValue());
2397 const char *name(CYPoolCString(pool, property));
2399 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2400 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2401 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2409 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2410 if (Class super = class_getSuperclass(_class))
2411 Internal_getPropertyNames_(super, names);
2414 Ivar *data(class_copyIvarList(_class, &size));
2415 for (size_t i(0); i != size; ++i)
2416 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2420 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2421 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2424 id self(internal->GetValue());
2425 Class _class(object_getClass(self));
2427 Internal_getPropertyNames_(_class, names);
2430 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2431 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2432 return internal->GetOwner();
2435 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2436 Type_privateData *typical(internal->type_);
2437 sig::Type *type(typical->type_);
2441 const char *name(CYPoolCString(pool, property));
2442 size_t length(strlen(name));
2443 double number(CYCastDouble(name, length));
2445 size_t count(type->data.signature.count);
2447 if (std::isnan(number)) {
2448 if (property == NULL)
2451 sig::Element *elements(type->data.signature.elements);
2453 for (size_t local(0); local != count; ++local) {
2454 sig::Element *element(&elements[local]);
2455 if (element->name != NULL && strcmp(name, element->name) == 0) {
2463 index = static_cast<ssize_t>(number);
2464 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2469 ffi_type **elements(typical->GetFFI()->elements);
2471 base = reinterpret_cast<uint8_t *>(internal->value_);
2472 for (ssize_t local(0); local != index; ++local)
2473 base += elements[local]->size;
2478 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2479 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2480 Type_privateData *typical(internal->type_);
2482 ffi_type *ffi(typical->GetFFI());
2484 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2485 base += ffi->size * index;
2487 JSObjectRef owner(internal->GetOwner() ?: object);
2490 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2494 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2496 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2497 Type_privateData *typical(internal->type_);
2499 if (typical->type_ == NULL)
2503 if (!CYGetOffset(pool, property, offset))
2506 return Pointer_getIndex(context, object, offset, exception);
2509 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2510 return Pointer_getIndex(context, object, 0, exception);
2513 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2514 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2515 Type_privateData *typical(internal->type_);
2517 ffi_type *ffi(typical->GetFFI());
2519 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2520 base += ffi->size * index;
2523 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2528 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2530 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2531 Type_privateData *typical(internal->type_);
2533 if (typical->type_ == NULL)
2537 if (!CYGetOffset(pool, property, offset))
2540 return Pointer_setIndex(context, object, offset, value, exception);
2543 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2544 return Pointer_setIndex(context, object, 0, value, exception);
2547 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2548 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2549 Type_privateData *typical(internal->type_);
2550 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2553 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2555 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2556 Type_privateData *typical(internal->type_);
2561 if (!Index_(pool, internal, property, index, base))
2564 JSObjectRef owner(internal->GetOwner() ?: object);
2567 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2571 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2573 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2574 Type_privateData *typical(internal->type_);
2579 if (!Index_(pool, internal, property, index, base))
2583 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2588 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2589 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2590 Type_privateData *typical(internal->type_);
2591 sig::Type *type(typical->type_);
2596 size_t count(type->data.signature.count);
2597 sig::Element *elements(type->data.signature.elements);
2601 for (size_t index(0); index != count; ++index) {
2603 name = elements[index].name;
2606 sprintf(number, "%lu", index);
2610 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2614 JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
2616 if (setups + count != signature->count - 1)
2617 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2619 size_t size(setups + count);
2621 memcpy(values, setup, sizeof(void *) * setups);
2623 for (size_t index(setups); index != size; ++index) {
2624 sig::Element *element(&signature->elements[index + 1]);
2625 ffi_type *ffi(cif->arg_types[index]);
2627 values[index] = new(pool) uint8_t[ffi->size];
2628 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2631 uint8_t value[cif->rtype->size];
2632 ffi_call(cif, function, value, values);
2634 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2638 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2641 NSString *name(CYCastNSString(pool, property));
2642 if (Class _class = NSClassFromString(name))
2643 return CYMakeInstance(context, _class, true);
2648 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2649 size_t size(objc_getClassList(NULL, 0));
2650 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2653 size_t writ(objc_getClassList(data, size));
2656 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2662 for (size_t i(0); i != writ; ++i)
2663 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2669 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2670 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2674 const char *name(CYPoolCString(pool, property));
2676 const char **data(objc_copyClassNamesForImage(internal, &size));
2678 for (size_t i(0); i != size; ++i)
2679 if (strcmp(name, data[i]) == 0) {
2680 if (Class _class = objc_getClass(name)) {
2681 value = CYMakeInstance(context, _class, true);
2693 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2694 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2696 const char **data(objc_copyClassNamesForImage(internal, &size));
2697 for (size_t i(0); i != size; ++i)
2698 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2702 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2705 const char *name(CYPoolCString(pool, property));
2707 const char **data(objc_copyImageNames(&size));
2708 for (size_t i(0); i != size; ++i)
2709 if (strcmp(name, data[i]) == 0) {
2718 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2719 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2724 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2726 const char **data(objc_copyImageNames(&size));
2727 for (size_t i(0); i != size; ++i)
2728 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2732 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2735 NSString *name(CYCastNSString(pool, property));
2736 if (Protocol *protocol = NSProtocolFromString(name))
2737 return CYMakeInstance(context, protocol, true);
2742 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2744 Protocol **data(objc_copyProtocolList(&size));
2745 for (size_t i(0); i != size; ++i)
2746 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2750 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
2751 Type_privateData *internal(new Type_privateData(NULL, type));
2752 return JSObjectMake(context, Type_, internal);
2755 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
2756 Type_privateData *internal(new Type_privateData(type));
2757 return JSObjectMake(context, Type_, internal);
2760 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2761 if (JSStringIsEqualToUTF8CString(property, "nil"))
2762 return Instance::Make(context, nil);
2766 NSString *name(CYCastNSString(pool, property));
2767 if (Class _class = NSClassFromString(name))
2768 return CYMakeInstance(context, _class, true);
2769 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2770 switch ([[entry objectAtIndex:0] intValue]) {
2772 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2774 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2776 // XXX: this is horrendously inefficient
2777 sig::Signature signature;
2778 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2780 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2781 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2783 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
2784 switch ([[entry objectAtIndex:0] intValue]) {
2785 // XXX: implement case 0
2787 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
2793 static bool stret(ffi_type *ffi_type) {
2794 return ffi_type->type == FFI_TYPE_STRUCT && (
2795 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2796 struct_forward_array[ffi_type->size] != 0
2801 int *_NSGetArgc(void);
2802 char ***_NSGetArgv(void);
2803 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2806 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2808 NSLog(@"%s", CYCastCString(context, arguments[0]));
2809 return CYJSUndefined(context);
2813 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2816 Class _class(object_getClass(self));
2817 if (Method method = class_getInstanceMethod(_class, _cmd))
2818 type = method_getTypeEncoding(method);
2822 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2824 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2825 type = CYPoolCString(pool, [method _typeString]);
2834 sig::Signature signature;
2835 sig::Parse(pool, &signature, type, &Structor_);
2838 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2840 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2841 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2844 static size_t Nonce_(0);
2846 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2848 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
2849 return CYCastJSValue(context, name);
2852 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2862 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2864 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2865 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2866 self = internal->GetValue();
2867 uninitialized = internal->IsUninitialized();
2869 internal->value_ = nil;
2871 self = CYCastNSObject(pool, context, arguments[0]);
2872 uninitialized = false;
2876 return CYJSNull(context);
2878 _cmd = CYCastSEL(context, arguments[1]);
2881 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2884 /* Hook: objc_registerClassPair {{{ */
2885 // XXX: replace this with associated objects
2887 MSHook(void, CYDealloc, id self, SEL sel) {
2888 CYInternal *internal;
2889 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2890 if (internal != NULL)
2892 _CYDealloc(self, sel);
2895 MSHook(void, objc_registerClassPair, Class _class) {
2896 Class super(class_getSuperclass(_class));
2897 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2898 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2899 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2902 _objc_registerClassPair(_class);
2905 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2908 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2910 Class _class(CYCastNSObject(pool, context, arguments[0]));
2911 $objc_registerClassPair(_class);
2912 return CYJSUndefined(context);
2917 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2918 JSValueRef setup[count + 2];
2921 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2922 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2925 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2927 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2929 // XXX: handle Instance::Uninitialized?
2930 id self(CYCastNSObject(pool, context, _this));
2934 setup[1] = &internal->sel_;
2936 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2939 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2941 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2942 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2945 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2948 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2949 const char *name(CYCastCString(context, arguments[0]));
2950 return CYMakeSelector(context, sel_registerName(name));
2954 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2957 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2959 void *value(CYCastPointer<void *>(context, arguments[0]));
2960 const char *type(CYCastCString(context, arguments[1]));
2964 sig::Signature signature;
2965 sig::Parse(pool, &signature, type, &Structor_);
2967 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2971 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2974 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2975 const char *type(CYCastCString(context, arguments[0]));
2976 return CYMakeType(context, type);
2980 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2981 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2986 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
2987 type.primitive = sig::pointer_P;
2988 type.data.data.size = 0;
2990 size_t index(CYGetIndex(NULL, property));
2991 if (index == _not(size_t))
2993 type.primitive = sig::array_P;
2994 type.data.data.size = index;
3000 type.data.data.type = internal->type_;
3002 return CYMakeType(context, &type);
3006 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3007 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3011 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3012 sig::Type *type(internal->type_);
3013 ffi_type *ffi(internal->GetFFI());
3015 uint8_t value[ffi->size];
3017 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3018 return CYFromFFI(context, type, ffi, value);
3022 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3025 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3026 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3028 sig::Type *type(internal->type_);
3031 if (type->primitive != sig::array_P)
3034 size = type->data.data.size;
3035 type = type->data.data.type;
3038 void *value(malloc(internal->GetFFI()->size));
3039 return CYMakePointer(context, value, type, NULL, NULL);
3043 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3046 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
3047 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3048 return Instance::Make(context, self);
3052 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3055 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
3056 const char *type(CYCastCString(context, arguments[1]));
3057 return CYMakeFunctor(context, arguments[0], type);
3061 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3062 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3063 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3066 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3067 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3068 Type_privateData *typical(internal->GetType());
3073 if (typical == NULL) {
3077 type = typical->type_;
3078 ffi = typical->ffi_;
3081 return CYMakePointer(context, &internal->value_, type, ffi, object);
3084 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3085 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3088 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3092 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3093 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3096 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3097 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3099 sprintf(string, "%p", internal->value_);
3102 return CYCastJSValue(context, string);
3106 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3107 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3108 return Instance::Make(context, object_getClass(internal->GetValue()));
3111 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3112 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3113 id self(internal->GetValue());
3114 if (!CYIsClass(self))
3115 return CYJSUndefined(context);
3117 return CYGetClassPrototype(context, self);
3121 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3122 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3123 id self(internal->GetValue());
3124 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3125 return CYJSUndefined(context);
3126 return Messages::Make(context, self);
3129 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3130 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3133 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3137 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
3142 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3143 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3146 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3150 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3151 // XXX: check for support of cy$toJSON?
3152 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3157 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3158 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3161 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3165 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3170 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3171 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3174 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3178 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3179 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3182 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3183 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3184 const char *name(sel_getName(internal->GetValue()));
3188 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3193 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3196 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
3198 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3199 Class _class(CYCastNSObject(pool, context, arguments[0]));
3200 SEL sel(internal->GetValue());
3201 Method method(class_getInstanceMethod(_class, sel));
3202 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3203 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3207 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3209 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3211 const char *type(sig::Unparse(pool, internal->type_));
3213 return CYCastJSValue(context, CYJSString(type));
3218 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3220 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3222 const char *type(sig::Unparse(pool, internal->type_));
3224 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
3229 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3230 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3233 static JSStaticValue CYValue_staticValues[2] = {
3234 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3235 {NULL, NULL, NULL, 0}
3238 static JSStaticValue Pointer_staticValues[2] = {
3239 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3240 {NULL, NULL, NULL, 0}
3243 static JSStaticFunction Pointer_staticFunctions[4] = {
3244 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3245 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3246 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3250 static JSStaticFunction Struct_staticFunctions[2] = {
3251 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3255 static JSStaticFunction Functor_staticFunctions[4] = {
3256 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3257 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3258 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3262 static JSStaticValue Instance_staticValues[5] = {
3263 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3264 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3265 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3266 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3267 {NULL, NULL, NULL, 0}
3270 static JSStaticFunction Instance_staticFunctions[5] = {
3271 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3272 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3273 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3274 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3278 static JSStaticFunction Internal_staticFunctions[2] = {
3279 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3283 static JSStaticFunction Selector_staticFunctions[5] = {
3284 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3285 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3286 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3287 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3291 static JSStaticFunction Type_staticFunctions[4] = {
3292 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3293 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3294 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3298 CYDriver::CYDriver(const std::string &filename) :
3303 filename_(filename),
3309 CYDriver::~CYDriver() {
3313 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
3314 CYDriver::Error error;
3315 error.location_ = location;
3316 error.message_ = message;
3317 driver.errors_.push_back(error);
3320 void CYSetArgs(int argc, const char *argv[]) {
3321 JSContextRef context(CYGetJSContext());
3322 JSValueRef args[argc];
3323 for (int i(0); i != argc; ++i)
3324 args[i] = CYCastJSValue(context, argv[i]);
3325 JSValueRef exception(NULL);
3326 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3327 CYThrow(context, exception);
3328 CYSetProperty(context, System_, CYJSString("args"), array);
3331 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3332 return JSContextGetGlobalObject(context);
3335 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3336 JSContextRef context(CYGetJSContext());
3337 JSValueRef exception(NULL), result;
3340 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3341 } catch (const char *error) {
3345 if (exception != NULL) { error:
3350 if (JSValueIsUndefined(context, result))
3356 json = CYPoolCCYON(pool, context, result, &exception);
3357 } catch (const char *error) {
3361 if (exception != NULL)
3364 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3368 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
3369 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
3377 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
3378 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
3386 static apr_pool_t *Pool_;
3390 const char * volatile data_;
3393 // XXX: this is "tre lame"
3394 @interface CYClient_ : NSObject {
3397 - (void) execute:(NSValue *)value;
3401 @implementation CYClient_
3403 - (void) execute:(NSValue *)value {
3404 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3405 const char *data(execute->data_);
3406 execute->data_ = NULL;
3407 execute->data_ = CYExecute(execute->pool_, data);
3416 apr_thread_t *thread_;
3418 CYClient(int socket) :
3424 _syscall(close(socket_));
3427 void Handle() { _pooled
3428 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3432 if (!CYRecvAll(socket_, &size, sizeof(size)))
3436 char *data(new(pool) char[size + 1]);
3437 if (!CYRecvAll(socket_, data, size))
3441 CYDriver driver("");
3442 cy::parser parser(driver);
3444 driver.data_ = data;
3445 driver.size_ = size;
3448 if (parser.parse() != 0 || !driver.errors_.empty()) {
3450 size = _not(size_t);
3452 std::ostringstream str;
3453 driver.source_->Show(str);
3454 std::string code(str.str());
3455 CYExecute_ execute = {pool, code.c_str()};
3456 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3457 json = execute.data_;
3458 size = json == NULL ? _not(size_t) : strlen(json);
3461 if (!CYSendAll(socket_, &size, sizeof(size)))
3464 if (!CYSendAll(socket_, json, size))
3470 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3471 CYClient *client(reinterpret_cast<CYClient *>(data));
3477 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3478 CYClient *client(new(pool) CYClient(socket));
3479 apr_threadattr_t *attr;
3480 _aprcall(apr_threadattr_create(&attr, client->pool_));
3481 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3484 MSInitialize { _pooled
3485 _aprcall(apr_initialize());
3486 _aprcall(apr_pool_create(&Pool_, NULL));
3488 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3489 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3491 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3493 NSArray_ = objc_getClass("NSArray");
3494 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3495 NSCFType_ = objc_getClass("NSCFType");
3496 NSDictionary_ = objc_getClass("NSDictonary");
3497 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3498 NSZombie_ = objc_getClass("_NSZombie_");
3499 Object_ = objc_getClass("Object");
3502 JSGlobalContextRef CYGetJSContext() {
3503 if (Context_ == NULL) {
3504 JSClassDefinition definition;
3506 definition = kJSClassDefinitionEmpty;
3507 definition.className = "Functor";
3508 definition.staticFunctions = Functor_staticFunctions;
3509 definition.callAsFunction = &Functor_callAsFunction;
3510 definition.finalize = &Finalize;
3511 Functor_ = JSClassCreate(&definition);
3513 definition = kJSClassDefinitionEmpty;
3514 definition.className = "Instance";
3515 definition.staticValues = Instance_staticValues;
3516 definition.staticFunctions = Instance_staticFunctions;
3517 definition.hasProperty = &Instance_hasProperty;
3518 definition.getProperty = &Instance_getProperty;
3519 definition.setProperty = &Instance_setProperty;
3520 definition.deleteProperty = &Instance_deleteProperty;
3521 definition.getPropertyNames = &Instance_getPropertyNames;
3522 definition.callAsConstructor = &Instance_callAsConstructor;
3523 definition.hasInstance = &Instance_hasInstance;
3524 definition.finalize = &Finalize;
3525 Instance_ = JSClassCreate(&definition);
3527 definition = kJSClassDefinitionEmpty;
3528 definition.className = "Internal";
3529 definition.staticFunctions = Internal_staticFunctions;
3530 definition.hasProperty = &Internal_hasProperty;
3531 definition.getProperty = &Internal_getProperty;
3532 definition.setProperty = &Internal_setProperty;
3533 definition.getPropertyNames = &Internal_getPropertyNames;
3534 definition.finalize = &Finalize;
3535 Internal_ = JSClassCreate(&definition);
3537 definition = kJSClassDefinitionEmpty;
3538 definition.className = "Message";
3539 definition.staticFunctions = Functor_staticFunctions;
3540 definition.callAsFunction = &Message_callAsFunction;
3541 definition.finalize = &Finalize;
3542 Message_ = JSClassCreate(&definition);
3544 definition = kJSClassDefinitionEmpty;
3545 definition.className = "Messages";
3546 definition.hasProperty = &Messages_hasProperty;
3547 definition.getProperty = &Messages_getProperty;
3548 definition.setProperty = &Messages_setProperty;
3550 definition.deleteProperty = &Messages_deleteProperty;
3552 definition.getPropertyNames = &Messages_getPropertyNames;
3553 definition.finalize = &Finalize;
3554 Messages_ = JSClassCreate(&definition);
3556 definition = kJSClassDefinitionEmpty;
3557 definition.className = "NSArrayPrototype";
3558 //definition.hasProperty = &NSArrayPrototype_hasProperty;
3559 //definition.getProperty = &NSArrayPrototype_getProperty;
3560 //definition.setProperty = &NSArrayPrototype_setProperty;
3561 //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
3562 //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
3563 NSArrayPrototype_ = JSClassCreate(&definition);
3565 definition = kJSClassDefinitionEmpty;
3566 definition.className = "Pointer";
3567 definition.staticValues = Pointer_staticValues;
3568 definition.staticFunctions = Pointer_staticFunctions;
3569 definition.getProperty = &Pointer_getProperty;
3570 definition.setProperty = &Pointer_setProperty;
3571 definition.finalize = &Finalize;
3572 Pointer_ = JSClassCreate(&definition);
3574 definition = kJSClassDefinitionEmpty;
3575 definition.className = "Selector";
3576 definition.staticValues = CYValue_staticValues;
3577 definition.staticFunctions = Selector_staticFunctions;
3578 definition.callAsFunction = &Selector_callAsFunction;
3579 definition.finalize = &Finalize;
3580 Selector_ = JSClassCreate(&definition);
3582 definition = kJSClassDefinitionEmpty;
3583 definition.className = "Struct";
3584 definition.staticFunctions = Struct_staticFunctions;
3585 definition.getProperty = &Struct_getProperty;
3586 definition.setProperty = &Struct_setProperty;
3587 definition.getPropertyNames = &Struct_getPropertyNames;
3588 definition.finalize = &Finalize;
3589 Struct_ = JSClassCreate(&definition);
3591 definition = kJSClassDefinitionEmpty;
3592 definition.className = "Type";
3593 definition.staticFunctions = Type_staticFunctions;
3594 definition.getProperty = &Type_getProperty;
3595 definition.callAsFunction = &Type_callAsFunction;
3596 definition.callAsConstructor = &Type_callAsConstructor;
3597 definition.finalize = &Finalize;
3598 Type_ = JSClassCreate(&definition);
3600 definition = kJSClassDefinitionEmpty;
3601 definition.className = "Runtime";
3602 definition.getProperty = &Runtime_getProperty;
3603 Runtime_ = JSClassCreate(&definition);
3605 definition = kJSClassDefinitionEmpty;
3606 definition.className = "ObjectiveC::Classes";
3607 definition.getProperty = &ObjectiveC_Classes_getProperty;
3608 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3609 ObjectiveC_Classes_ = JSClassCreate(&definition);
3611 definition = kJSClassDefinitionEmpty;
3612 definition.className = "ObjectiveC::Images";
3613 definition.getProperty = &ObjectiveC_Images_getProperty;
3614 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3615 ObjectiveC_Images_ = JSClassCreate(&definition);
3617 definition = kJSClassDefinitionEmpty;
3618 definition.className = "ObjectiveC::Image::Classes";
3619 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3620 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3621 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3623 definition = kJSClassDefinitionEmpty;
3624 definition.className = "ObjectiveC::Protocols";
3625 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3626 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3627 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3629 definition = kJSClassDefinitionEmpty;
3630 //definition.getProperty = &Global_getProperty;
3631 JSClassRef Global(JSClassCreate(&definition));
3633 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3636 JSObjectRef global(CYGetGlobalObject(context));
3638 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3639 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3640 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3642 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3643 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3644 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3646 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3647 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3648 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3650 length_ = JSStringCreateWithUTF8CString("length");
3651 message_ = JSStringCreateWithUTF8CString("message");
3652 name_ = JSStringCreateWithUTF8CString("name");
3653 prototype_ = JSStringCreateWithUTF8CString("prototype");
3654 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3655 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3657 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3658 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3660 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3661 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3662 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3663 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3665 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3666 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3667 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3668 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3670 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3672 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3673 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3674 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3675 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3677 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3678 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3679 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3680 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3681 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3683 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3685 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3687 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3688 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3689 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3691 System_ = JSObjectMake(context, NULL, NULL);
3692 CYSetProperty(context, global, CYJSString("system"), System_);
3693 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3694 //CYSetProperty(context, System_, CYJSString("global"), global);
3696 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3698 Result_ = JSStringCreateWithUTF8CString("_");
3700 JSValueProtect(context, Array_);
3701 JSValueProtect(context, Function_);
3702 JSValueProtect(context, String_);
3704 JSValueProtect(context, Instance_prototype_);
3705 JSValueProtect(context, Object_prototype_);
3707 JSValueProtect(context, Array_prototype_);
3708 JSValueProtect(context, Array_pop_);
3709 JSValueProtect(context, Array_push_);
3710 JSValueProtect(context, Array_splice_);