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')
759 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
760 return CYGetIndex(CYPoolCString(pool, value));
763 bool CYGetOffset(const char *value, ssize_t &index) {
764 if (value[0] != '0') {
766 index = strtol(value, &end, 10);
767 if (value + strlen(value) == end)
769 } else if (value[1] == '\0') {
777 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
778 return CYGetOffset(CYPoolCString(pool, value), index);
781 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
783 @interface NSMethodSignature (Cycript)
784 - (NSString *) _typeString;
787 @interface NSObject (Cycript)
789 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
790 - (JSType) cy$JSType;
792 - (NSObject *) cy$toJSON:(NSString *)key;
793 - (NSString *) cy$toCYON;
794 - (NSString *) cy$toKey;
796 - (bool) cy$hasProperty:(NSString *)name;
797 - (NSObject *) cy$getProperty:(NSString *)name;
798 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
799 - (bool) cy$deleteProperty:(NSString *)name;
804 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
807 @interface NSString (Cycript)
808 - (void *) cy$symbol;
811 struct PropertyAttributes {
816 const char *variable;
829 PropertyAttributes(objc_property_t property) :
841 name = property_getName(property);
842 const char *attributes(property_getAttributes(property));
844 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
846 case 'R': readonly = true; break;
847 case 'C': copy = true; break;
848 case '&': retain = true; break;
849 case 'N': nonatomic = true; break;
850 case 'G': getter_ = token + 1; break;
851 case 'S': setter_ = token + 1; break;
852 case 'V': variable = token + 1; break;
856 /*if (variable == NULL) {
857 variable = property_getName(property);
858 size_t size(strlen(variable));
859 char *name(new(pool_) char[size + 2]);
861 memcpy(name + 1, variable, size);
862 name[size + 1] = '\0';
867 const char *Getter() {
869 getter_ = apr_pstrdup(pool_, name);
873 const char *Setter() {
874 if (setter_ == NULL && !readonly) {
875 size_t length(strlen(name));
877 char *temp(new(pool_) char[length + 5]);
883 temp[3] = toupper(name[0]);
884 memcpy(temp + 4, name + 1, length - 1);
887 temp[length + 3] = ':';
888 temp[length + 4] = '\0';
897 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
898 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
901 /* Bridge: NSArray {{{ */
902 @implementation NSArray (Cycript)
904 - (NSString *) cy$toCYON {
905 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
906 [json appendString:@"["];
909 for (id object in self) {
911 [json appendString:@","];
914 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
915 [json appendString:CYPoolNSCYON(NULL, object)];
917 [json appendString:@","];
922 [json appendString:@"]"];
926 - (bool) cy$hasProperty:(NSString *)name {
927 if ([name isEqualToString:@"length"])
930 size_t index(CYGetIndex(NULL, name));
931 if (index == _not(size_t) || index >= [self count])
932 return [super cy$hasProperty:name];
937 - (NSObject *) cy$getProperty:(NSString *)name {
938 if ([name isEqualToString:@"length"])
939 return [NSNumber numberWithUnsignedInteger:[self count]];
941 size_t index(CYGetIndex(NULL, name));
942 if (index == _not(size_t) || index >= [self count])
943 return [super cy$getProperty:name];
945 return [self objectAtIndex:index];
950 /* Bridge: NSDictionary {{{ */
951 @implementation NSDictionary (Cycript)
953 - (NSString *) cy$toCYON {
954 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
955 [json appendString:@"{"];
958 for (id key in self) {
960 [json appendString:@","];
963 [json appendString:[key cy$toKey]];
964 [json appendString:@":"];
965 NSObject *object([self objectForKey:key]);
966 [json appendString:CYPoolNSCYON(NULL, object)];
969 [json appendString:@"}"];
973 - (bool) cy$hasProperty:(NSString *)name {
974 return [self objectForKey:name] != nil;
977 - (NSObject *) cy$getProperty:(NSString *)name {
978 return [self objectForKey:name];
983 /* Bridge: NSMutableArray {{{ */
984 @implementation NSMutableArray (Cycript)
986 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
987 if ([name isEqualToString:@"length"]) {
988 // XXX: is this not intelligent?
989 NSUInteger size([(NSNumber *)value unsignedIntegerValue]);
990 NSUInteger count([self count]);
992 [self removeObjectsInRange:NSMakeRange(size, count - size)];
993 else if (size != count) {
994 WebUndefined *undefined([WebUndefined undefined]);
995 for (size_t i(count); i != size; ++i)
996 [self addObject:undefined];
1001 size_t index(CYGetIndex(NULL, name));
1002 if (index == _not(size_t))
1003 return [super cy$setProperty:name to:value];
1005 id object(value ?: [NSNull null]);
1007 size_t count([self count]);
1009 [self replaceObjectAtIndex:index withObject:object];
1011 if (index != count) {
1012 WebUndefined *undefined([WebUndefined undefined]);
1013 for (size_t i(count); i != index; ++i)
1014 [self addObject:undefined];
1017 [self addObject:object];
1023 - (bool) cy$deleteProperty:(NSString *)name {
1024 size_t index(CYGetIndex(NULL, name));
1025 if (index == _not(size_t) || index >= [self count])
1026 return [super cy$deleteProperty:name];
1027 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1033 /* Bridge: NSMutableDictionary {{{ */
1034 @implementation NSMutableDictionary (Cycript)
1036 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1037 [self setObject:(value ?: [NSNull null]) forKey:name];
1041 - (bool) cy$deleteProperty:(NSString *)name {
1042 if ([self objectForKey:name] == nil)
1045 [self removeObjectForKey:name];
1052 /* Bridge: NSNumber {{{ */
1053 @implementation NSNumber (Cycript)
1055 - (JSType) cy$JSType {
1056 // XXX: this just seems stupid
1057 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
1060 - (NSObject *) cy$toJSON:(NSString *)key {
1064 - (NSString *) cy$toCYON {
1065 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1068 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1069 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1074 /* Bridge: NSNull {{{ */
1075 @implementation NSNull (Cycript)
1077 - (JSType) cy$JSType {
1081 - (NSObject *) cy$toJSON:(NSString *)key {
1085 - (NSString *) cy$toCYON {
1091 /* Bridge: NSObject {{{ */
1092 @implementation NSObject (Cycript)
1094 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1095 return CYMakeInstance(context, self, false);
1098 - (JSType) cy$JSType {
1099 return kJSTypeObject;
1102 - (NSObject *) cy$toJSON:(NSString *)key {
1103 return [self description];
1106 - (NSString *) cy$toCYON {
1107 return [[self cy$toJSON:@""] cy$toCYON];
1110 - (NSString *) cy$toKey {
1111 return [self cy$toCYON];
1114 - (bool) cy$hasProperty:(NSString *)name {
1118 - (NSObject *) cy$getProperty:(NSString *)name {
1122 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1126 - (bool) cy$deleteProperty:(NSString *)name {
1132 /* Bridge: NSProxy {{{ */
1133 @implementation NSProxy (Cycript)
1135 - (NSObject *) cy$toJSON:(NSString *)key {
1136 return [self description];
1139 - (NSString *) cy$toCYON {
1140 return [[self cy$toJSON:@""] cy$toCYON];
1145 /* Bridge: NSString {{{ */
1146 @implementation NSString (Cycript)
1148 - (JSType) cy$JSType {
1149 return kJSTypeString;
1152 - (NSObject *) cy$toJSON:(NSString *)key {
1156 - (NSString *) cy$toCYON {
1157 // XXX: this should use the better code from Output.cpp
1158 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
1160 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
1161 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
1162 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
1163 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
1164 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
1166 CFStringInsert(json, 0, CFSTR("\""));
1167 CFStringAppend(json, CFSTR("\""));
1169 return [reinterpret_cast<const NSString *>(json) autorelease];
1172 - (NSString *) cy$toKey {
1173 const char *value([self UTF8String]);
1174 size_t size(strlen(value));
1179 if (DigitRange_[value[0]]) {
1180 size_t index(CYGetIndex(NULL, self));
1181 if (index == _not(size_t))
1184 if (!WordStartRange_[value[0]])
1186 for (size_t i(1); i != size; ++i)
1187 if (!WordEndRange_[value[i]])
1194 return [self cy$toCYON];
1197 - (void *) cy$symbol {
1199 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1204 /* Bridge: WebUndefined {{{ */
1205 @implementation WebUndefined (Cycript)
1207 - (JSType) cy$JSType {
1208 return kJSTypeUndefined;
1211 - (NSObject *) cy$toJSON:(NSString *)key {
1215 - (NSString *) cy$toCYON {
1216 return @"undefined";
1219 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1220 return CYJSUndefined(context);
1226 @interface CYJSObject : NSMutableDictionary {
1227 JSObjectRef object_;
1228 JSContextRef context_;
1231 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1233 - (NSString *) cy$toJSON:(NSString *)key;
1235 - (NSUInteger) count;
1236 - (id) objectForKey:(id)key;
1237 - (NSEnumerator *) keyEnumerator;
1238 - (void) setObject:(id)object forKey:(id)key;
1239 - (void) removeObjectForKey:(id)key;
1243 @interface CYJSArray : NSMutableArray {
1244 JSObjectRef object_;
1245 JSContextRef context_;
1248 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1250 - (NSUInteger) count;
1251 - (id) objectAtIndex:(NSUInteger)index;
1253 - (void) addObject:(id)anObject;
1254 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1255 - (void) removeLastObject;
1256 - (void) removeObjectAtIndex:(NSUInteger)index;
1257 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1261 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1262 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1263 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1268 @catch (id error) { \
1269 CYThrow(context, error, exception); \
1273 apr_status_t CYPoolRelease_(void *data) {
1274 id object(reinterpret_cast<id>(data));
1279 id CYPoolRelease(apr_pool_t *pool, id object) {
1282 else if (pool == NULL)
1283 return [object autorelease];
1285 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1290 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1291 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1294 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1295 JSValueRef exception(NULL);
1296 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1297 CYThrow(context, exception);
1298 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1299 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1302 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1303 if (!JSValueIsObjectOfClass(context, object, Instance_))
1304 return CYCastNSObject_(pool, context, object);
1306 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1307 return internal->GetValue();
1311 double CYCastDouble(const char *value, size_t size) {
1313 double number(strtod(value, &end));
1314 if (end != value + size)
1319 double CYCastDouble(const char *value) {
1320 return CYCastDouble(value, strlen(value));
1323 double CYCastDouble(JSContextRef context, JSValueRef value) {
1324 JSValueRef exception(NULL);
1325 double number(JSValueToNumber(context, value, &exception));
1326 CYThrow(context, exception);
1330 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1331 double number(CYCastDouble(context, value));
1332 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1335 CFStringRef CYCopyCFString(const char *value) {
1336 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1339 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1340 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1343 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1344 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1347 bool CYCastBool(JSContextRef context, JSValueRef value) {
1348 return JSValueToBoolean(context, value);
1351 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1355 switch (JSType type = JSValueGetType(context, value)) {
1356 case kJSTypeUndefined:
1357 object = [WebUndefined undefined];
1365 case kJSTypeBoolean:
1366 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1371 object = CYCopyCFNumber(context, value);
1376 object = CYCopyCFString(context, value);
1381 // XXX: this might could be more efficient
1382 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1387 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1394 return CYPoolRelease(pool, object);
1396 return CFRetain(object);
1399 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1400 return CYCFType(pool, context, value, true);
1403 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1404 return CYCFType(pool, context, value, false);
1407 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1409 size_t size(JSPropertyNameArrayGetCount(names));
1410 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1411 for (size_t index(0); index != size; ++index)
1412 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1416 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1417 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1420 void CYThrow(JSContextRef context, JSValueRef value) {
1423 @throw CYCastNSObject(NULL, context, value);
1426 JSValueRef CYJSNull(JSContextRef context) {
1427 return JSValueMakeNull(context);
1430 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1431 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1434 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1435 return CYCastJSValue(context, CYJSString(value));
1438 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1440 return CYJSNull(context);
1441 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1442 return [value cy$JSValueInContext:context];
1444 return CYMakeInstance(context, value, false);
1447 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1448 JSValueRef exception(NULL);
1449 JSObjectRef object(JSValueToObject(context, value, &exception));
1450 CYThrow(context, exception);
1454 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1455 if (exception == NULL)
1457 *exception = CYCastJSValue(context, error);
1460 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1461 JSValueRef exception(NULL);
1462 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1463 CYThrow(context, exception);
1467 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1468 // XXX: this isn't actually correct
1469 return value != NULL && JSValueIsObject(context, value);
1472 @implementation CYJSObject
1474 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1475 if ((self = [super init]) != nil) {
1481 - (NSObject *) cy$toJSON:(NSString *)key {
1482 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1483 if (!CYIsCallable(context_, toJSON))
1484 return [super cy$toJSON:key];
1486 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1487 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1488 // XXX: do I really want an NSNull here?!
1489 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1493 - (NSString *) cy$toCYON {
1494 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1495 if (!CYIsCallable(context_, toCYON)) super:
1496 return [super cy$toCYON];
1497 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1498 return CYCastNSString(NULL, CYJSString(context_, value));
1502 - (NSUInteger) count {
1503 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1504 size_t size(JSPropertyNameArrayGetCount(names));
1505 JSPropertyNameArrayRelease(names);
1509 - (id) objectForKey:(id)key {
1510 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1511 if (JSValueIsUndefined(context_, value))
1513 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1516 - (NSEnumerator *) keyEnumerator {
1517 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1518 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1519 JSPropertyNameArrayRelease(names);
1523 - (void) setObject:(id)object forKey:(id)key {
1524 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1527 - (void) removeObjectForKey:(id)key {
1528 JSValueRef exception(NULL);
1529 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1530 CYThrow(context_, exception);
1535 @implementation CYJSArray
1537 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1538 if ((self = [super init]) != nil) {
1544 - (NSUInteger) count {
1545 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1548 - (id) objectAtIndex:(NSUInteger)index {
1549 size_t bounds([self count]);
1550 if (index >= bounds)
1551 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1552 JSValueRef exception(NULL);
1553 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1554 CYThrow(context_, exception);
1555 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1558 - (void) addObject:(id)object {
1559 JSValueRef exception(NULL);
1560 JSValueRef arguments[1];
1561 arguments[0] = CYCastJSValue(context_, object);
1562 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1563 CYThrow(context_, exception);
1566 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1567 size_t bounds([self count] + 1);
1568 if (index >= bounds)
1569 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1570 JSValueRef exception(NULL);
1571 JSValueRef arguments[3];
1572 arguments[0] = CYCastJSValue(context_, index);
1573 arguments[1] = CYCastJSValue(context_, 0);
1574 arguments[2] = CYCastJSValue(context_, object);
1575 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1576 CYThrow(context_, exception);
1579 - (void) removeLastObject {
1580 JSValueRef exception(NULL);
1581 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1582 CYThrow(context_, exception);
1585 - (void) removeObjectAtIndex:(NSUInteger)index {
1586 size_t bounds([self count]);
1587 if (index >= bounds)
1588 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1589 JSValueRef exception(NULL);
1590 JSValueRef arguments[2];
1591 arguments[0] = CYCastJSValue(context_, index);
1592 arguments[1] = CYCastJSValue(context_, 1);
1593 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1594 CYThrow(context_, exception);
1597 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1598 size_t bounds([self count]);
1599 if (index >= bounds)
1600 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1601 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1606 NSString *CYCopyNSCYON(id value) {
1612 Class _class(object_getClass(value));
1613 SEL sel(@selector(cy$toCYON));
1615 if (Method toCYON = class_getInstanceMethod(_class, sel))
1616 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1617 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1618 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1619 string = [value cy$toCYON];
1622 if (value == NSZombie_)
1623 string = @"_NSZombie_";
1624 else if (_class == NSZombie_)
1625 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1626 // XXX: frowny /in/ the pants
1627 else if (value == NSMessageBuilder_ || value == Object_)
1630 string = [NSString stringWithFormat:@"%@", value];
1633 // XXX: frowny pants
1635 string = @"undefined";
1638 return [string retain];
1641 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1642 if (JSValueIsNull(context, value))
1643 return [@"null" retain];
1647 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1652 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1653 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1656 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1657 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1658 const char *string(CYPoolCString(pool, json));
1664 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1668 JSObjectRef object_;
1676 // XXX: delete object_? ;(
1679 static CYInternal *Get(id self) {
1680 CYInternal *internal(NULL);
1681 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1682 // XXX: do something epic? ;P
1688 static CYInternal *Set(id self) {
1689 CYInternal *internal(NULL);
1690 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1691 if (internal == NULL) {
1692 internal = new CYInternal();
1693 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1696 // XXX: do something epic? ;P
1702 bool HasProperty(JSContextRef context, JSStringRef name) {
1703 if (object_ == NULL)
1705 return JSObjectHasProperty(context, object_, name);
1708 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1709 if (object_ == NULL)
1711 return CYGetProperty(context, object_, name);
1714 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1715 if (object_ == NULL)
1716 object_ = JSObjectMake(context, NULL, NULL);
1717 CYSetProperty(context, object_, name, value);
1721 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1722 Selector_privateData *internal(new Selector_privateData(sel));
1723 return JSObjectMake(context, Selector_, internal);
1726 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1727 Pointer *internal(new Pointer(pointer, context, owner, type));
1728 return JSObjectMake(context, Pointer_, internal);
1731 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1732 Functor_privateData *internal(new Functor_privateData(type, function));
1733 return JSObjectMake(context, Functor_, internal);
1736 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1738 const char *string([CYCastNSString(NULL, value) UTF8String]);
1741 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1742 char *string(new(pool) char[size]);
1743 JSStringGetUTF8CString(value, string, size);
1748 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1749 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1752 bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1753 return CYGetOffset(CYPoolCString(pool, value), index);
1756 // XXX: this macro is unhygenic
1757 #define CYCastCString(context, value) ({ \
1759 if (value == NULL) \
1761 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1762 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1763 utf8 = reinterpret_cast<char *>(alloca(size)); \
1764 JSStringGetUTF8CString(string, utf8, size); \
1765 JSStringRelease(string); \
1771 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1772 switch (JSValueGetType(context, value)) {
1775 /*case kJSTypeString:
1776 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1778 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1779 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1780 return internal->value_;
1783 double number(CYCastDouble(context, value));
1784 if (std::isnan(number))
1785 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1786 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1790 template <typename Type_>
1791 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1792 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1795 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1796 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1797 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1798 return reinterpret_cast<SEL>(internal->value_);
1800 return CYCastPointer<SEL>(context, value);
1803 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1804 switch (type->primitive) {
1805 case sig::boolean_P:
1806 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1809 #define CYPoolFFI_(primitive, native) \
1810 case sig::primitive ## _P: \
1811 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1814 CYPoolFFI_(uchar, unsigned char)
1815 CYPoolFFI_(char, char)
1816 CYPoolFFI_(ushort, unsigned short)
1817 CYPoolFFI_(short, short)
1818 CYPoolFFI_(ulong, unsigned long)
1819 CYPoolFFI_(long, long)
1820 CYPoolFFI_(uint, unsigned int)
1821 CYPoolFFI_(int, int)
1822 CYPoolFFI_(ulonglong, unsigned long long)
1823 CYPoolFFI_(longlong, long long)
1824 CYPoolFFI_(float, float)
1825 CYPoolFFI_(double, double)
1828 case sig::typename_P:
1829 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1832 case sig::selector_P:
1833 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1836 case sig::pointer_P:
1837 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1841 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1844 case sig::struct_P: {
1845 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1846 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1847 for (size_t index(0); index != type->data.signature.count; ++index) {
1848 sig::Element *element(&type->data.signature.elements[index]);
1849 ffi_type *field(ffi->elements[index]);
1852 if (aggregate == NULL)
1855 rhs = CYGetProperty(context, aggregate, index);
1856 if (JSValueIsUndefined(context, rhs)) {
1857 if (element->name != NULL)
1858 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1861 if (JSValueIsUndefined(context, rhs)) undefined:
1862 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1866 CYPoolFFI(pool, context, element->type, field, base, rhs);
1868 base += field->size;
1876 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1881 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1884 switch (type->primitive) {
1885 case sig::boolean_P:
1886 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1889 #define CYFromFFI_(primitive, native) \
1890 case sig::primitive ## _P: \
1891 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1894 CYFromFFI_(uchar, unsigned char)
1895 CYFromFFI_(char, char)
1896 CYFromFFI_(ushort, unsigned short)
1897 CYFromFFI_(short, short)
1898 CYFromFFI_(ulong, unsigned long)
1899 CYFromFFI_(long, long)
1900 CYFromFFI_(uint, unsigned int)
1901 CYFromFFI_(int, int)
1902 CYFromFFI_(ulonglong, unsigned long long)
1903 CYFromFFI_(longlong, long long)
1904 CYFromFFI_(float, float)
1905 CYFromFFI_(double, double)
1907 case sig::object_P: {
1908 if (id object = *reinterpret_cast<id *>(data)) {
1909 value = CYCastJSValue(context, object);
1915 case sig::typename_P:
1916 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1919 case sig::selector_P:
1920 if (SEL sel = *reinterpret_cast<SEL *>(data))
1921 value = CYMakeSelector(context, sel);
1925 case sig::pointer_P:
1926 if (void *pointer = *reinterpret_cast<void **>(data))
1927 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1932 if (char *utf8 = *reinterpret_cast<char **>(data))
1933 value = CYCastJSValue(context, utf8);
1938 value = CYMakeStruct(context, data, type, ffi, owner);
1942 value = CYJSUndefined(context);
1946 value = CYJSNull(context);
1950 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1957 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1958 if (Method method = class_getInstanceMethod(_class, selector)) {
1962 method_getReturnType(method, type, sizeof(type));
1967 // XXX: possibly use a more "awesome" check?
1971 const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
1973 return method_getTypeEncoding(method);
1974 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1975 return CYPoolCString(pool, type);
1980 void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1981 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1983 JSContextRef context(internal->context_);
1985 size_t count(internal->cif_.nargs);
1986 JSValueRef values[count];
1988 for (size_t index(0); index != count; ++index)
1989 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1991 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
1992 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1995 void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1996 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1998 JSContextRef context(internal->context_);
2000 size_t count(internal->cif_.nargs);
2001 JSValueRef values[count];
2003 for (size_t index(0); index != count; ++index)
2004 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2006 JSObjectRef _this(CYCastJSObject(context, values[0]));
2008 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2009 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2012 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2013 // XXX: in case of exceptions this will leak
2014 // XXX: in point of fact, this may /need/ to leak :(
2015 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2017 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2018 NULL, sizeof(ffi_closure),
2019 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2023 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2024 _assert(status == FFI_OK);
2026 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2028 internal->value_ = closure;
2033 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2034 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2035 return JSObjectMake(context, Functor_, internal);
2038 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2039 JSValueRef exception(NULL);
2040 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2041 CYThrow(context, exception);
2044 JSObjectRef function(CYCastJSObject(context, value));
2045 return CYMakeFunctor(context, function, type);
2047 void (*function)()(CYCastPointer<void (*)()>(context, value));
2048 return CYMakeFunctor(context, function, type);
2052 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2053 Message_privateData *internal(new Message_privateData(sel, type, imp));
2054 return JSObjectMake(context, Message_, internal);
2057 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2058 JSObjectRef function(CYCastJSObject(context, value));
2059 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2060 return reinterpret_cast<IMP>(internal->GetValue());
2063 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2064 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2065 Class _class(internal->GetValue());
2068 const char *name(CYPoolCString(pool, property));
2070 if (SEL sel = sel_getUid(name))
2071 if (class_getInstanceMethod(_class, sel) != NULL)
2077 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2078 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2079 Class _class(internal->GetValue());
2082 const char *name(CYPoolCString(pool, property));
2084 if (SEL sel = sel_getUid(name))
2085 if (Method method = class_getInstanceMethod(_class, sel))
2086 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2091 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2092 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2093 Class _class(internal->GetValue());
2096 const char *name(CYPoolCString(pool, property));
2098 SEL sel(sel_registerName(name));
2100 Method method(class_getInstanceMethod(_class, sel));
2105 if (JSValueIsObjectOfClass(context, value, Message_)) {
2106 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2107 type = sig::Unparse(pool, &message->signature_);
2108 imp = reinterpret_cast<IMP>(message->GetValue());
2110 type = CYPoolTypeEncoding(pool, _class, sel, method);
2111 imp = CYMakeMessage(context, value, type);
2115 method_setImplementation(method, imp);
2117 class_replaceMethod(_class, sel, imp, type);
2123 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2124 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2125 Class _class(internal->GetValue());
2128 const char *name(CYPoolCString(pool, property));
2130 if (SEL sel = sel_getUid(name))
2131 if (Method method = class_getInstanceMethod(_class, sel)) {
2132 objc_method_list list = {NULL, 1, {method}};
2133 class_removeMethods(_class, &list);
2141 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2142 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2143 Class _class(internal->GetValue());
2146 Method *data(class_copyMethodList(_class, &size));
2147 for (size_t i(0); i != size; ++i)
2148 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2152 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2153 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2154 id self(internal->GetValue());
2156 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2160 NSString *name(CYCastNSString(pool, property));
2162 if (CYInternal *internal = CYInternal::Get(self))
2163 if (internal->HasProperty(context, property))
2166 Class _class(object_getClass(self));
2169 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2170 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2171 if ([self cy$hasProperty:name])
2173 } CYPoolCatch(false)
2175 const char *string(CYPoolCString(pool, name));
2177 if (class_getProperty(_class, string) != NULL)
2180 if (SEL sel = sel_getUid(string))
2181 if (CYImplements(self, _class, sel, true))
2187 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2188 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2189 id self(internal->GetValue());
2191 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2192 return Internal::Make(context, self, object);
2196 NSString *name(CYCastNSString(pool, property));
2198 if (CYInternal *internal = CYInternal::Get(self))
2199 if (JSValueRef value = internal->GetProperty(context, property))
2203 if (NSObject *data = [self cy$getProperty:name])
2204 return CYCastJSValue(context, data);
2207 const char *string(CYPoolCString(pool, name));
2208 Class _class(object_getClass(self));
2210 if (objc_property_t property = class_getProperty(_class, string)) {
2211 PropertyAttributes attributes(property);
2212 SEL sel(sel_registerName(attributes.Getter()));
2213 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2216 if (SEL sel = sel_getUid(string))
2217 if (CYImplements(self, _class, sel, true))
2218 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2224 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2225 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2226 id self(internal->GetValue());
2231 NSString *name(CYCastNSString(pool, property));
2232 NSString *data(CYCastNSObject(pool, context, value));
2235 if ([self cy$setProperty:name to:data])
2239 const char *string(CYPoolCString(pool, name));
2240 Class _class(object_getClass(self));
2242 if (objc_property_t property = class_getProperty(_class, string)) {
2243 PropertyAttributes attributes(property);
2244 if (const char *setter = attributes.Setter()) {
2245 SEL sel(sel_registerName(setter));
2246 JSValueRef arguments[1] = {value};
2247 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2252 size_t length(strlen(string));
2254 char set[length + 5];
2260 if (string[0] != '\0') {
2261 set[3] = toupper(string[0]);
2262 memcpy(set + 4, string + 1, length - 1);
2265 set[length + 3] = ':';
2266 set[length + 4] = '\0';
2268 if (SEL sel = sel_getUid(set))
2269 if (CYImplements(self, _class, sel, false)) {
2270 JSValueRef arguments[1] = {value};
2271 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2274 if (CYInternal *internal = CYInternal::Set(self)) {
2275 internal->SetProperty(context, property, value);
2283 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2284 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2285 id self(internal->GetValue());
2289 NSString *name(CYCastNSString(NULL, property));
2290 return [self cy$deleteProperty:name];
2295 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2296 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2297 id self(internal->GetValue());
2300 Class _class(object_getClass(self));
2304 objc_property_t *data(class_copyPropertyList(_class, &size));
2305 for (size_t i(0); i != size; ++i)
2306 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2311 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2313 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2314 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2319 bool CYIsClass(id self) {
2320 // XXX: this is a lame object_isClass
2321 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2324 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2325 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2326 Class _class(internal->GetValue());
2327 if (!CYIsClass(_class))
2330 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2331 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2332 // XXX: this isn't always safe
2334 return [linternal->GetValue() isKindOfClass:_class];
2341 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2342 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2345 id self(internal->GetValue());
2346 const char *name(CYPoolCString(pool, property));
2348 if (object_getInstanceVariable(self, name, NULL) != NULL)
2354 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2355 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2359 id self(internal->GetValue());
2360 const char *name(CYPoolCString(pool, property));
2362 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2363 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2364 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2371 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2372 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2376 id self(internal->GetValue());
2377 const char *name(CYPoolCString(pool, property));
2379 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2380 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2381 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2389 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2390 if (Class super = class_getSuperclass(_class))
2391 Internal_getPropertyNames_(super, names);
2394 Ivar *data(class_copyIvarList(_class, &size));
2395 for (size_t i(0); i != size; ++i)
2396 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2400 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2401 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2404 id self(internal->GetValue());
2405 Class _class(object_getClass(self));
2407 Internal_getPropertyNames_(_class, names);
2410 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2411 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2412 return internal->GetOwner();
2415 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2416 Type_privateData *typical(internal->type_);
2417 sig::Type *type(typical->type_);
2421 const char *name(CYPoolCString(pool, property));
2422 size_t length(strlen(name));
2423 double number(CYCastDouble(name, length));
2425 size_t count(type->data.signature.count);
2427 if (std::isnan(number)) {
2428 if (property == NULL)
2431 sig::Element *elements(type->data.signature.elements);
2433 for (size_t local(0); local != count; ++local) {
2434 sig::Element *element(&elements[local]);
2435 if (element->name != NULL && strcmp(name, element->name) == 0) {
2443 index = static_cast<ssize_t>(number);
2444 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2449 ffi_type **elements(typical->GetFFI()->elements);
2451 base = reinterpret_cast<uint8_t *>(internal->value_);
2452 for (ssize_t local(0); local != index; ++local)
2453 base += elements[local]->size;
2458 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2459 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2460 Type_privateData *typical(internal->type_);
2462 ffi_type *ffi(typical->GetFFI());
2464 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2465 base += ffi->size * index;
2467 JSObjectRef owner(internal->GetOwner() ?: object);
2470 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2474 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2476 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2477 Type_privateData *typical(internal->type_);
2479 if (typical->type_ == NULL)
2483 if (!CYGetOffset(pool, property, offset))
2486 return Pointer_getIndex(context, object, offset, exception);
2489 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2490 return Pointer_getIndex(context, object, 0, exception);
2493 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2494 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2495 Type_privateData *typical(internal->type_);
2497 ffi_type *ffi(typical->GetFFI());
2499 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2500 base += ffi->size * index;
2503 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2508 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2510 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2511 Type_privateData *typical(internal->type_);
2513 if (typical->type_ == NULL)
2517 if (!CYGetOffset(pool, property, offset))
2520 return Pointer_setIndex(context, object, offset, value, exception);
2523 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2524 return Pointer_setIndex(context, object, 0, value, exception);
2527 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2528 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2529 Type_privateData *typical(internal->type_);
2530 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2533 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2535 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2536 Type_privateData *typical(internal->type_);
2541 if (!Index_(pool, internal, property, index, base))
2544 JSObjectRef owner(internal->GetOwner() ?: object);
2547 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2551 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2553 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2554 Type_privateData *typical(internal->type_);
2559 if (!Index_(pool, internal, property, index, base))
2563 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2568 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2569 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2570 Type_privateData *typical(internal->type_);
2571 sig::Type *type(typical->type_);
2576 size_t count(type->data.signature.count);
2577 sig::Element *elements(type->data.signature.elements);
2581 for (size_t index(0); index != count; ++index) {
2583 name = elements[index].name;
2586 sprintf(number, "%lu", index);
2590 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2594 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)()) {
2596 if (setups + count != signature->count - 1)
2597 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2599 size_t size(setups + count);
2601 memcpy(values, setup, sizeof(void *) * setups);
2603 for (size_t index(setups); index != size; ++index) {
2604 sig::Element *element(&signature->elements[index + 1]);
2605 ffi_type *ffi(cif->arg_types[index]);
2607 values[index] = new(pool) uint8_t[ffi->size];
2608 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2611 uint8_t value[cif->rtype->size];
2612 ffi_call(cif, function, value, values);
2614 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2618 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2621 NSString *name(CYCastNSString(pool, property));
2622 if (Class _class = NSClassFromString(name))
2623 return CYMakeInstance(context, _class, true);
2628 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2629 size_t size(objc_getClassList(NULL, 0));
2630 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2633 size_t writ(objc_getClassList(data, size));
2636 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2642 for (size_t i(0); i != writ; ++i)
2643 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2649 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2650 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2654 const char *name(CYPoolCString(pool, property));
2656 const char **data(objc_copyClassNamesForImage(internal, &size));
2658 for (size_t i(0); i != size; ++i)
2659 if (strcmp(name, data[i]) == 0) {
2660 if (Class _class = objc_getClass(name)) {
2661 value = CYMakeInstance(context, _class, true);
2673 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2674 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2676 const char **data(objc_copyClassNamesForImage(internal, &size));
2677 for (size_t i(0); i != size; ++i)
2678 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2682 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2685 const char *name(CYPoolCString(pool, property));
2687 const char **data(objc_copyImageNames(&size));
2688 for (size_t i(0); i != size; ++i)
2689 if (strcmp(name, data[i]) == 0) {
2698 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2699 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2704 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2706 const char **data(objc_copyImageNames(&size));
2707 for (size_t i(0); i != size; ++i)
2708 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2712 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2715 NSString *name(CYCastNSString(pool, property));
2716 if (Protocol *protocol = NSProtocolFromString(name))
2717 return CYMakeInstance(context, protocol, true);
2722 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2724 Protocol **data(objc_copyProtocolList(&size));
2725 for (size_t i(0); i != size; ++i)
2726 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2730 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2731 if (JSStringIsEqualToUTF8CString(property, "nil"))
2732 return Instance::Make(context, nil);
2736 NSString *name(CYCastNSString(pool, property));
2737 if (Class _class = NSClassFromString(name))
2738 return CYMakeInstance(context, _class, true);
2739 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2740 switch ([[entry objectAtIndex:0] intValue]) {
2742 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2744 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2746 // XXX: this is horrendously inefficient
2747 sig::Signature signature;
2748 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2750 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2751 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2757 bool stret(ffi_type *ffi_type) {
2758 return ffi_type->type == FFI_TYPE_STRUCT && (
2759 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2760 struct_forward_array[ffi_type->size] != 0
2765 int *_NSGetArgc(void);
2766 char ***_NSGetArgv(void);
2767 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2770 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2772 NSLog(@"%s", CYCastCString(context, arguments[0]));
2773 return CYJSUndefined(context);
2777 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2780 Class _class(object_getClass(self));
2781 if (Method method = class_getInstanceMethod(_class, _cmd))
2782 type = method_getTypeEncoding(method);
2786 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2788 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2789 type = CYPoolCString(pool, [method _typeString]);
2798 sig::Signature signature;
2799 sig::Parse(pool, &signature, type, &Structor_);
2802 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2804 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2805 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2808 static size_t Nonce_(0);
2810 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2812 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
2813 return CYCastJSValue(context, name);
2816 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2826 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2828 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2829 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2830 self = internal->GetValue();
2831 uninitialized = internal->IsUninitialized();
2833 internal->value_ = nil;
2835 self = CYCastNSObject(pool, context, arguments[0]);
2836 uninitialized = false;
2840 return CYJSNull(context);
2842 _cmd = CYCastSEL(context, arguments[1]);
2845 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2848 /* Hook: objc_registerClassPair {{{ */
2849 // XXX: replace this with associated objects
2851 MSHook(void, CYDealloc, id self, SEL sel) {
2852 CYInternal *internal;
2853 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2854 if (internal != NULL)
2856 _CYDealloc(self, sel);
2859 MSHook(void, objc_registerClassPair, Class _class) {
2860 Class super(class_getSuperclass(_class));
2861 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2862 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2863 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2866 _objc_registerClassPair(_class);
2869 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2872 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2874 Class _class(CYCastNSObject(pool, context, arguments[0]));
2875 $objc_registerClassPair(_class);
2876 return CYJSUndefined(context);
2881 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2882 JSValueRef setup[count + 2];
2885 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2886 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2889 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2891 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2893 // XXX: handle Instance::Uninitialized?
2894 id self(CYCastNSObject(pool, context, _this));
2898 setup[1] = &internal->sel_;
2900 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2903 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2905 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2906 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2909 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2912 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2913 const char *name(CYCastCString(context, arguments[0]));
2914 return CYMakeSelector(context, sel_registerName(name));
2918 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2921 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2923 void *value(CYCastPointer<void *>(context, arguments[0]));
2924 const char *type(CYCastCString(context, arguments[1]));
2928 sig::Signature signature;
2929 sig::Parse(pool, &signature, type, &Structor_);
2931 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2935 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2936 Type_privateData *internal(new Type_privateData(NULL, type));
2937 return JSObjectMake(context, Type_, internal);
2940 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2943 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2944 const char *type(CYCastCString(context, arguments[0]));
2945 return CYMakeType(context, object, type);
2949 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2952 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2953 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2954 sig::Type *type(internal->type_);
2955 ffi_type *ffi(internal->GetFFI());
2957 uint8_t value[ffi->size];
2959 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2960 return CYFromFFI(context, type, ffi, value);
2964 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2967 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2968 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2969 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2971 void *value(malloc(internal->GetFFI()->size * size));
2972 return CYMakePointer(context, value, internal->type_, internal->ffi_, NULL);
2976 JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2979 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
2980 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2981 return Instance::Make(context, self);
2985 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2988 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2989 const char *type(CYCastCString(context, arguments[1]));
2990 return CYMakeFunctor(context, arguments[0], type);
2994 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2995 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2996 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2999 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3000 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3001 Type_privateData *typical(internal->GetType());
3006 if (typical == NULL) {
3010 type = typical->type_;
3011 ffi = typical->ffi_;
3014 return CYMakePointer(context, &internal->value_, type, ffi, object);
3017 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3018 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3021 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3025 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3026 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3029 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3030 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3032 sprintf(string, "%p", internal->value_);
3035 return CYCastJSValue(context, string);
3039 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3040 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3041 return Instance::Make(context, object_getClass(internal->GetValue()));
3044 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3045 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3046 id self(internal->GetValue());
3047 if (!CYIsClass(self))
3048 return CYJSUndefined(context);
3050 return CYGetClassPrototype(context, self);
3054 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3055 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3056 id self(internal->GetValue());
3057 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3058 return CYJSUndefined(context);
3059 return Messages::Make(context, self);
3062 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3063 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3066 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3070 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
3075 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3076 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3079 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3083 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3084 // XXX: check for support of cy$toJSON?
3085 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3090 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3091 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3094 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3098 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3103 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3104 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3107 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3111 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3112 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3115 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3116 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3117 const char *name(sel_getName(internal->GetValue()));
3121 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3126 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3129 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
3131 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3132 Class _class(CYCastNSObject(pool, context, arguments[0]));
3133 SEL sel(internal->GetValue());
3134 Method method(class_getInstanceMethod(_class, sel));
3135 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3136 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3140 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3142 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3144 const char *type(sig::Unparse(pool, internal->type_));
3146 return CYCastJSValue(context, CYJSString(type));
3151 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3153 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3155 const char *type(sig::Unparse(pool, internal->type_));
3157 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
3162 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3163 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3166 static JSStaticValue CYValue_staticValues[2] = {
3167 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3168 {NULL, NULL, NULL, 0}
3171 static JSStaticValue Pointer_staticValues[2] = {
3172 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3173 {NULL, NULL, NULL, 0}
3176 static JSStaticFunction Pointer_staticFunctions[4] = {
3177 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3178 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3179 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3183 static JSStaticFunction Struct_staticFunctions[2] = {
3184 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3188 static JSStaticFunction Functor_staticFunctions[4] = {
3189 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3190 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3191 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3195 static JSStaticValue Instance_staticValues[5] = {
3196 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3197 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3198 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3199 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3200 {NULL, NULL, NULL, 0}
3203 static JSStaticFunction Instance_staticFunctions[5] = {
3204 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3205 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3206 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3207 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3211 static JSStaticFunction Internal_staticFunctions[2] = {
3212 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3216 static JSStaticFunction Selector_staticFunctions[5] = {
3217 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3218 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3219 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3220 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3224 static JSStaticFunction Type_staticFunctions[4] = {
3225 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3226 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3227 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3231 CYDriver::CYDriver(const std::string &filename) :
3236 filename_(filename),
3242 CYDriver::~CYDriver() {
3246 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
3247 CYDriver::Error error;
3248 error.location_ = location;
3249 error.message_ = message;
3250 driver.errors_.push_back(error);
3253 void CYSetArgs(int argc, const char *argv[]) {
3254 JSContextRef context(CYGetJSContext());
3255 JSValueRef args[argc];
3256 for (int i(0); i != argc; ++i)
3257 args[i] = CYCastJSValue(context, argv[i]);
3258 JSValueRef exception(NULL);
3259 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3260 CYThrow(context, exception);
3261 CYSetProperty(context, System_, CYJSString("args"), array);
3264 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3265 return JSContextGetGlobalObject(context);
3268 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3269 JSContextRef context(CYGetJSContext());
3270 JSValueRef exception(NULL), result;
3273 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3274 } catch (const char *error) {
3278 if (exception != NULL) { error:
3283 if (JSValueIsUndefined(context, result))
3289 json = CYPoolCCYON(pool, context, result, &exception);
3290 } catch (const char *error) {
3294 if (exception != NULL)
3297 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3301 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
3302 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
3310 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
3311 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
3323 const char * volatile data_;
3326 // XXX: this is "tre lame"
3327 @interface CYClient_ : NSObject {
3330 - (void) execute:(NSValue *)value;
3334 @implementation CYClient_
3336 - (void) execute:(NSValue *)value {
3337 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3338 const char *data(execute->data_);
3339 execute->data_ = NULL;
3340 execute->data_ = CYExecute(execute->pool_, data);
3349 apr_thread_t *thread_;
3351 CYClient(int socket) :
3357 _syscall(close(socket_));
3360 void Handle() { _pooled
3361 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3365 if (!CYRecvAll(socket_, &size, sizeof(size)))
3369 char *data(new(pool) char[size + 1]);
3370 if (!CYRecvAll(socket_, data, size))
3374 CYDriver driver("");
3375 cy::parser parser(driver);
3377 driver.data_ = data;
3378 driver.size_ = size;
3381 if (parser.parse() != 0 || !driver.errors_.empty()) {
3383 size = _not(size_t);
3385 std::ostringstream str;
3386 driver.source_->Show(str);
3387 std::string code(str.str());
3388 CYExecute_ execute = {pool, code.c_str()};
3389 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3390 json = execute.data_;
3391 size = json == NULL ? _not(size_t) : strlen(json);
3394 if (!CYSendAll(socket_, &size, sizeof(size)))
3397 if (!CYSendAll(socket_, json, size))
3403 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3404 CYClient *client(reinterpret_cast<CYClient *>(data));
3410 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3411 CYClient *client(new(pool) CYClient(socket));
3412 apr_threadattr_t *attr;
3413 _aprcall(apr_threadattr_create(&attr, client->pool_));
3414 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3417 MSInitialize { _pooled
3418 _aprcall(apr_initialize());
3419 _aprcall(apr_pool_create(&Pool_, NULL));
3421 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3422 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3424 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3426 NSArray_ = objc_getClass("NSArray");
3427 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3428 NSCFType_ = objc_getClass("NSCFType");
3429 NSDictionary_ = objc_getClass("NSDictonary");
3430 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3431 NSZombie_ = objc_getClass("_NSZombie_");
3432 Object_ = objc_getClass("Object");
3435 JSGlobalContextRef CYGetJSContext() {
3436 if (Context_ == NULL) {
3437 JSClassDefinition definition;
3439 definition = kJSClassDefinitionEmpty;
3440 definition.className = "Functor";
3441 definition.staticFunctions = Functor_staticFunctions;
3442 definition.callAsFunction = &Functor_callAsFunction;
3443 definition.finalize = &Finalize;
3444 Functor_ = JSClassCreate(&definition);
3446 definition = kJSClassDefinitionEmpty;
3447 definition.className = "Instance";
3448 definition.staticValues = Instance_staticValues;
3449 definition.staticFunctions = Instance_staticFunctions;
3450 definition.hasProperty = &Instance_hasProperty;
3451 definition.getProperty = &Instance_getProperty;
3452 definition.setProperty = &Instance_setProperty;
3453 definition.deleteProperty = &Instance_deleteProperty;
3454 definition.getPropertyNames = &Instance_getPropertyNames;
3455 definition.callAsConstructor = &Instance_callAsConstructor;
3456 definition.hasInstance = &Instance_hasInstance;
3457 definition.finalize = &Finalize;
3458 Instance_ = JSClassCreate(&definition);
3460 definition = kJSClassDefinitionEmpty;
3461 definition.className = "Internal";
3462 definition.staticFunctions = Internal_staticFunctions;
3463 definition.hasProperty = &Internal_hasProperty;
3464 definition.getProperty = &Internal_getProperty;
3465 definition.setProperty = &Internal_setProperty;
3466 definition.getPropertyNames = &Internal_getPropertyNames;
3467 definition.finalize = &Finalize;
3468 Internal_ = JSClassCreate(&definition);
3470 definition = kJSClassDefinitionEmpty;
3471 definition.className = "Message";
3472 definition.staticFunctions = Functor_staticFunctions;
3473 definition.callAsFunction = &Message_callAsFunction;
3474 definition.finalize = &Finalize;
3475 Message_ = JSClassCreate(&definition);
3477 definition = kJSClassDefinitionEmpty;
3478 definition.className = "Messages";
3479 definition.hasProperty = &Messages_hasProperty;
3480 definition.getProperty = &Messages_getProperty;
3481 definition.setProperty = &Messages_setProperty;
3483 definition.deleteProperty = &Messages_deleteProperty;
3485 definition.getPropertyNames = &Messages_getPropertyNames;
3486 definition.finalize = &Finalize;
3487 Messages_ = JSClassCreate(&definition);
3489 definition = kJSClassDefinitionEmpty;
3490 definition.className = "NSArrayPrototype";
3491 //definition.hasProperty = &NSArrayPrototype_hasProperty;
3492 //definition.getProperty = &NSArrayPrototype_getProperty;
3493 //definition.setProperty = &NSArrayPrototype_setProperty;
3494 //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
3495 //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
3496 NSArrayPrototype_ = JSClassCreate(&definition);
3498 definition = kJSClassDefinitionEmpty;
3499 definition.className = "Pointer";
3500 definition.staticValues = Pointer_staticValues;
3501 definition.staticFunctions = Pointer_staticFunctions;
3502 definition.getProperty = &Pointer_getProperty;
3503 definition.setProperty = &Pointer_setProperty;
3504 definition.finalize = &Finalize;
3505 Pointer_ = JSClassCreate(&definition);
3507 definition = kJSClassDefinitionEmpty;
3508 definition.className = "Selector";
3509 definition.staticValues = CYValue_staticValues;
3510 definition.staticFunctions = Selector_staticFunctions;
3511 definition.callAsFunction = &Selector_callAsFunction;
3512 definition.finalize = &Finalize;
3513 Selector_ = JSClassCreate(&definition);
3515 definition = kJSClassDefinitionEmpty;
3516 definition.className = "Struct";
3517 definition.staticFunctions = Struct_staticFunctions;
3518 definition.getProperty = &Struct_getProperty;
3519 definition.setProperty = &Struct_setProperty;
3520 definition.getPropertyNames = &Struct_getPropertyNames;
3521 definition.finalize = &Finalize;
3522 Struct_ = JSClassCreate(&definition);
3524 definition = kJSClassDefinitionEmpty;
3525 definition.className = "Type";
3526 definition.staticFunctions = Type_staticFunctions;
3527 //definition.getProperty = &Type_getProperty;
3528 definition.callAsFunction = &Type_callAsFunction;
3529 definition.callAsConstructor = &Type_callAsConstructor;
3530 definition.finalize = &Finalize;
3531 Type_ = JSClassCreate(&definition);
3533 definition = kJSClassDefinitionEmpty;
3534 definition.className = "Runtime";
3535 definition.getProperty = &Runtime_getProperty;
3536 Runtime_ = JSClassCreate(&definition);
3538 definition = kJSClassDefinitionEmpty;
3539 definition.className = "ObjectiveC::Classes";
3540 definition.getProperty = &ObjectiveC_Classes_getProperty;
3541 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3542 ObjectiveC_Classes_ = JSClassCreate(&definition);
3544 definition = kJSClassDefinitionEmpty;
3545 definition.className = "ObjectiveC::Images";
3546 definition.getProperty = &ObjectiveC_Images_getProperty;
3547 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3548 ObjectiveC_Images_ = JSClassCreate(&definition);
3550 definition = kJSClassDefinitionEmpty;
3551 definition.className = "ObjectiveC::Image::Classes";
3552 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3553 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3554 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3556 definition = kJSClassDefinitionEmpty;
3557 definition.className = "ObjectiveC::Protocols";
3558 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3559 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3560 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3562 definition = kJSClassDefinitionEmpty;
3563 //definition.getProperty = &Global_getProperty;
3564 JSClassRef Global(JSClassCreate(&definition));
3566 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3569 JSObjectRef global(CYGetGlobalObject(context));
3571 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3572 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3573 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3575 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3576 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3577 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3579 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3580 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3581 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3583 length_ = JSStringCreateWithUTF8CString("length");
3584 message_ = JSStringCreateWithUTF8CString("message");
3585 name_ = JSStringCreateWithUTF8CString("name");
3586 prototype_ = JSStringCreateWithUTF8CString("prototype");
3587 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3588 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3590 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3591 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3593 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3594 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3595 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3596 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3598 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3599 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3600 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3601 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3603 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3605 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3606 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3607 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3608 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3610 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3611 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3612 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3613 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3614 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3616 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3618 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3620 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3621 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3622 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3624 System_ = JSObjectMake(context, NULL, NULL);
3625 CYSetProperty(context, global, CYJSString("system"), System_);
3626 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3627 //CYSetProperty(context, System_, CYJSString("global"), global);
3629 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3631 Result_ = JSStringCreateWithUTF8CString("_");
3633 JSValueProtect(context, Array_);
3634 JSValueProtect(context, Function_);
3635 JSValueProtect(context, String_);
3637 JSValueProtect(context, Instance_prototype_);
3638 JSValueProtect(context, Object_prototype_);
3640 JSValueProtect(context, Array_prototype_);
3641 JSValueProtect(context, Array_pop_);
3642 JSValueProtect(context, Array_push_);
3643 JSValueProtect(context, Array_splice_);