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);
339 Transient = (1 << 0),
340 Uninitialized = (1 << 1),
345 Instance(id value, Flags flags) :
351 virtual ~Instance() {
352 if ((flags_ & Transient) == 0)
353 // XXX: does this handle background threads correctly?
354 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
357 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
358 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
359 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object == nil ? nil : object_getClass(object)));
363 id GetValue() const {
364 return reinterpret_cast<id>(value_);
367 bool IsUninitialized() const {
368 return (flags_ & Uninitialized) != 0;
371 virtual Type_privateData *GetType() const;
377 Messages(Class value) :
382 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
383 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
384 if (_class == NSArray_)
386 if (Class super = class_getSuperclass(_class))
387 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
389 JSObjectSetPrototype(context, value, Array_prototype_);*/
393 Class GetValue() const {
394 return reinterpret_cast<Class>(value_);
403 Internal(id value, JSObjectRef owner) :
409 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
410 return JSObjectMake(context, Internal_, new Internal(object, owner));
413 id GetValue() const {
414 return reinterpret_cast<id>(value_);
420 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
422 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
423 lhs.name = apr_pstrdup(pool, rhs.name);
424 if (rhs.type == NULL)
427 lhs.type = new(pool) Type;
428 Copy(pool, *lhs.type, *rhs.type);
430 lhs.offset = rhs.offset;
433 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
434 size_t count(rhs.count);
436 lhs.elements = new(pool) Element[count];
437 for (size_t index(0); index != count; ++index)
438 Copy(pool, lhs.elements[index], rhs.elements[index]);
441 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
442 lhs.primitive = rhs.primitive;
443 lhs.name = apr_pstrdup(pool, rhs.name);
444 lhs.flags = rhs.flags;
446 if (sig::IsAggregate(rhs.primitive))
447 Copy(pool, lhs.data.signature, rhs.data.signature);
449 if (rhs.data.data.type != NULL) {
450 lhs.data.data.type = new(pool) Type;
451 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
454 lhs.data.data.size = rhs.data.data.size;
458 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
460 lhs.alignment = rhs.alignment;
462 if (rhs.elements == NULL)
466 while (rhs.elements[count] != NULL)
469 lhs.elements = new(pool) ffi_type *[count + 1];
470 lhs.elements[count] = NULL;
472 for (size_t index(0); index != count; ++index) {
473 // XXX: if these are libffi native then you can just take them
474 ffi_type *ffi(new(pool) ffi_type);
475 lhs.elements[index] = ffi;
476 sig::Copy(pool, *ffi, *rhs.elements[index]);
483 struct CStringMapLess :
484 std::binary_function<const char *, const char *, bool>
486 _finline bool operator ()(const char *lhs, const char *rhs) const {
487 return strcmp(lhs, rhs) < 0;
491 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
496 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
497 switch ([[entry objectAtIndex:0] intValue]) {
499 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
503 sig::Signature signature;
504 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
505 type = signature.elements[0].type;
511 struct Type_privateData :
514 static Type_privateData *Object;
515 static Type_privateData *Selector;
520 void Set(sig::Type *type) {
521 type_ = new(pool_) sig::Type;
522 sig::Copy(pool_, *type_, *type);
525 Type_privateData(apr_pool_t *pool, const char *type) :
531 sig::Signature signature;
532 sig::Parse(pool_, &signature, type, &Structor_);
533 type_ = signature.elements[0].type;
536 Type_privateData(sig::Type *type) :
543 Type_privateData(sig::Type *type, ffi_type *ffi) {
544 ffi_ = new(pool_) ffi_type;
545 sig::Copy(pool_, *ffi_, *ffi);
551 ffi_ = new(pool_) ffi_type;
553 sig::Element element;
555 element.type = type_;
558 sig::Signature signature;
559 signature.elements = &element;
563 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
571 Type_privateData *Type_privateData::Object;
572 Type_privateData *Type_privateData::Selector;
574 Type_privateData *Instance::GetType() const {
575 return Type_privateData::Object;
578 Type_privateData *Selector_privateData::GetType() const {
579 return Type_privateData::Selector;
586 Type_privateData *type_;
588 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
591 type_(new(pool_) Type_privateData(type))
596 struct Struct_privateData :
600 Type_privateData *type_;
602 Struct_privateData(JSObjectRef owner) :
608 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
609 static TypeMap Types_;
611 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
612 Struct_privateData *internal(new Struct_privateData(owner));
613 apr_pool_t *pool(internal->pool_);
614 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
615 internal->type_ = typical;
618 internal->value_ = data;
620 size_t size(typical->GetFFI()->size);
621 void *copy(apr_palloc(internal->pool_, size));
622 memcpy(copy, data, size);
623 internal->value_ = copy;
626 return JSObjectMake(context, Struct_, internal);
629 struct Functor_privateData :
632 sig::Signature signature_;
636 Functor_privateData(const char *type, void (*value)()) :
637 CYValue(reinterpret_cast<void *>(value))
639 sig::Parse(pool_, &signature_, type, &Structor_);
640 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
643 void (*GetValue())() const {
644 return reinterpret_cast<void (*)()>(value_);
648 struct Closure_privateData :
651 JSContextRef context_;
652 JSObjectRef function_;
654 Closure_privateData(const char *type) :
655 Functor_privateData(type, NULL)
660 struct Message_privateData :
665 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
666 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
672 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
673 Instance::Flags flags;
676 flags = Instance::Transient;
678 flags = Instance::None;
679 object = [object retain];
682 return Instance::Make(context, object, flags);
685 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
687 return [value UTF8String];
689 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
690 char *string(new(pool) char[size]);
691 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
692 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
697 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
698 return JSValueMakeBoolean(context, value);
701 JSValueRef CYCastJSValue(JSContextRef context, double value) {
702 return JSValueMakeNumber(context, value);
705 #define CYCastJSValue_(Type_) \
706 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
707 return JSValueMakeNumber(context, static_cast<double>(value)); \
711 CYCastJSValue_(unsigned int)
712 CYCastJSValue_(long int)
713 CYCastJSValue_(long unsigned int)
714 CYCastJSValue_(long long int)
715 CYCastJSValue_(long long unsigned int)
717 JSValueRef CYJSUndefined(JSContextRef context) {
718 return JSValueMakeUndefined(context);
721 size_t CYGetIndex(const char *value) {
722 if (value[0] != '0') {
724 size_t index(strtoul(value, &end, 10));
725 if (value + strlen(value) == end)
727 } else if (value[1] == '\0')
732 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
733 return CYGetIndex(CYPoolCString(pool, value));
736 bool CYGetOffset(const char *value, ssize_t &index) {
737 if (value[0] != '0') {
739 index = strtol(value, &end, 10);
740 if (value + strlen(value) == end)
742 } else if (value[1] == '\0') {
750 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
751 return CYGetOffset(CYPoolCString(pool, value), index);
754 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
756 @interface NSMethodSignature (Cycript)
757 - (NSString *) _typeString;
760 @interface NSObject (Cycript)
762 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
763 - (JSType) cy$JSType;
765 - (NSObject *) cy$toJSON:(NSString *)key;
766 - (NSString *) cy$toCYON;
767 - (NSString *) cy$toKey;
769 - (bool) cy$hasProperty:(NSString *)name;
770 - (NSObject *) cy$getProperty:(NSString *)name;
771 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
772 - (bool) cy$deleteProperty:(NSString *)name;
777 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
780 @interface NSString (Cycript)
781 - (void *) cy$symbol;
784 struct PropertyAttributes {
789 const char *variable;
802 PropertyAttributes(objc_property_t property) :
814 name = property_getName(property);
815 const char *attributes(property_getAttributes(property));
817 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
819 case 'R': readonly = true; break;
820 case 'C': copy = true; break;
821 case '&': retain = true; break;
822 case 'N': nonatomic = true; break;
823 case 'G': getter_ = token + 1; break;
824 case 'S': setter_ = token + 1; break;
825 case 'V': variable = token + 1; break;
829 /*if (variable == NULL) {
830 variable = property_getName(property);
831 size_t size(strlen(variable));
832 char *name(new(pool_) char[size + 2]);
834 memcpy(name + 1, variable, size);
835 name[size + 1] = '\0';
840 const char *Getter() {
842 getter_ = apr_pstrdup(pool_, name);
846 const char *Setter() {
847 if (setter_ == NULL && !readonly) {
848 size_t length(strlen(name));
850 char *temp(new(pool_) char[length + 5]);
856 temp[3] = toupper(name[0]);
857 memcpy(temp + 4, name + 1, length - 1);
860 temp[length + 3] = ':';
861 temp[length + 4] = '\0';
870 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
871 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
874 /* Bridge: NSArray {{{ */
875 @implementation NSArray (Cycript)
877 - (NSString *) cy$toCYON {
878 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
879 [json appendString:@"["];
882 for (id object in self) {
884 [json appendString:@","];
887 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
888 [json appendString:CYPoolNSCYON(NULL, object)];
890 [json appendString:@","];
895 [json appendString:@"]"];
899 - (bool) cy$hasProperty:(NSString *)name {
900 if ([name isEqualToString:@"length"])
903 size_t index(CYGetIndex(NULL, name));
904 if (index == _not(size_t) || index >= [self count])
905 return [super cy$hasProperty:name];
910 - (NSObject *) cy$getProperty:(NSString *)name {
911 if ([name isEqualToString:@"length"])
912 return [NSNumber numberWithUnsignedInteger:[self count]];
914 size_t index(CYGetIndex(NULL, name));
915 if (index == _not(size_t) || index >= [self count])
916 return [super cy$getProperty:name];
918 return [self objectAtIndex:index];
923 /* Bridge: NSDictionary {{{ */
924 @implementation NSDictionary (Cycript)
926 - (NSString *) cy$toCYON {
927 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
928 [json appendString:@"{"];
931 for (id key in self) {
933 [json appendString:@","];
936 [json appendString:[key cy$toKey]];
937 [json appendString:@":"];
938 NSObject *object([self objectForKey:key]);
939 [json appendString:CYPoolNSCYON(NULL, object)];
942 [json appendString:@"}"];
946 - (bool) cy$hasProperty:(NSString *)name {
947 return [self objectForKey:name] != nil;
950 - (NSObject *) cy$getProperty:(NSString *)name {
951 return [self objectForKey:name];
956 /* Bridge: NSMutableArray {{{ */
957 @implementation NSMutableArray (Cycript)
959 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
960 if ([name isEqualToString:@"length"]) {
961 // XXX: is this not intelligent?
962 NSUInteger size([(NSNumber *)value unsignedIntegerValue]);
963 NSUInteger count([self count]);
965 [self removeObjectsInRange:NSMakeRange(size, count - size)];
966 else if (size != count) {
967 WebUndefined *undefined([WebUndefined undefined]);
968 for (size_t i(count); i != size; ++i)
969 [self addObject:undefined];
974 size_t index(CYGetIndex(NULL, name));
975 if (index == _not(size_t))
976 return [super cy$setProperty:name to:value];
978 id object(value ?: [NSNull null]);
980 size_t count([self count]);
982 [self replaceObjectAtIndex:index withObject:object];
984 if (index != count) {
985 WebUndefined *undefined([WebUndefined undefined]);
986 for (size_t i(count); i != index; ++i)
987 [self addObject:undefined];
990 [self addObject:object];
996 - (bool) cy$deleteProperty:(NSString *)name {
997 size_t index(CYGetIndex(NULL, name));
998 if (index == _not(size_t) || index >= [self count])
999 return [super cy$deleteProperty:name];
1000 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1006 /* Bridge: NSMutableDictionary {{{ */
1007 @implementation NSMutableDictionary (Cycript)
1009 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1010 [self setObject:(value ?: [NSNull null]) forKey:name];
1014 - (bool) cy$deleteProperty:(NSString *)name {
1015 if ([self objectForKey:name] == nil)
1018 [self removeObjectForKey:name];
1025 /* Bridge: NSNumber {{{ */
1026 @implementation NSNumber (Cycript)
1028 - (JSType) cy$JSType {
1029 // XXX: this just seems stupid
1030 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
1033 - (NSObject *) cy$toJSON:(NSString *)key {
1037 - (NSString *) cy$toCYON {
1038 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1041 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1042 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1047 /* Bridge: NSNull {{{ */
1048 @implementation NSNull (Cycript)
1050 - (JSType) cy$JSType {
1054 - (NSObject *) cy$toJSON:(NSString *)key {
1058 - (NSString *) cy$toCYON {
1064 /* Bridge: NSObject {{{ */
1065 @implementation NSObject (Cycript)
1067 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1068 return CYMakeInstance(context, self, false);
1071 - (JSType) cy$JSType {
1072 return kJSTypeObject;
1075 - (NSObject *) cy$toJSON:(NSString *)key {
1076 return [self description];
1079 - (NSString *) cy$toCYON {
1080 return [[self cy$toJSON:@""] cy$toCYON];
1083 - (NSString *) cy$toKey {
1084 return [self cy$toCYON];
1087 - (bool) cy$hasProperty:(NSString *)name {
1091 - (NSObject *) cy$getProperty:(NSString *)name {
1095 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1099 - (bool) cy$deleteProperty:(NSString *)name {
1105 /* Bridge: NSProxy {{{ */
1106 @implementation NSProxy (Cycript)
1108 - (NSObject *) cy$toJSON:(NSString *)key {
1109 return [self description];
1112 - (NSString *) cy$toCYON {
1113 return [[self cy$toJSON:@""] cy$toCYON];
1118 /* Bridge: NSString {{{ */
1119 @implementation NSString (Cycript)
1121 - (JSType) cy$JSType {
1122 return kJSTypeString;
1125 - (NSObject *) cy$toJSON:(NSString *)key {
1129 - (NSString *) cy$toCYON {
1130 // XXX: this should use the better code from Output.cpp
1131 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
1133 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
1134 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
1135 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
1136 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
1137 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
1139 CFStringInsert(json, 0, CFSTR("\""));
1140 CFStringAppend(json, CFSTR("\""));
1142 return [reinterpret_cast<const NSString *>(json) autorelease];
1145 - (NSString *) cy$toKey {
1146 const char *value([self UTF8String]);
1147 size_t size(strlen(value));
1152 if (DigitRange_[value[0]]) {
1153 size_t index(CYGetIndex(NULL, self));
1154 if (index == _not(size_t))
1157 if (!WordStartRange_[value[0]])
1159 for (size_t i(1); i != size; ++i)
1160 if (!WordEndRange_[value[i]])
1167 return [self cy$toCYON];
1170 - (void *) cy$symbol {
1172 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1177 /* Bridge: WebUndefined {{{ */
1178 @implementation WebUndefined (Cycript)
1180 - (JSType) cy$JSType {
1181 return kJSTypeUndefined;
1184 - (NSObject *) cy$toJSON:(NSString *)key {
1188 - (NSString *) cy$toCYON {
1189 return @"undefined";
1192 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1193 return CYJSUndefined(context);
1199 @interface CYJSObject : NSMutableDictionary {
1200 JSObjectRef object_;
1201 JSContextRef context_;
1204 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1206 - (NSString *) cy$toJSON:(NSString *)key;
1208 - (NSUInteger) count;
1209 - (id) objectForKey:(id)key;
1210 - (NSEnumerator *) keyEnumerator;
1211 - (void) setObject:(id)object forKey:(id)key;
1212 - (void) removeObjectForKey:(id)key;
1216 @interface CYJSArray : NSMutableArray {
1217 JSObjectRef object_;
1218 JSContextRef context_;
1221 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1223 - (NSUInteger) count;
1224 - (id) objectAtIndex:(NSUInteger)index;
1226 - (void) addObject:(id)anObject;
1227 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1228 - (void) removeLastObject;
1229 - (void) removeObjectAtIndex:(NSUInteger)index;
1230 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1234 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1235 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1236 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1241 @catch (id error) { \
1242 CYThrow(context, error, exception); \
1246 apr_status_t CYPoolRelease_(void *data) {
1247 id object(reinterpret_cast<id>(data));
1252 id CYPoolRelease(apr_pool_t *pool, id object) {
1255 else if (pool == NULL)
1256 return [object autorelease];
1258 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1263 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1264 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1267 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1268 JSValueRef exception(NULL);
1269 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1270 CYThrow(context, exception);
1271 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1272 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1275 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1276 if (!JSValueIsObjectOfClass(context, object, Instance_))
1277 return CYCastNSObject_(pool, context, object);
1279 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1280 return internal->GetValue();
1284 double CYCastDouble(const char *value, size_t size) {
1286 double number(strtod(value, &end));
1287 if (end != value + size)
1292 double CYCastDouble(const char *value) {
1293 return CYCastDouble(value, strlen(value));
1296 double CYCastDouble(JSContextRef context, JSValueRef value) {
1297 JSValueRef exception(NULL);
1298 double number(JSValueToNumber(context, value, &exception));
1299 CYThrow(context, exception);
1303 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1304 double number(CYCastDouble(context, value));
1305 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1308 CFStringRef CYCopyCFString(const char *value) {
1309 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1312 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1313 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1316 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1317 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1320 bool CYCastBool(JSContextRef context, JSValueRef value) {
1321 return JSValueToBoolean(context, value);
1324 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1328 switch (JSType type = JSValueGetType(context, value)) {
1329 case kJSTypeUndefined:
1330 object = [WebUndefined undefined];
1338 case kJSTypeBoolean:
1339 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1344 object = CYCopyCFNumber(context, value);
1349 object = CYCopyCFString(context, value);
1354 // XXX: this might could be more efficient
1355 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1360 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1367 return CYPoolRelease(pool, object);
1369 return CFRetain(object);
1372 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1373 return CYCFType(pool, context, value, true);
1376 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1377 return CYCFType(pool, context, value, false);
1380 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1382 size_t size(JSPropertyNameArrayGetCount(names));
1383 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1384 for (size_t index(0); index != size; ++index)
1385 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1389 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1390 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1393 void CYThrow(JSContextRef context, JSValueRef value) {
1396 @throw CYCastNSObject(NULL, context, value);
1399 JSValueRef CYJSNull(JSContextRef context) {
1400 return JSValueMakeNull(context);
1403 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1404 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1407 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1408 return CYCastJSValue(context, CYJSString(value));
1411 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1413 return CYJSNull(context);
1414 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1415 return [value cy$JSValueInContext:context];
1417 return CYMakeInstance(context, value, false);
1420 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1421 JSValueRef exception(NULL);
1422 JSObjectRef object(JSValueToObject(context, value, &exception));
1423 CYThrow(context, exception);
1427 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1428 if (exception == NULL)
1430 *exception = CYCastJSValue(context, error);
1433 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1434 JSValueRef exception(NULL);
1435 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1436 CYThrow(context, exception);
1440 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1441 // XXX: this isn't actually correct
1442 return value != NULL && JSValueIsObject(context, value);
1445 @implementation CYJSObject
1447 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1448 if ((self = [super init]) != nil) {
1454 - (NSObject *) cy$toJSON:(NSString *)key {
1455 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1456 if (!CYIsCallable(context_, toJSON))
1457 return [super cy$toJSON:key];
1459 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1460 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1461 // XXX: do I really want an NSNull here?!
1462 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1466 - (NSString *) cy$toCYON {
1467 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1468 if (!CYIsCallable(context_, toCYON)) super:
1469 return [super cy$toCYON];
1470 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1471 return CYCastNSString(NULL, CYJSString(context_, value));
1475 - (NSUInteger) count {
1476 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1477 size_t size(JSPropertyNameArrayGetCount(names));
1478 JSPropertyNameArrayRelease(names);
1482 - (id) objectForKey:(id)key {
1483 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1484 if (JSValueIsUndefined(context_, value))
1486 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1489 - (NSEnumerator *) keyEnumerator {
1490 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1491 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1492 JSPropertyNameArrayRelease(names);
1496 - (void) setObject:(id)object forKey:(id)key {
1497 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1500 - (void) removeObjectForKey:(id)key {
1501 JSValueRef exception(NULL);
1502 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1503 CYThrow(context_, exception);
1508 @implementation CYJSArray
1510 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1511 if ((self = [super init]) != nil) {
1517 - (NSUInteger) count {
1518 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1521 - (id) objectAtIndex:(NSUInteger)index {
1522 size_t bounds([self count]);
1523 if (index >= bounds)
1524 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1525 JSValueRef exception(NULL);
1526 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1527 CYThrow(context_, exception);
1528 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1531 - (void) addObject:(id)object {
1532 JSValueRef exception(NULL);
1533 JSValueRef arguments[1];
1534 arguments[0] = CYCastJSValue(context_, object);
1535 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1536 CYThrow(context_, exception);
1539 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1540 size_t bounds([self count] + 1);
1541 if (index >= bounds)
1542 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1543 JSValueRef exception(NULL);
1544 JSValueRef arguments[3];
1545 arguments[0] = CYCastJSValue(context_, index);
1546 arguments[1] = CYCastJSValue(context_, 0);
1547 arguments[2] = CYCastJSValue(context_, object);
1548 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1549 CYThrow(context_, exception);
1552 - (void) removeLastObject {
1553 JSValueRef exception(NULL);
1554 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1555 CYThrow(context_, exception);
1558 - (void) removeObjectAtIndex:(NSUInteger)index {
1559 size_t bounds([self count]);
1560 if (index >= bounds)
1561 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1562 JSValueRef exception(NULL);
1563 JSValueRef arguments[2];
1564 arguments[0] = CYCastJSValue(context_, index);
1565 arguments[1] = CYCastJSValue(context_, 1);
1566 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1567 CYThrow(context_, exception);
1570 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1571 size_t bounds([self count]);
1572 if (index >= bounds)
1573 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1574 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1579 NSString *CYCopyNSCYON(id value) {
1585 Class _class(object_getClass(value));
1586 SEL sel(@selector(cy$toCYON));
1588 if (Method toCYON = class_getInstanceMethod(_class, sel))
1589 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1590 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1591 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1592 string = [value cy$toCYON];
1595 if (value == NSZombie_)
1596 string = @"_NSZombie_";
1597 else if (_class == NSZombie_)
1598 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1599 // XXX: frowny /in/ the pants
1600 else if (value == NSMessageBuilder_ || value == Object_)
1603 string = [NSString stringWithFormat:@"%@", value];
1606 // XXX: frowny pants
1608 string = @"undefined";
1611 return [string retain];
1614 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1615 if (JSValueIsNull(context, value))
1616 return [@"null" retain];
1620 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1625 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1626 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1629 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1630 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1631 const char *string(CYPoolCString(pool, json));
1637 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1641 JSObjectRef object_;
1649 // XXX: delete object_? ;(
1652 static CYInternal *Get(id self) {
1653 CYInternal *internal(NULL);
1654 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1655 // XXX: do something epic? ;P
1661 static CYInternal *Set(id self) {
1662 CYInternal *internal(NULL);
1663 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1664 if (internal == NULL) {
1665 internal = new CYInternal();
1666 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1669 // XXX: do something epic? ;P
1675 bool HasProperty(JSContextRef context, JSStringRef name) {
1676 if (object_ == NULL)
1678 return JSObjectHasProperty(context, object_, name);
1681 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1682 if (object_ == NULL)
1684 return CYGetProperty(context, object_, name);
1687 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1688 if (object_ == NULL)
1689 object_ = JSObjectMake(context, NULL, NULL);
1690 CYSetProperty(context, object_, name, value);
1694 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1695 Selector_privateData *internal(new Selector_privateData(sel));
1696 return JSObjectMake(context, Selector_, internal);
1699 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1700 Pointer *internal(new Pointer(pointer, type, owner));
1701 return JSObjectMake(context, Pointer_, internal);
1704 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1705 Functor_privateData *internal(new Functor_privateData(type, function));
1706 return JSObjectMake(context, Functor_, internal);
1709 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1711 const char *string([CYCastNSString(NULL, value) UTF8String]);
1714 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1715 char *string(new(pool) char[size]);
1716 JSStringGetUTF8CString(value, string, size);
1721 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1722 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1725 bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1726 return CYGetOffset(CYPoolCString(pool, value), index);
1729 // XXX: this macro is unhygenic
1730 #define CYCastCString(context, value) ({ \
1732 if (value == NULL) \
1734 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1735 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1736 utf8 = reinterpret_cast<char *>(alloca(size)); \
1737 JSStringGetUTF8CString(string, utf8, size); \
1738 JSStringRelease(string); \
1744 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1745 switch (JSValueGetType(context, value)) {
1748 /*case kJSTypeString:
1749 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1751 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1752 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1753 return internal->value_;
1756 double number(CYCastDouble(context, value));
1757 if (std::isnan(number))
1758 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1759 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1763 template <typename Type_>
1764 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1765 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1768 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1769 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1770 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1771 return reinterpret_cast<SEL>(internal->value_);
1773 return CYCastPointer<SEL>(context, value);
1776 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1777 switch (type->primitive) {
1778 case sig::boolean_P:
1779 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1782 #define CYPoolFFI_(primitive, native) \
1783 case sig::primitive ## _P: \
1784 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1787 CYPoolFFI_(uchar, unsigned char)
1788 CYPoolFFI_(char, char)
1789 CYPoolFFI_(ushort, unsigned short)
1790 CYPoolFFI_(short, short)
1791 CYPoolFFI_(ulong, unsigned long)
1792 CYPoolFFI_(long, long)
1793 CYPoolFFI_(uint, unsigned int)
1794 CYPoolFFI_(int, int)
1795 CYPoolFFI_(ulonglong, unsigned long long)
1796 CYPoolFFI_(longlong, long long)
1797 CYPoolFFI_(float, float)
1798 CYPoolFFI_(double, double)
1801 case sig::typename_P:
1802 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1805 case sig::selector_P:
1806 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1809 case sig::pointer_P:
1810 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1814 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1817 case sig::struct_P: {
1818 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1819 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1820 for (size_t index(0); index != type->data.signature.count; ++index) {
1821 sig::Element *element(&type->data.signature.elements[index]);
1822 ffi_type *field(ffi->elements[index]);
1825 if (aggregate == NULL)
1828 rhs = CYGetProperty(context, aggregate, index);
1829 if (JSValueIsUndefined(context, rhs)) {
1830 if (element->name != NULL)
1831 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1834 if (JSValueIsUndefined(context, rhs)) undefined:
1835 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1839 CYPoolFFI(pool, context, element->type, field, base, rhs);
1841 base += field->size;
1849 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1854 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1857 switch (type->primitive) {
1858 case sig::boolean_P:
1859 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1862 #define CYFromFFI_(primitive, native) \
1863 case sig::primitive ## _P: \
1864 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1867 CYFromFFI_(uchar, unsigned char)
1868 CYFromFFI_(char, char)
1869 CYFromFFI_(ushort, unsigned short)
1870 CYFromFFI_(short, short)
1871 CYFromFFI_(ulong, unsigned long)
1872 CYFromFFI_(long, long)
1873 CYFromFFI_(uint, unsigned int)
1874 CYFromFFI_(int, int)
1875 CYFromFFI_(ulonglong, unsigned long long)
1876 CYFromFFI_(longlong, long long)
1877 CYFromFFI_(float, float)
1878 CYFromFFI_(double, double)
1880 case sig::object_P: {
1881 if (id object = *reinterpret_cast<id *>(data)) {
1882 value = CYCastJSValue(context, object);
1888 case sig::typename_P:
1889 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1892 case sig::selector_P:
1893 if (SEL sel = *reinterpret_cast<SEL *>(data))
1894 value = CYMakeSelector(context, sel);
1898 case sig::pointer_P:
1899 if (void *pointer = *reinterpret_cast<void **>(data))
1900 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1905 if (char *utf8 = *reinterpret_cast<char **>(data))
1906 value = CYCastJSValue(context, utf8);
1911 value = CYMakeStruct(context, data, type, ffi, owner);
1915 value = CYJSUndefined(context);
1919 value = CYJSNull(context);
1923 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1930 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1931 if (Method method = class_getInstanceMethod(_class, selector)) {
1935 method_getReturnType(method, type, sizeof(type));
1940 // XXX: possibly use a more "awesome" check?
1944 const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
1946 return method_getTypeEncoding(method);
1947 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1948 return CYPoolCString(pool, type);
1953 void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1954 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1956 JSContextRef context(internal->context_);
1958 size_t count(internal->cif_.nargs);
1959 JSValueRef values[count];
1961 for (size_t index(0); index != count; ++index)
1962 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1964 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
1965 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1968 void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1969 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1971 JSContextRef context(internal->context_);
1973 size_t count(internal->cif_.nargs);
1974 JSValueRef values[count];
1976 for (size_t index(0); index != count; ++index)
1977 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1979 JSObjectRef _this(CYCastJSObject(context, values[0]));
1981 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1982 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1985 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
1986 // XXX: in case of exceptions this will leak
1987 // XXX: in point of fact, this may /need/ to leak :(
1988 Closure_privateData *internal(new Closure_privateData(type));
1990 ffi_closure *closure((ffi_closure *) _syscall(mmap(
1991 NULL, sizeof(ffi_closure),
1992 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1996 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
1997 _assert(status == FFI_OK);
1999 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2001 internal->value_ = closure;
2003 internal->context_ = CYGetJSContext();
2004 internal->function_ = function;
2009 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2010 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2011 return JSObjectMake(context, Functor_, internal);
2014 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2015 JSValueRef exception(NULL);
2016 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2017 CYThrow(context, exception);
2020 JSObjectRef function(CYCastJSObject(context, value));
2021 return CYMakeFunctor(context, function, type);
2023 void (*function)()(CYCastPointer<void (*)()>(context, value));
2024 return CYMakeFunctor(context, function, type);
2028 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2029 Message_privateData *internal(new Message_privateData(sel, type, imp));
2030 return JSObjectMake(context, Message_, internal);
2033 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2034 JSObjectRef function(CYCastJSObject(context, value));
2035 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2036 return reinterpret_cast<IMP>(internal->GetValue());
2039 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2040 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2041 Class _class(internal->GetValue());
2044 const char *name(CYPoolCString(pool, property));
2046 if (SEL sel = sel_getUid(name))
2047 if (class_getInstanceMethod(_class, sel) != NULL)
2053 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2054 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2055 Class _class(internal->GetValue());
2058 const char *name(CYPoolCString(pool, property));
2060 if (SEL sel = sel_getUid(name))
2061 if (Method method = class_getInstanceMethod(_class, sel))
2062 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2067 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2068 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2069 Class _class(internal->GetValue());
2072 const char *name(CYPoolCString(pool, property));
2074 SEL sel(sel_registerName(name));
2076 Method method(class_getInstanceMethod(_class, sel));
2081 if (JSValueIsObjectOfClass(context, value, Message_)) {
2082 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2083 type = sig::Unparse(pool, &message->signature_);
2084 imp = reinterpret_cast<IMP>(message->GetValue());
2086 type = CYPoolTypeEncoding(pool, _class, sel, method);
2087 imp = CYMakeMessage(context, value, type);
2091 method_setImplementation(method, imp);
2093 class_replaceMethod(_class, sel, imp, type);
2099 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2100 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2101 Class _class(internal->GetValue());
2104 const char *name(CYPoolCString(pool, property));
2106 if (SEL sel = sel_getUid(name))
2107 if (Method method = class_getInstanceMethod(_class, sel)) {
2108 objc_method_list list = {NULL, 1, {method}};
2109 class_removeMethods(_class, &list);
2117 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2118 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2119 Class _class(internal->GetValue());
2122 Method *data(class_copyMethodList(_class, &size));
2123 for (size_t i(0); i != size; ++i)
2124 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2128 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2129 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2130 id self(internal->GetValue());
2132 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2136 NSString *name(CYCastNSString(pool, property));
2138 if (CYInternal *internal = CYInternal::Get(self))
2139 if (internal->HasProperty(context, property))
2142 Class _class(object_getClass(self));
2145 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2146 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2147 if ([self cy$hasProperty:name])
2149 } CYPoolCatch(false)
2151 const char *string(CYPoolCString(pool, name));
2153 if (class_getProperty(_class, string) != NULL)
2156 if (SEL sel = sel_getUid(string))
2157 if (CYImplements(self, _class, sel, true))
2163 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2164 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2165 id self(internal->GetValue());
2167 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2168 return Internal::Make(context, self, object);
2172 NSString *name(CYCastNSString(pool, property));
2174 if (CYInternal *internal = CYInternal::Get(self))
2175 if (JSValueRef value = internal->GetProperty(context, property))
2179 if (NSObject *data = [self cy$getProperty:name])
2180 return CYCastJSValue(context, data);
2183 const char *string(CYPoolCString(pool, name));
2184 Class _class(object_getClass(self));
2186 if (objc_property_t property = class_getProperty(_class, string)) {
2187 PropertyAttributes attributes(property);
2188 SEL sel(sel_registerName(attributes.Getter()));
2189 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2192 if (SEL sel = sel_getUid(string))
2193 if (CYImplements(self, _class, sel, true))
2194 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2200 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2201 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2202 id self(internal->GetValue());
2207 NSString *name(CYCastNSString(pool, property));
2208 NSString *data(CYCastNSObject(pool, context, value));
2211 if ([self cy$setProperty:name to:data])
2215 const char *string(CYPoolCString(pool, name));
2216 Class _class(object_getClass(self));
2218 if (objc_property_t property = class_getProperty(_class, string)) {
2219 PropertyAttributes attributes(property);
2220 if (const char *setter = attributes.Setter()) {
2221 SEL sel(sel_registerName(setter));
2222 JSValueRef arguments[1] = {value};
2223 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2228 size_t length(strlen(string));
2230 char set[length + 5];
2236 if (string[0] != '\0') {
2237 set[3] = toupper(string[0]);
2238 memcpy(set + 4, string + 1, length - 1);
2241 set[length + 3] = ':';
2242 set[length + 4] = '\0';
2244 if (SEL sel = sel_getUid(set))
2245 if (CYImplements(self, _class, sel, false)) {
2246 JSValueRef arguments[1] = {value};
2247 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2250 if (CYInternal *internal = CYInternal::Set(self)) {
2251 internal->SetProperty(context, property, value);
2259 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2260 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2261 id self(internal->GetValue());
2265 NSString *name(CYCastNSString(NULL, property));
2266 return [self cy$deleteProperty:name];
2271 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2272 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2273 id self(internal->GetValue());
2276 Class _class(object_getClass(self));
2280 objc_property_t *data(class_copyPropertyList(_class, &size));
2281 for (size_t i(0); i != size; ++i)
2282 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2287 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2289 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2290 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2295 bool CYIsClass(id self) {
2296 // XXX: this is a lame object_isClass
2297 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2300 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2301 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2302 Class _class(internal->GetValue());
2303 if (!CYIsClass(_class))
2306 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2307 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2308 // XXX: this isn't always safe
2310 return [linternal->GetValue() isKindOfClass:_class];
2317 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2318 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2321 id self(internal->GetValue());
2322 const char *name(CYPoolCString(pool, property));
2324 if (object_getInstanceVariable(self, name, NULL) != NULL)
2330 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2331 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2335 id self(internal->GetValue());
2336 const char *name(CYPoolCString(pool, property));
2338 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2339 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2340 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2347 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2348 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2352 id self(internal->GetValue());
2353 const char *name(CYPoolCString(pool, property));
2355 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2356 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2357 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2365 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2366 if (Class super = class_getSuperclass(_class))
2367 Internal_getPropertyNames_(super, names);
2370 Ivar *data(class_copyIvarList(_class, &size));
2371 for (size_t i(0); i != size; ++i)
2372 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2376 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2377 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2380 id self(internal->GetValue());
2381 Class _class(object_getClass(self));
2383 Internal_getPropertyNames_(_class, names);
2386 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2387 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2388 return internal->owner_;
2391 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2392 Type_privateData *typical(internal->type_);
2393 sig::Type *type(typical->type_);
2397 const char *name(CYPoolCString(pool, property));
2398 size_t length(strlen(name));
2399 double number(CYCastDouble(name, length));
2401 size_t count(type->data.signature.count);
2403 if (std::isnan(number)) {
2404 if (property == NULL)
2407 sig::Element *elements(type->data.signature.elements);
2409 for (size_t local(0); local != count; ++local) {
2410 sig::Element *element(&elements[local]);
2411 if (element->name != NULL && strcmp(name, element->name) == 0) {
2419 index = static_cast<ssize_t>(number);
2420 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2425 ffi_type **elements(typical->GetFFI()->elements);
2427 base = reinterpret_cast<uint8_t *>(internal->value_);
2428 for (ssize_t local(0); local != index; ++local)
2429 base += elements[local]->size;
2434 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2435 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2436 Type_privateData *typical(internal->type_);
2438 ffi_type *ffi(typical->GetFFI());
2440 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2441 base += ffi->size * index;
2443 JSObjectRef owner(internal->owner_ ?: object);
2446 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2450 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2452 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2453 Type_privateData *typical(internal->type_);
2455 if (typical->type_ == NULL)
2459 if (!CYGetOffset(pool, property, offset))
2462 return Pointer_getIndex(context, object, offset, exception);
2465 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2466 return Pointer_getIndex(context, object, 0, exception);
2469 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2470 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2471 Type_privateData *typical(internal->type_);
2473 ffi_type *ffi(typical->GetFFI());
2475 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2476 base += ffi->size * index;
2479 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2484 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2486 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2487 Type_privateData *typical(internal->type_);
2489 if (typical->type_ == NULL)
2493 if (!CYGetOffset(pool, property, offset))
2496 return Pointer_setIndex(context, object, offset, value, exception);
2499 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2500 return Pointer_setIndex(context, object, 0, value, exception);
2503 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2504 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2505 Type_privateData *typical(internal->type_);
2506 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2509 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2511 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2512 Type_privateData *typical(internal->type_);
2517 if (!Index_(pool, internal, property, index, base))
2520 JSObjectRef owner(internal->owner_ ?: object);
2523 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2527 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2529 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2530 Type_privateData *typical(internal->type_);
2535 if (!Index_(pool, internal, property, index, base))
2539 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2544 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2545 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2546 Type_privateData *typical(internal->type_);
2547 sig::Type *type(typical->type_);
2552 size_t count(type->data.signature.count);
2553 sig::Element *elements(type->data.signature.elements);
2557 for (size_t index(0); index != count; ++index) {
2559 name = elements[index].name;
2562 sprintf(number, "%lu", index);
2566 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2570 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)()) {
2572 if (setups + count != signature->count - 1)
2573 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2575 size_t size(setups + count);
2577 memcpy(values, setup, sizeof(void *) * setups);
2579 for (size_t index(setups); index != size; ++index) {
2580 sig::Element *element(&signature->elements[index + 1]);
2581 ffi_type *ffi(cif->arg_types[index]);
2583 values[index] = new(pool) uint8_t[ffi->size];
2584 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2587 uint8_t value[cif->rtype->size];
2588 ffi_call(cif, function, value, values);
2590 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2594 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2597 NSString *name(CYCastNSString(pool, property));
2598 if (Class _class = NSClassFromString(name))
2599 return CYMakeInstance(context, _class, true);
2604 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2605 size_t size(objc_getClassList(NULL, 0));
2606 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2609 size_t writ(objc_getClassList(data, size));
2612 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2618 for (size_t i(0); i != writ; ++i)
2619 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2625 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2626 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2630 const char *name(CYPoolCString(pool, property));
2632 const char **data(objc_copyClassNamesForImage(internal, &size));
2634 for (size_t i(0); i != size; ++i)
2635 if (strcmp(name, data[i]) == 0) {
2636 if (Class _class = objc_getClass(name)) {
2637 value = CYMakeInstance(context, _class, true);
2649 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2650 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2652 const char **data(objc_copyClassNamesForImage(internal, &size));
2653 for (size_t i(0); i != size; ++i)
2654 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2658 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2661 const char *name(CYPoolCString(pool, property));
2663 const char **data(objc_copyImageNames(&size));
2664 for (size_t i(0); i != size; ++i)
2665 if (strcmp(name, data[i]) == 0) {
2674 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2675 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2680 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2682 const char **data(objc_copyImageNames(&size));
2683 for (size_t i(0); i != size; ++i)
2684 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2688 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2691 NSString *name(CYCastNSString(pool, property));
2692 if (Protocol *protocol = NSProtocolFromString(name))
2693 return CYMakeInstance(context, protocol, true);
2698 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2700 Protocol **data(objc_copyProtocolList(&size));
2701 for (size_t i(0); i != size; ++i)
2702 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2706 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2707 if (JSStringIsEqualToUTF8CString(property, "nil"))
2708 return Instance::Make(context, nil);
2712 NSString *name(CYCastNSString(pool, property));
2713 if (Class _class = NSClassFromString(name))
2714 return CYMakeInstance(context, _class, true);
2715 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2716 switch ([[entry objectAtIndex:0] intValue]) {
2718 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2720 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2722 // XXX: this is horrendously inefficient
2723 sig::Signature signature;
2724 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2726 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2727 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2733 bool stret(ffi_type *ffi_type) {
2734 return ffi_type->type == FFI_TYPE_STRUCT && (
2735 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2736 struct_forward_array[ffi_type->size] != 0
2741 int *_NSGetArgc(void);
2742 char ***_NSGetArgv(void);
2743 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2746 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2748 NSLog(@"%s", CYCastCString(context, arguments[0]));
2749 return CYJSUndefined(context);
2753 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2756 Class _class(object_getClass(self));
2757 if (Method method = class_getInstanceMethod(_class, _cmd))
2758 type = method_getTypeEncoding(method);
2762 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2764 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2765 type = CYPoolCString(pool, [method _typeString]);
2774 sig::Signature signature;
2775 sig::Parse(pool, &signature, type, &Structor_);
2778 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2780 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2781 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2784 static size_t Nonce_(0);
2786 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2788 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
2789 return CYCastJSValue(context, name);
2792 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2802 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2804 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2805 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2806 self = internal->GetValue();
2807 uninitialized = internal->IsUninitialized();
2809 internal->value_ = nil;
2811 self = CYCastNSObject(pool, context, arguments[0]);
2812 uninitialized = false;
2816 return CYJSNull(context);
2818 _cmd = CYCastSEL(context, arguments[1]);
2821 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2824 /* Hook: objc_registerClassPair {{{ */
2825 // XXX: replace this with associated objects
2827 MSHook(void, CYDealloc, id self, SEL sel) {
2828 CYInternal *internal;
2829 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2830 if (internal != NULL)
2832 _CYDealloc(self, sel);
2835 MSHook(void, objc_registerClassPair, Class _class) {
2836 Class super(class_getSuperclass(_class));
2837 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2838 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2839 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2842 _objc_registerClassPair(_class);
2845 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2848 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2850 Class _class(CYCastNSObject(pool, context, arguments[0]));
2851 $objc_registerClassPair(_class);
2852 return CYJSUndefined(context);
2857 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2858 JSValueRef setup[count + 2];
2861 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2862 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2865 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2867 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2869 // XXX: handle Instance::Uninitialized?
2870 id self(CYCastNSObject(pool, context, _this));
2874 setup[1] = &internal->sel_;
2876 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2879 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2881 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2882 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2885 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2888 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2889 const char *name(CYCastCString(context, arguments[0]));
2890 return CYMakeSelector(context, sel_registerName(name));
2894 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2897 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2899 void *value(CYCastPointer<void *>(context, arguments[0]));
2900 const char *type(CYCastCString(context, arguments[1]));
2904 sig::Signature signature;
2905 sig::Parse(pool, &signature, type, &Structor_);
2907 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2911 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2912 Type_privateData *internal(new Type_privateData(NULL, type));
2913 return JSObjectMake(context, Type_, internal);
2916 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2919 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2920 const char *type(CYCastCString(context, arguments[0]));
2921 return CYMakeType(context, object, type);
2925 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2928 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2929 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2930 sig::Type *type(internal->type_);
2931 ffi_type *ffi(internal->GetFFI());
2933 uint8_t value[ffi->size];
2935 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2936 return CYFromFFI(context, type, ffi, value);
2940 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2943 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2944 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2945 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2947 void *value(malloc(internal->GetFFI()->size * size));
2948 return CYMakePointer(context, value, internal->type_, internal->ffi_, NULL);
2952 JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2955 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
2956 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2957 return Instance::Make(context, self);
2961 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2964 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2965 const char *type(CYCastCString(context, arguments[1]));
2966 return CYMakeFunctor(context, arguments[0], type);
2970 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2971 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2972 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2975 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2976 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2977 Type_privateData *typical(internal->GetType());
2982 if (typical == NULL) {
2986 type = typical->type_;
2987 ffi = typical->ffi_;
2990 return CYMakePointer(context, &internal->value_, type, ffi, object);
2993 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2994 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2997 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3001 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3002 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3005 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3006 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3008 sprintf(string, "%p", internal->value_);
3011 return CYCastJSValue(context, string);
3015 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3016 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3017 return Instance::Make(context, object_getClass(internal->GetValue()));
3020 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3021 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3022 id self(internal->GetValue());
3023 if (!CYIsClass(self))
3024 return CYJSUndefined(context);
3026 return CYGetClassPrototype(context, self);
3030 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3031 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3032 id self(internal->GetValue());
3033 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3034 return CYJSUndefined(context);
3035 return Messages::Make(context, self);
3038 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3039 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3042 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3046 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
3051 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3052 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3055 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3059 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3060 // XXX: check for support of cy$toJSON?
3061 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3066 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3067 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3070 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3074 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3079 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3080 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3083 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3087 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3088 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3091 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3092 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3093 const char *name(sel_getName(internal->GetValue()));
3097 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3102 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3105 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
3107 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3108 Class _class(CYCastNSObject(pool, context, arguments[0]));
3109 SEL sel(internal->GetValue());
3110 Method method(class_getInstanceMethod(_class, sel));
3111 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3112 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3116 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3118 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3120 const char *type(sig::Unparse(pool, internal->type_));
3122 return CYCastJSValue(context, CYJSString(type));
3127 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3129 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3131 const char *type(sig::Unparse(pool, internal->type_));
3133 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
3138 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3139 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3142 static JSStaticValue CYValue_staticValues[2] = {
3143 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3144 {NULL, NULL, NULL, 0}
3147 static JSStaticValue Pointer_staticValues[2] = {
3148 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3149 {NULL, NULL, NULL, 0}
3152 static JSStaticFunction Pointer_staticFunctions[4] = {
3153 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3154 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3155 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3159 static JSStaticFunction Struct_staticFunctions[2] = {
3160 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3164 static JSStaticFunction Functor_staticFunctions[4] = {
3165 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3166 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3167 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3171 static JSStaticValue Instance_staticValues[5] = {
3172 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3173 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3174 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3175 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3176 {NULL, NULL, NULL, 0}
3179 static JSStaticFunction Instance_staticFunctions[5] = {
3180 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3181 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3182 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3183 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3187 static JSStaticFunction Internal_staticFunctions[2] = {
3188 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3192 static JSStaticFunction Selector_staticFunctions[5] = {
3193 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3194 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3195 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3196 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3200 static JSStaticFunction Type_staticFunctions[4] = {
3201 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3202 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3203 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3207 CYDriver::CYDriver(const std::string &filename) :
3212 filename_(filename),
3218 CYDriver::~CYDriver() {
3222 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
3223 CYDriver::Error error;
3224 error.location_ = location;
3225 error.message_ = message;
3226 driver.errors_.push_back(error);
3229 void CYSetArgs(int argc, const char *argv[]) {
3230 JSContextRef context(CYGetJSContext());
3231 JSValueRef args[argc];
3232 for (int i(0); i != argc; ++i)
3233 args[i] = CYCastJSValue(context, argv[i]);
3234 JSValueRef exception(NULL);
3235 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3236 CYThrow(context, exception);
3237 CYSetProperty(context, System_, CYJSString("args"), array);
3240 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3241 return JSContextGetGlobalObject(context);
3244 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3245 JSContextRef context(CYGetJSContext());
3246 JSValueRef exception(NULL), result;
3249 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3250 } catch (const char *error) {
3254 if (exception != NULL) { error:
3259 if (JSValueIsUndefined(context, result))
3262 const char *json(CYPoolCCYON(pool, context, result, &exception));
3263 if (exception != NULL)
3266 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3270 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
3271 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
3279 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
3280 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
3292 const char * volatile data_;
3295 // XXX: this is "tre lame"
3296 @interface CYClient_ : NSObject {
3299 - (void) execute:(NSValue *)value;
3303 @implementation CYClient_
3305 - (void) execute:(NSValue *)value {
3306 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3307 const char *data(execute->data_);
3308 execute->data_ = NULL;
3309 execute->data_ = CYExecute(execute->pool_, data);
3318 apr_thread_t *thread_;
3320 CYClient(int socket) :
3326 _syscall(close(socket_));
3329 void Handle() { _pooled
3330 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3334 if (!CYRecvAll(socket_, &size, sizeof(size)))
3338 char *data(new(pool) char[size + 1]);
3339 if (!CYRecvAll(socket_, data, size))
3343 CYDriver driver("");
3344 cy::parser parser(driver);
3346 driver.data_ = data;
3347 driver.size_ = size;
3350 if (parser.parse() != 0 || !driver.errors_.empty()) {
3352 size = _not(size_t);
3354 std::ostringstream str;
3355 driver.source_->Show(str);
3356 std::string code(str.str());
3357 CYExecute_ execute = {pool, code.c_str()};
3358 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3359 json = execute.data_;
3360 size = json == NULL ? _not(size_t) : strlen(json);
3363 if (!CYSendAll(socket_, &size, sizeof(size)))
3366 if (!CYSendAll(socket_, json, size))
3372 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3373 CYClient *client(reinterpret_cast<CYClient *>(data));
3379 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3380 CYClient *client(new(pool) CYClient(socket));
3381 apr_threadattr_t *attr;
3382 _aprcall(apr_threadattr_create(&attr, client->pool_));
3383 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3386 MSInitialize { _pooled
3387 _aprcall(apr_initialize());
3388 _aprcall(apr_pool_create(&Pool_, NULL));
3390 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3391 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3393 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3395 NSArray_ = objc_getClass("NSArray");
3396 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3397 NSCFType_ = objc_getClass("NSCFType");
3398 NSDictionary_ = objc_getClass("NSDictonary");
3399 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3400 NSZombie_ = objc_getClass("_NSZombie_");
3401 Object_ = objc_getClass("Object");
3404 JSGlobalContextRef CYGetJSContext() {
3405 if (Context_ == NULL) {
3406 JSClassDefinition definition;
3408 definition = kJSClassDefinitionEmpty;
3409 definition.className = "Functor";
3410 definition.staticFunctions = Functor_staticFunctions;
3411 definition.callAsFunction = &Functor_callAsFunction;
3412 definition.finalize = &Finalize;
3413 Functor_ = JSClassCreate(&definition);
3415 definition = kJSClassDefinitionEmpty;
3416 definition.className = "Instance";
3417 definition.staticValues = Instance_staticValues;
3418 definition.staticFunctions = Instance_staticFunctions;
3419 definition.hasProperty = &Instance_hasProperty;
3420 definition.getProperty = &Instance_getProperty;
3421 definition.setProperty = &Instance_setProperty;
3422 definition.deleteProperty = &Instance_deleteProperty;
3423 definition.getPropertyNames = &Instance_getPropertyNames;
3424 definition.callAsConstructor = &Instance_callAsConstructor;
3425 definition.hasInstance = &Instance_hasInstance;
3426 definition.finalize = &Finalize;
3427 Instance_ = JSClassCreate(&definition);
3429 definition = kJSClassDefinitionEmpty;
3430 definition.className = "Internal";
3431 definition.staticFunctions = Internal_staticFunctions;
3432 definition.hasProperty = &Internal_hasProperty;
3433 definition.getProperty = &Internal_getProperty;
3434 definition.setProperty = &Internal_setProperty;
3435 definition.getPropertyNames = &Internal_getPropertyNames;
3436 definition.finalize = &Finalize;
3437 Internal_ = JSClassCreate(&definition);
3439 definition = kJSClassDefinitionEmpty;
3440 definition.className = "Message";
3441 definition.staticFunctions = Functor_staticFunctions;
3442 definition.callAsFunction = &Message_callAsFunction;
3443 definition.finalize = &Finalize;
3444 Message_ = JSClassCreate(&definition);
3446 definition = kJSClassDefinitionEmpty;
3447 definition.className = "Messages";
3448 definition.hasProperty = &Messages_hasProperty;
3449 definition.getProperty = &Messages_getProperty;
3450 definition.setProperty = &Messages_setProperty;
3452 definition.deleteProperty = &Messages_deleteProperty;
3454 definition.getPropertyNames = &Messages_getPropertyNames;
3455 definition.finalize = &Finalize;
3456 Messages_ = JSClassCreate(&definition);
3458 definition = kJSClassDefinitionEmpty;
3459 definition.className = "NSArrayPrototype";
3460 //definition.hasProperty = &NSArrayPrototype_hasProperty;
3461 //definition.getProperty = &NSArrayPrototype_getProperty;
3462 //definition.setProperty = &NSArrayPrototype_setProperty;
3463 //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
3464 //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
3465 NSArrayPrototype_ = JSClassCreate(&definition);
3467 definition = kJSClassDefinitionEmpty;
3468 definition.className = "Pointer";
3469 definition.staticValues = Pointer_staticValues;
3470 definition.staticFunctions = Pointer_staticFunctions;
3471 definition.getProperty = &Pointer_getProperty;
3472 definition.setProperty = &Pointer_setProperty;
3473 definition.finalize = &Finalize;
3474 Pointer_ = JSClassCreate(&definition);
3476 definition = kJSClassDefinitionEmpty;
3477 definition.className = "Selector";
3478 definition.staticValues = CYValue_staticValues;
3479 definition.staticFunctions = Selector_staticFunctions;
3480 definition.callAsFunction = &Selector_callAsFunction;
3481 definition.finalize = &Finalize;
3482 Selector_ = JSClassCreate(&definition);
3484 definition = kJSClassDefinitionEmpty;
3485 definition.className = "Struct";
3486 definition.staticFunctions = Struct_staticFunctions;
3487 definition.getProperty = &Struct_getProperty;
3488 definition.setProperty = &Struct_setProperty;
3489 definition.getPropertyNames = &Struct_getPropertyNames;
3490 definition.finalize = &Finalize;
3491 Struct_ = JSClassCreate(&definition);
3493 definition = kJSClassDefinitionEmpty;
3494 definition.className = "Type";
3495 definition.staticFunctions = Type_staticFunctions;
3496 //definition.getProperty = &Type_getProperty;
3497 definition.callAsFunction = &Type_callAsFunction;
3498 definition.callAsConstructor = &Type_callAsConstructor;
3499 definition.finalize = &Finalize;
3500 Type_ = JSClassCreate(&definition);
3502 definition = kJSClassDefinitionEmpty;
3503 definition.className = "Runtime";
3504 definition.getProperty = &Runtime_getProperty;
3505 Runtime_ = JSClassCreate(&definition);
3507 definition = kJSClassDefinitionEmpty;
3508 definition.className = "ObjectiveC::Classes";
3509 definition.getProperty = &ObjectiveC_Classes_getProperty;
3510 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3511 ObjectiveC_Classes_ = JSClassCreate(&definition);
3513 definition = kJSClassDefinitionEmpty;
3514 definition.className = "ObjectiveC::Images";
3515 definition.getProperty = &ObjectiveC_Images_getProperty;
3516 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3517 ObjectiveC_Images_ = JSClassCreate(&definition);
3519 definition = kJSClassDefinitionEmpty;
3520 definition.className = "ObjectiveC::Image::Classes";
3521 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3522 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3523 definition.finalize = &Finalize;
3524 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3526 definition = kJSClassDefinitionEmpty;
3527 definition.className = "ObjectiveC::Protocols";
3528 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3529 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3530 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3532 definition = kJSClassDefinitionEmpty;
3533 //definition.getProperty = &Global_getProperty;
3534 JSClassRef Global(JSClassCreate(&definition));
3536 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3539 JSObjectRef global(CYGetGlobalObject(context));
3541 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3542 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3543 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3545 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3546 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3547 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3549 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3550 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3551 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3553 length_ = JSStringCreateWithUTF8CString("length");
3554 message_ = JSStringCreateWithUTF8CString("message");
3555 name_ = JSStringCreateWithUTF8CString("name");
3556 prototype_ = JSStringCreateWithUTF8CString("prototype");
3557 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3558 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3560 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3561 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3563 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3564 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3565 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3566 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3568 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3569 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3570 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3571 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3573 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3575 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3576 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3577 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3578 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3580 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3581 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3582 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3583 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3584 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3586 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3588 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3590 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3591 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3592 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3594 System_ = JSObjectMake(context, NULL, NULL);
3595 CYSetProperty(context, global, CYJSString("system"), System_);
3596 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3597 //CYSetProperty(context, System_, CYJSString("global"), global);
3599 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3601 Result_ = JSStringCreateWithUTF8CString("_");