1 /* Cycript - Remove Execution Server and Disassembler
2 * Copyright (C) 2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 #include <substrate.h>
43 #include "cycript.hpp"
45 #include "sig/parse.hpp"
46 #include "sig/ffi_type.hpp"
48 #include "Pooling.hpp"
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <CoreFoundation/CFLogUtilities.h>
54 #include <WebKit/WebScriptObject.h>
59 #include <ext/stdio_filebuf.h>
67 #include "Cycript.tab.hh"
69 #include <apr-1/apr_thread_proc.h>
74 #define _assert(test) do { \
76 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
79 #define _trace() do { \
80 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
85 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
87 #define CYPoolCatch(value) \
88 @catch (NSException *error) { \
89 _saved = [error retain]; \
95 [_saved autorelease]; \
99 void CYThrow(JSContextRef context, JSValueRef value);
101 /* JavaScript Properties {{{ */
102 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
103 JSValueRef exception(NULL);
104 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
105 CYThrow(context, exception);
109 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
110 JSValueRef exception(NULL);
111 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
112 CYThrow(context, exception);
116 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
117 JSValueRef exception(NULL);
118 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
119 CYThrow(context, exception);
122 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
123 JSValueRef exception(NULL);
124 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
125 CYThrow(context, exception);
128 /* JavaScript Strings {{{ */
129 JSStringRef CYCopyJSString(id value) {
130 // XXX: this definition scares me; is anyone using this?!
131 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
134 JSStringRef CYCopyJSString(const char *value) {
135 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
138 JSStringRef CYCopyJSString(JSStringRef value) {
139 return value == NULL ? NULL : JSStringRetain(value);
142 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
143 if (JSValueIsNull(context, value))
145 JSValueRef exception(NULL);
146 JSStringRef string(JSValueToStringCopy(context, value, &exception));
147 CYThrow(context, exception);
157 JSStringRelease(string_);
161 CYJSString(const CYJSString &rhs) :
162 string_(CYCopyJSString(rhs.string_))
166 template <typename Arg0_>
167 CYJSString(Arg0_ arg0) :
168 string_(CYCopyJSString(arg0))
172 template <typename Arg0_, typename Arg1_>
173 CYJSString(Arg0_ arg0, Arg1_ arg1) :
174 string_(CYCopyJSString(arg0, arg1))
178 CYJSString &operator =(const CYJSString &rhs) {
180 string_ = CYCopyJSString(rhs.string_);
193 operator JSStringRef() const {
198 CFStringRef CYCopyCFString(JSStringRef value) {
199 return JSStringCopyCFString(kCFAllocatorDefault, value);
202 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
203 return CYCopyCFString(CYJSString(context, value));
208 static JSGlobalContextRef Context_;
209 static JSObjectRef System_;
210 static JSObjectRef ObjectiveC_;
212 static JSClassRef Functor_;
213 static JSClassRef Instance_;
214 static JSClassRef Internal_;
215 static JSClassRef Message_;
216 static JSClassRef Messages_;
217 static JSClassRef NSArrayPrototype_;
218 static JSClassRef Pointer_;
219 static JSClassRef Runtime_;
220 static JSClassRef Selector_;
221 static JSClassRef Struct_;
222 static JSClassRef Type_;
224 static JSClassRef ObjectiveC_Classes_;
225 static JSClassRef ObjectiveC_Image_Classes_;
226 static JSClassRef ObjectiveC_Images_;
227 static JSClassRef ObjectiveC_Protocols_;
229 static JSObjectRef Array_;
230 static JSObjectRef Function_;
231 static JSObjectRef String_;
233 static JSStringRef Result_;
235 static JSStringRef length_;
236 static JSStringRef message_;
237 static JSStringRef name_;
238 static JSStringRef prototype_;
239 static JSStringRef toCYON_;
240 static JSStringRef toJSON_;
242 static JSObjectRef Instance_prototype_;
243 static JSObjectRef Object_prototype_;
245 static JSObjectRef Array_prototype_;
246 static JSObjectRef Array_pop_;
247 static JSObjectRef Array_push_;
248 static JSObjectRef Array_splice_;
250 static Class NSArray_;
251 static Class NSCFBoolean_;
252 static Class NSCFType_;
253 static Class NSDictionary_;
254 static Class NSMessageBuilder_;
255 static Class NSZombie_;
256 static Class Object_;
258 static NSArray *Bridge_;
260 static void Finalize(JSObjectRef object) {
261 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
264 class Type_privateData;
274 CYValue(void *value) :
279 CYValue(const CYValue &rhs) :
284 virtual Type_privateData *GetType() const {
289 struct Selector_privateData :
292 Selector_privateData(SEL value) :
297 SEL GetValue() const {
298 return reinterpret_cast<SEL>(value_);
301 virtual Type_privateData *GetType() const;
304 // XXX: trick this out with associated objects!
305 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
307 return Instance_prototype_;
309 // XXX: I need to think through multi-context
310 typedef std::map<Class, JSValueRef> CacheMap;
311 static CacheMap cache_;
313 JSValueRef &value(cache_[self]);
317 JSClassRef _class(NULL);
318 JSValueRef prototype;
320 if (self == NSArray_)
321 prototype = Array_prototype_;
322 else if (self == NSDictionary_)
323 prototype = Object_prototype_;
325 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
327 JSObjectRef object(JSObjectMake(context, _class, NULL));
328 JSObjectSetPrototype(context, object, prototype);
330 JSValueProtect(context, object);
340 Transient = (1 << 0),
341 Uninitialized = (1 << 1),
346 Instance(id value, Flags flags) :
352 virtual ~Instance() {
353 if ((flags_ & Transient) == 0)
354 // XXX: does this handle background threads correctly?
355 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
358 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
359 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
360 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object == nil ? nil : object_getClass(object)));
364 id GetValue() const {
365 return reinterpret_cast<id>(value_);
368 bool IsUninitialized() const {
369 return (flags_ & Uninitialized) != 0;
372 virtual Type_privateData *GetType() const;
378 Messages(Class value) :
383 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
384 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
385 if (_class == NSArray_)
387 if (Class super = class_getSuperclass(_class))
388 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
390 JSObjectSetPrototype(context, value, Array_prototype_);*/
394 Class GetValue() const {
395 return reinterpret_cast<Class>(value_);
403 JSContextRef context_;
407 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
412 JSValueProtect(context_, owner_);
416 JSValueUnprotect(context_, owner_);
419 JSObjectRef GetOwner() const {
427 Internal(id value, JSContextRef context, JSObjectRef owner) :
428 CYOwned(value, context, owner)
432 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
433 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
436 id GetValue() const {
437 return reinterpret_cast<id>(value_);
443 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
445 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
446 lhs.name = apr_pstrdup(pool, rhs.name);
447 if (rhs.type == NULL)
450 lhs.type = new(pool) Type;
451 Copy(pool, *lhs.type, *rhs.type);
453 lhs.offset = rhs.offset;
456 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
457 size_t count(rhs.count);
459 lhs.elements = new(pool) Element[count];
460 for (size_t index(0); index != count; ++index)
461 Copy(pool, lhs.elements[index], rhs.elements[index]);
464 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
465 lhs.primitive = rhs.primitive;
466 lhs.name = apr_pstrdup(pool, rhs.name);
467 lhs.flags = rhs.flags;
469 if (sig::IsAggregate(rhs.primitive))
470 Copy(pool, lhs.data.signature, rhs.data.signature);
472 sig::Type *&lht(lhs.data.data.type);
473 sig::Type *&rht(rhs.data.data.type);
478 lht = new(pool) Type;
479 Copy(pool, *lht, *rht);
482 lhs.data.data.size = rhs.data.data.size;
486 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
488 lhs.alignment = rhs.alignment;
490 if (rhs.elements == NULL)
494 while (rhs.elements[count] != NULL)
497 lhs.elements = new(pool) ffi_type *[count + 1];
498 lhs.elements[count] = NULL;
500 for (size_t index(0); index != count; ++index) {
501 // XXX: if these are libffi native then you can just take them
502 ffi_type *ffi(new(pool) ffi_type);
503 lhs.elements[index] = ffi;
504 sig::Copy(pool, *ffi, *rhs.elements[index]);
511 struct CStringMapLess :
512 std::binary_function<const char *, const char *, bool>
514 _finline bool operator ()(const char *lhs, const char *rhs) const {
515 return strcmp(lhs, rhs) < 0;
519 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
524 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
525 switch ([[entry objectAtIndex:0] intValue]) {
527 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
531 sig::Signature signature;
532 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
533 type = signature.elements[0].type;
539 struct Type_privateData :
542 static Type_privateData *Object;
543 static Type_privateData *Selector;
548 void Set(sig::Type *type) {
549 type_ = new(pool_) sig::Type;
550 sig::Copy(pool_, *type_, *type);
553 Type_privateData(apr_pool_t *pool, const char *type) :
559 sig::Signature signature;
560 sig::Parse(pool_, &signature, type, &Structor_);
561 type_ = signature.elements[0].type;
564 Type_privateData(sig::Type *type) :
571 Type_privateData(sig::Type *type, ffi_type *ffi) {
572 ffi_ = new(pool_) ffi_type;
573 sig::Copy(pool_, *ffi_, *ffi);
579 ffi_ = new(pool_) ffi_type;
581 sig::Element element;
583 element.type = type_;
586 sig::Signature signature;
587 signature.elements = &element;
591 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
599 Type_privateData *Type_privateData::Object;
600 Type_privateData *Type_privateData::Selector;
602 Type_privateData *Instance::GetType() const {
603 return Type_privateData::Object;
606 Type_privateData *Selector_privateData::GetType() const {
607 return Type_privateData::Selector;
613 Type_privateData *type_;
615 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
616 CYOwned(value, context, owner),
617 type_(new(pool_) Type_privateData(type))
622 struct Struct_privateData :
625 Type_privateData *type_;
627 Struct_privateData(JSContextRef context, JSObjectRef owner) :
628 CYOwned(NULL, context, owner)
633 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
634 static TypeMap Types_;
636 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
637 Struct_privateData *internal(new Struct_privateData(context, owner));
638 apr_pool_t *pool(internal->pool_);
639 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
640 internal->type_ = typical;
643 internal->value_ = data;
645 size_t size(typical->GetFFI()->size);
646 void *copy(apr_palloc(internal->pool_, size));
647 memcpy(copy, data, size);
648 internal->value_ = copy;
651 return JSObjectMake(context, Struct_, internal);
654 struct Functor_privateData :
657 sig::Signature signature_;
661 Functor_privateData(const char *type, void (*value)()) :
662 CYValue(reinterpret_cast<void *>(value))
664 sig::Parse(pool_, &signature_, type, &Structor_);
665 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
668 void (*GetValue())() const {
669 return reinterpret_cast<void (*)()>(value_);
673 struct Closure_privateData :
676 JSContextRef context_;
677 JSObjectRef function_;
679 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
680 Functor_privateData(type, NULL),
684 JSValueProtect(context_, function_);
687 virtual ~Closure_privateData() {
688 JSValueUnprotect(context_, function_);
692 struct Message_privateData :
697 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
698 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
704 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
705 Instance::Flags flags;
708 flags = Instance::Transient;
710 flags = Instance::None;
711 object = [object retain];
714 return Instance::Make(context, object, flags);
717 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
719 return [value UTF8String];
721 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
722 char *string(new(pool) char[size]);
723 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
724 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
729 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
730 return JSValueMakeBoolean(context, value);
733 JSValueRef CYCastJSValue(JSContextRef context, double value) {
734 return JSValueMakeNumber(context, value);
737 #define CYCastJSValue_(Type_) \
738 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
739 return JSValueMakeNumber(context, static_cast<double>(value)); \
743 CYCastJSValue_(unsigned int)
744 CYCastJSValue_(long int)
745 CYCastJSValue_(long unsigned int)
746 CYCastJSValue_(long long int)
747 CYCastJSValue_(long long unsigned int)
749 JSValueRef CYJSUndefined(JSContextRef context) {
750 return JSValueMakeUndefined(context);
753 size_t CYGetIndex(const char *value) {
754 if (value[0] != '0') {
756 size_t index(strtoul(value, &end, 10));
757 if (value + strlen(value) == end)
759 } else if (value[1] == '\0')
765 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value);
767 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
768 return CYGetIndex(CYPoolCString(pool, value));
771 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
772 return CYGetIndex(CYPoolCString(pool, value));
775 bool CYGetOffset(const char *value, ssize_t &index) {
776 if (value[0] != '0') {
778 index = strtol(value, &end, 10);
779 if (value + strlen(value) == end)
781 } else if (value[1] == '\0') {
789 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
790 return CYGetOffset(CYPoolCString(pool, value), index);
793 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
795 @interface NSMethodSignature (Cycript)
796 - (NSString *) _typeString;
799 @interface NSObject (Cycript)
801 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
802 - (JSType) cy$JSType;
804 - (NSObject *) cy$toJSON:(NSString *)key;
805 - (NSString *) cy$toCYON;
806 - (NSString *) cy$toKey;
808 - (bool) cy$hasProperty:(NSString *)name;
809 - (NSObject *) cy$getProperty:(NSString *)name;
810 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
811 - (bool) cy$deleteProperty:(NSString *)name;
816 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
819 @interface NSString (Cycript)
820 - (void *) cy$symbol;
823 struct PropertyAttributes {
828 const char *variable;
841 PropertyAttributes(objc_property_t property) :
853 name = property_getName(property);
854 const char *attributes(property_getAttributes(property));
856 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
858 case 'R': readonly = true; break;
859 case 'C': copy = true; break;
860 case '&': retain = true; break;
861 case 'N': nonatomic = true; break;
862 case 'G': getter_ = token + 1; break;
863 case 'S': setter_ = token + 1; break;
864 case 'V': variable = token + 1; break;
868 /*if (variable == NULL) {
869 variable = property_getName(property);
870 size_t size(strlen(variable));
871 char *name(new(pool_) char[size + 2]);
873 memcpy(name + 1, variable, size);
874 name[size + 1] = '\0';
879 const char *Getter() {
881 getter_ = apr_pstrdup(pool_, name);
885 const char *Setter() {
886 if (setter_ == NULL && !readonly) {
887 size_t length(strlen(name));
889 char *temp(new(pool_) char[length + 5]);
895 temp[3] = toupper(name[0]);
896 memcpy(temp + 4, name + 1, length - 1);
899 temp[length + 3] = ':';
900 temp[length + 4] = '\0';
909 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
910 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
913 /* Bridge: NSArray {{{ */
914 @implementation NSArray (Cycript)
916 - (NSString *) cy$toCYON {
917 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
918 [json appendString:@"["];
921 for (id object in self) {
923 [json appendString:@","];
926 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
927 [json appendString:CYPoolNSCYON(NULL, object)];
929 [json appendString:@","];
934 [json appendString:@"]"];
938 - (bool) cy$hasProperty:(NSString *)name {
939 if ([name isEqualToString:@"length"])
942 size_t index(CYGetIndex(NULL, name));
943 if (index == _not(size_t) || index >= [self count])
944 return [super cy$hasProperty:name];
949 - (NSObject *) cy$getProperty:(NSString *)name {
950 if ([name isEqualToString:@"length"])
951 return [NSNumber numberWithUnsignedInteger:[self count]];
953 size_t index(CYGetIndex(NULL, name));
954 if (index == _not(size_t) || index >= [self count])
955 return [super cy$getProperty:name];
957 return [self objectAtIndex:index];
962 /* Bridge: NSDictionary {{{ */
963 @implementation NSDictionary (Cycript)
965 - (NSString *) cy$toCYON {
966 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
967 [json appendString:@"{"];
970 for (id key in self) {
972 [json appendString:@","];
975 [json appendString:[key cy$toKey]];
976 [json appendString:@":"];
977 NSObject *object([self objectForKey:key]);
978 [json appendString:CYPoolNSCYON(NULL, object)];
981 [json appendString:@"}"];
985 - (bool) cy$hasProperty:(NSString *)name {
986 return [self objectForKey:name] != nil;
989 - (NSObject *) cy$getProperty:(NSString *)name {
990 return [self objectForKey:name];
995 /* Bridge: NSMutableArray {{{ */
996 @implementation NSMutableArray (Cycript)
998 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
999 if ([name isEqualToString:@"length"]) {
1000 // XXX: is this not intelligent?
1001 NSUInteger size([(NSNumber *)value unsignedIntegerValue]);
1002 NSUInteger count([self count]);
1004 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1005 else if (size != count) {
1006 WebUndefined *undefined([WebUndefined undefined]);
1007 for (size_t i(count); i != size; ++i)
1008 [self addObject:undefined];
1013 size_t index(CYGetIndex(NULL, name));
1014 if (index == _not(size_t))
1015 return [super cy$setProperty:name to:value];
1017 id object(value ?: [NSNull null]);
1019 size_t count([self count]);
1021 [self replaceObjectAtIndex:index withObject:object];
1023 if (index != count) {
1024 WebUndefined *undefined([WebUndefined undefined]);
1025 for (size_t i(count); i != index; ++i)
1026 [self addObject:undefined];
1029 [self addObject:object];
1035 - (bool) cy$deleteProperty:(NSString *)name {
1036 size_t index(CYGetIndex(NULL, name));
1037 if (index == _not(size_t) || index >= [self count])
1038 return [super cy$deleteProperty:name];
1039 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1045 /* Bridge: NSMutableDictionary {{{ */
1046 @implementation NSMutableDictionary (Cycript)
1048 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1049 [self setObject:(value ?: [NSNull null]) forKey:name];
1053 - (bool) cy$deleteProperty:(NSString *)name {
1054 if ([self objectForKey:name] == nil)
1057 [self removeObjectForKey:name];
1064 /* Bridge: NSNumber {{{ */
1065 @implementation NSNumber (Cycript)
1067 - (JSType) cy$JSType {
1068 // XXX: this just seems stupid
1069 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
1072 - (NSObject *) cy$toJSON:(NSString *)key {
1076 - (NSString *) cy$toCYON {
1077 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1080 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1081 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1086 /* Bridge: NSNull {{{ */
1087 @implementation NSNull (Cycript)
1089 - (JSType) cy$JSType {
1093 - (NSObject *) cy$toJSON:(NSString *)key {
1097 - (NSString *) cy$toCYON {
1103 /* Bridge: NSObject {{{ */
1104 @implementation NSObject (Cycript)
1106 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1107 return CYMakeInstance(context, self, false);
1110 - (JSType) cy$JSType {
1111 return kJSTypeObject;
1114 - (NSObject *) cy$toJSON:(NSString *)key {
1115 return [self description];
1118 - (NSString *) cy$toCYON {
1119 return [[self cy$toJSON:@""] cy$toCYON];
1122 - (NSString *) cy$toKey {
1123 return [self cy$toCYON];
1126 - (bool) cy$hasProperty:(NSString *)name {
1130 - (NSObject *) cy$getProperty:(NSString *)name {
1134 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1138 - (bool) cy$deleteProperty:(NSString *)name {
1144 /* Bridge: NSProxy {{{ */
1145 @implementation NSProxy (Cycript)
1147 - (NSObject *) cy$toJSON:(NSString *)key {
1148 return [self description];
1151 - (NSString *) cy$toCYON {
1152 return [[self cy$toJSON:@""] cy$toCYON];
1157 /* Bridge: NSString {{{ */
1158 @implementation NSString (Cycript)
1160 - (JSType) cy$JSType {
1161 return kJSTypeString;
1164 - (NSObject *) cy$toJSON:(NSString *)key {
1168 - (NSString *) cy$toCYON {
1169 // XXX: this should use the better code from Output.cpp
1170 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
1172 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
1173 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
1174 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
1175 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
1176 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
1178 CFStringInsert(json, 0, CFSTR("\""));
1179 CFStringAppend(json, CFSTR("\""));
1181 return [reinterpret_cast<const NSString *>(json) autorelease];
1184 - (NSString *) cy$toKey {
1185 const char *value([self UTF8String]);
1186 size_t size(strlen(value));
1191 if (DigitRange_[value[0]]) {
1192 size_t index(CYGetIndex(NULL, self));
1193 if (index == _not(size_t))
1196 if (!WordStartRange_[value[0]])
1198 for (size_t i(1); i != size; ++i)
1199 if (!WordEndRange_[value[i]])
1206 return [self cy$toCYON];
1209 - (void *) cy$symbol {
1211 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1216 /* Bridge: WebUndefined {{{ */
1217 @implementation WebUndefined (Cycript)
1219 - (JSType) cy$JSType {
1220 return kJSTypeUndefined;
1223 - (NSObject *) cy$toJSON:(NSString *)key {
1227 - (NSString *) cy$toCYON {
1228 return @"undefined";
1231 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1232 return CYJSUndefined(context);
1238 @interface CYJSObject : NSMutableDictionary {
1239 JSObjectRef object_;
1240 JSContextRef context_;
1243 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1245 - (NSString *) cy$toJSON:(NSString *)key;
1247 - (NSUInteger) count;
1248 - (id) objectForKey:(id)key;
1249 - (NSEnumerator *) keyEnumerator;
1250 - (void) setObject:(id)object forKey:(id)key;
1251 - (void) removeObjectForKey:(id)key;
1255 @interface CYJSArray : NSMutableArray {
1256 JSObjectRef object_;
1257 JSContextRef context_;
1260 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1262 - (NSUInteger) count;
1263 - (id) objectAtIndex:(NSUInteger)index;
1265 - (void) addObject:(id)anObject;
1266 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1267 - (void) removeLastObject;
1268 - (void) removeObjectAtIndex:(NSUInteger)index;
1269 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1273 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1274 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1275 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1280 @catch (id error) { \
1281 CYThrow(context, error, exception); \
1285 apr_status_t CYPoolRelease_(void *data) {
1286 id object(reinterpret_cast<id>(data));
1291 id CYPoolRelease(apr_pool_t *pool, id object) {
1294 else if (pool == NULL)
1295 return [object autorelease];
1297 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1302 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1303 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1306 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1307 JSValueRef exception(NULL);
1308 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1309 CYThrow(context, exception);
1310 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1311 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1314 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1315 if (!JSValueIsObjectOfClass(context, object, Instance_))
1316 return CYCastNSObject_(pool, context, object);
1318 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1319 return internal->GetValue();
1323 double CYCastDouble(const char *value, size_t size) {
1325 double number(strtod(value, &end));
1326 if (end != value + size)
1331 double CYCastDouble(const char *value) {
1332 return CYCastDouble(value, strlen(value));
1335 double CYCastDouble(JSContextRef context, JSValueRef value) {
1336 JSValueRef exception(NULL);
1337 double number(JSValueToNumber(context, value, &exception));
1338 CYThrow(context, exception);
1342 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1343 double number(CYCastDouble(context, value));
1344 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1347 CFStringRef CYCopyCFString(const char *value) {
1348 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1351 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1352 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1355 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1356 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1359 bool CYCastBool(JSContextRef context, JSValueRef value) {
1360 return JSValueToBoolean(context, value);
1363 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1367 switch (JSType type = JSValueGetType(context, value)) {
1368 case kJSTypeUndefined:
1369 object = [WebUndefined undefined];
1377 case kJSTypeBoolean:
1378 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1383 object = CYCopyCFNumber(context, value);
1388 object = CYCopyCFString(context, value);
1393 // XXX: this might could be more efficient
1394 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1399 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1406 return CYPoolRelease(pool, object);
1408 return CFRetain(object);
1411 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1412 return CYCFType(pool, context, value, true);
1415 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1416 return CYCFType(pool, context, value, false);
1419 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1421 size_t size(JSPropertyNameArrayGetCount(names));
1422 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1423 for (size_t index(0); index != size; ++index)
1424 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1428 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1429 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1432 void CYThrow(JSContextRef context, JSValueRef value) {
1435 @throw CYCastNSObject(NULL, context, value);
1438 JSValueRef CYJSNull(JSContextRef context) {
1439 return JSValueMakeNull(context);
1442 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1443 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1446 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1447 return CYCastJSValue(context, CYJSString(value));
1450 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1452 return CYJSNull(context);
1453 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1454 return [value cy$JSValueInContext:context];
1456 return CYMakeInstance(context, value, false);
1459 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1460 JSValueRef exception(NULL);
1461 JSObjectRef object(JSValueToObject(context, value, &exception));
1462 CYThrow(context, exception);
1466 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1467 if (exception == NULL)
1469 *exception = CYCastJSValue(context, error);
1472 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1473 JSValueRef exception(NULL);
1474 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1475 CYThrow(context, exception);
1479 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1480 // XXX: this isn't actually correct
1481 return value != NULL && JSValueIsObject(context, value);
1484 @implementation CYJSObject
1486 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1487 if ((self = [super init]) != nil) {
1490 JSValueProtect(context_, object_);
1495 JSValueUnprotect(context_, object_);
1499 - (NSObject *) cy$toJSON:(NSString *)key {
1500 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1501 if (!CYIsCallable(context_, toJSON))
1502 return [super cy$toJSON:key];
1504 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1505 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1506 // XXX: do I really want an NSNull here?!
1507 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1511 - (NSString *) cy$toCYON {
1512 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1513 if (!CYIsCallable(context_, toCYON)) super:
1514 return [super cy$toCYON];
1515 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1516 return CYCastNSString(NULL, CYJSString(context_, value));
1520 - (NSUInteger) count {
1521 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1522 size_t size(JSPropertyNameArrayGetCount(names));
1523 JSPropertyNameArrayRelease(names);
1527 - (id) objectForKey:(id)key {
1528 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1529 if (JSValueIsUndefined(context_, value))
1531 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1534 - (NSEnumerator *) keyEnumerator {
1535 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1536 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1537 JSPropertyNameArrayRelease(names);
1541 - (void) setObject:(id)object forKey:(id)key {
1542 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1545 - (void) removeObjectForKey:(id)key {
1546 JSValueRef exception(NULL);
1547 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1548 CYThrow(context_, exception);
1553 @implementation CYJSArray
1555 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1556 if ((self = [super init]) != nil) {
1559 JSValueProtect(context_, object_);
1564 JSValueUnprotect(context_, object_);
1568 - (NSUInteger) count {
1569 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1572 - (id) objectAtIndex:(NSUInteger)index {
1573 size_t bounds([self count]);
1574 if (index >= bounds)
1575 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1576 JSValueRef exception(NULL);
1577 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1578 CYThrow(context_, exception);
1579 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1582 - (void) addObject:(id)object {
1583 JSValueRef exception(NULL);
1584 JSValueRef arguments[1];
1585 arguments[0] = CYCastJSValue(context_, object);
1586 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1587 CYThrow(context_, exception);
1590 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1591 size_t bounds([self count] + 1);
1592 if (index >= bounds)
1593 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1594 JSValueRef exception(NULL);
1595 JSValueRef arguments[3];
1596 arguments[0] = CYCastJSValue(context_, index);
1597 arguments[1] = CYCastJSValue(context_, 0);
1598 arguments[2] = CYCastJSValue(context_, object);
1599 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1600 CYThrow(context_, exception);
1603 - (void) removeLastObject {
1604 JSValueRef exception(NULL);
1605 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1606 CYThrow(context_, exception);
1609 - (void) removeObjectAtIndex:(NSUInteger)index {
1610 size_t bounds([self count]);
1611 if (index >= bounds)
1612 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1613 JSValueRef exception(NULL);
1614 JSValueRef arguments[2];
1615 arguments[0] = CYCastJSValue(context_, index);
1616 arguments[1] = CYCastJSValue(context_, 1);
1617 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1618 CYThrow(context_, exception);
1621 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1622 size_t bounds([self count]);
1623 if (index >= bounds)
1624 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1625 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1630 NSString *CYCopyNSCYON(id value) {
1636 Class _class(object_getClass(value));
1637 SEL sel(@selector(cy$toCYON));
1639 if (Method toCYON = class_getInstanceMethod(_class, sel))
1640 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1641 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1642 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1643 string = [value cy$toCYON];
1646 if (value == NSZombie_)
1647 string = @"_NSZombie_";
1648 else if (_class == NSZombie_)
1649 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1650 // XXX: frowny /in/ the pants
1651 else if (value == NSMessageBuilder_ || value == Object_)
1654 string = [NSString stringWithFormat:@"%@", value];
1657 // XXX: frowny pants
1659 string = @"undefined";
1662 return [string retain];
1665 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1666 if (JSValueIsNull(context, value))
1667 return [@"null" retain];
1671 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1676 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1677 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1680 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1681 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1682 const char *string(CYPoolCString(pool, json));
1688 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1692 JSObjectRef object_;
1700 // XXX: delete object_? ;(
1703 static CYInternal *Get(id self) {
1704 CYInternal *internal(NULL);
1705 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1706 // XXX: do something epic? ;P
1712 static CYInternal *Set(id self) {
1713 CYInternal *internal(NULL);
1714 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1715 if (internal == NULL) {
1716 internal = new CYInternal();
1717 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1720 // XXX: do something epic? ;P
1726 bool HasProperty(JSContextRef context, JSStringRef name) {
1727 if (object_ == NULL)
1729 return JSObjectHasProperty(context, object_, name);
1732 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1733 if (object_ == NULL)
1735 return CYGetProperty(context, object_, name);
1738 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1739 if (object_ == NULL)
1740 object_ = JSObjectMake(context, NULL, NULL);
1741 CYSetProperty(context, object_, name, value);
1745 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1746 Selector_privateData *internal(new Selector_privateData(sel));
1747 return JSObjectMake(context, Selector_, internal);
1750 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1751 Pointer *internal(new Pointer(pointer, context, owner, type));
1752 return JSObjectMake(context, Pointer_, internal);
1755 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1756 Functor_privateData *internal(new Functor_privateData(type, function));
1757 return JSObjectMake(context, Functor_, internal);
1760 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1762 // XXX: this could be much more efficient
1763 const char *string([CYCastNSString(NULL, value) UTF8String]);
1766 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1767 char *string(new(pool) char[size]);
1768 JSStringGetUTF8CString(value, string, size);
1773 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1774 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1777 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1778 return CYGetOffset(CYPoolCString(pool, value), index);
1781 // XXX: this macro is unhygenic
1782 #define CYCastCString(context, value) ({ \
1784 if (value == NULL) \
1786 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1787 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1788 utf8 = reinterpret_cast<char *>(alloca(size)); \
1789 JSStringGetUTF8CString(string, utf8, size); \
1790 JSStringRelease(string); \
1796 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1797 switch (JSValueGetType(context, value)) {
1800 /*case kJSTypeString:
1801 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1803 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1804 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1805 return internal->value_;
1808 double number(CYCastDouble(context, value));
1809 if (std::isnan(number))
1810 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1811 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1815 template <typename Type_>
1816 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1817 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1820 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1821 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1822 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1823 return reinterpret_cast<SEL>(internal->value_);
1825 return CYCastPointer<SEL>(context, value);
1828 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1829 switch (type->primitive) {
1830 case sig::boolean_P:
1831 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1834 #define CYPoolFFI_(primitive, native) \
1835 case sig::primitive ## _P: \
1836 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1839 CYPoolFFI_(uchar, unsigned char)
1840 CYPoolFFI_(char, char)
1841 CYPoolFFI_(ushort, unsigned short)
1842 CYPoolFFI_(short, short)
1843 CYPoolFFI_(ulong, unsigned long)
1844 CYPoolFFI_(long, long)
1845 CYPoolFFI_(uint, unsigned int)
1846 CYPoolFFI_(int, int)
1847 CYPoolFFI_(ulonglong, unsigned long long)
1848 CYPoolFFI_(longlong, long long)
1849 CYPoolFFI_(float, float)
1850 CYPoolFFI_(double, double)
1853 case sig::typename_P:
1854 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1857 case sig::selector_P:
1858 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1861 case sig::pointer_P:
1862 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1866 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1869 case sig::struct_P: {
1870 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1871 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1872 for (size_t index(0); index != type->data.signature.count; ++index) {
1873 sig::Element *element(&type->data.signature.elements[index]);
1874 ffi_type *field(ffi->elements[index]);
1877 if (aggregate == NULL)
1880 rhs = CYGetProperty(context, aggregate, index);
1881 if (JSValueIsUndefined(context, rhs)) {
1882 if (element->name != NULL)
1883 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1886 if (JSValueIsUndefined(context, rhs)) undefined:
1887 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1891 CYPoolFFI(pool, context, element->type, field, base, rhs);
1893 base += field->size;
1901 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1906 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1909 switch (type->primitive) {
1910 case sig::boolean_P:
1911 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1914 #define CYFromFFI_(primitive, native) \
1915 case sig::primitive ## _P: \
1916 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1919 CYFromFFI_(uchar, unsigned char)
1920 CYFromFFI_(char, char)
1921 CYFromFFI_(ushort, unsigned short)
1922 CYFromFFI_(short, short)
1923 CYFromFFI_(ulong, unsigned long)
1924 CYFromFFI_(long, long)
1925 CYFromFFI_(uint, unsigned int)
1926 CYFromFFI_(int, int)
1927 CYFromFFI_(ulonglong, unsigned long long)
1928 CYFromFFI_(longlong, long long)
1929 CYFromFFI_(float, float)
1930 CYFromFFI_(double, double)
1932 case sig::object_P: {
1933 if (id object = *reinterpret_cast<id *>(data)) {
1934 value = CYCastJSValue(context, object);
1940 case sig::typename_P:
1941 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1944 case sig::selector_P:
1945 if (SEL sel = *reinterpret_cast<SEL *>(data))
1946 value = CYMakeSelector(context, sel);
1950 case sig::pointer_P:
1951 if (void *pointer = *reinterpret_cast<void **>(data))
1952 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1957 if (char *utf8 = *reinterpret_cast<char **>(data))
1958 value = CYCastJSValue(context, utf8);
1963 value = CYMakeStruct(context, data, type, ffi, owner);
1967 value = CYJSUndefined(context);
1971 value = CYJSNull(context);
1975 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1982 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1983 if (Method method = class_getInstanceMethod(_class, selector)) {
1987 method_getReturnType(method, type, sizeof(type));
1992 // XXX: possibly use a more "awesome" check?
1996 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
1998 return method_getTypeEncoding(method);
1999 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2000 return CYPoolCString(pool, type);
2005 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2006 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2008 JSContextRef context(internal->context_);
2010 size_t count(internal->cif_.nargs);
2011 JSValueRef values[count];
2013 for (size_t index(0); index != count; ++index)
2014 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2016 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2017 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2020 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2021 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2023 JSContextRef context(internal->context_);
2025 size_t count(internal->cif_.nargs);
2026 JSValueRef values[count];
2028 for (size_t index(0); index != count; ++index)
2029 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2031 JSObjectRef _this(CYCastJSObject(context, values[0]));
2033 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2034 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2037 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2038 // XXX: in case of exceptions this will leak
2039 // XXX: in point of fact, this may /need/ to leak :(
2040 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2042 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2043 NULL, sizeof(ffi_closure),
2044 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2048 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2049 _assert(status == FFI_OK);
2051 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2053 internal->value_ = closure;
2058 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2059 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2060 return JSObjectMake(context, Functor_, internal);
2063 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2064 JSValueRef exception(NULL);
2065 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2066 CYThrow(context, exception);
2069 JSObjectRef function(CYCastJSObject(context, value));
2070 return CYMakeFunctor(context, function, type);
2072 void (*function)()(CYCastPointer<void (*)()>(context, value));
2073 return CYMakeFunctor(context, function, type);
2077 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2078 Message_privateData *internal(new Message_privateData(sel, type, imp));
2079 return JSObjectMake(context, Message_, internal);
2082 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2083 JSObjectRef function(CYCastJSObject(context, value));
2084 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2085 return reinterpret_cast<IMP>(internal->GetValue());
2088 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2089 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2090 Class _class(internal->GetValue());
2093 const char *name(CYPoolCString(pool, property));
2095 if (SEL sel = sel_getUid(name))
2096 if (class_getInstanceMethod(_class, sel) != NULL)
2102 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2103 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2104 Class _class(internal->GetValue());
2107 const char *name(CYPoolCString(pool, property));
2109 if (SEL sel = sel_getUid(name))
2110 if (Method method = class_getInstanceMethod(_class, sel))
2111 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2116 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2117 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2118 Class _class(internal->GetValue());
2121 const char *name(CYPoolCString(pool, property));
2123 SEL sel(sel_registerName(name));
2125 Method method(class_getInstanceMethod(_class, sel));
2130 if (JSValueIsObjectOfClass(context, value, Message_)) {
2131 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2132 type = sig::Unparse(pool, &message->signature_);
2133 imp = reinterpret_cast<IMP>(message->GetValue());
2135 type = CYPoolTypeEncoding(pool, _class, sel, method);
2136 imp = CYMakeMessage(context, value, type);
2140 method_setImplementation(method, imp);
2142 class_replaceMethod(_class, sel, imp, type);
2148 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2149 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2150 Class _class(internal->GetValue());
2153 const char *name(CYPoolCString(pool, property));
2155 if (SEL sel = sel_getUid(name))
2156 if (Method method = class_getInstanceMethod(_class, sel)) {
2157 objc_method_list list = {NULL, 1, {method}};
2158 class_removeMethods(_class, &list);
2166 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2167 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2168 Class _class(internal->GetValue());
2171 Method *data(class_copyMethodList(_class, &size));
2172 for (size_t i(0); i != size; ++i)
2173 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2177 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2178 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2179 id self(internal->GetValue());
2181 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2185 NSString *name(CYCastNSString(pool, property));
2187 if (CYInternal *internal = CYInternal::Get(self))
2188 if (internal->HasProperty(context, property))
2191 Class _class(object_getClass(self));
2194 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2195 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2196 if ([self cy$hasProperty:name])
2198 } CYPoolCatch(false)
2200 const char *string(CYPoolCString(pool, name));
2202 if (class_getProperty(_class, string) != NULL)
2205 if (SEL sel = sel_getUid(string))
2206 if (CYImplements(self, _class, sel, true))
2212 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2213 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2214 id self(internal->GetValue());
2216 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2217 return Internal::Make(context, self, object);
2221 NSString *name(CYCastNSString(pool, property));
2223 if (CYInternal *internal = CYInternal::Get(self))
2224 if (JSValueRef value = internal->GetProperty(context, property))
2228 if (NSObject *data = [self cy$getProperty:name])
2229 return CYCastJSValue(context, data);
2232 const char *string(CYPoolCString(pool, name));
2233 Class _class(object_getClass(self));
2235 if (objc_property_t property = class_getProperty(_class, string)) {
2236 PropertyAttributes attributes(property);
2237 SEL sel(sel_registerName(attributes.Getter()));
2238 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2241 if (SEL sel = sel_getUid(string))
2242 if (CYImplements(self, _class, sel, true))
2243 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2249 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2250 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2251 id self(internal->GetValue());
2256 NSString *name(CYCastNSString(pool, property));
2257 NSString *data(CYCastNSObject(pool, context, value));
2260 if ([self cy$setProperty:name to:data])
2264 const char *string(CYPoolCString(pool, name));
2265 Class _class(object_getClass(self));
2267 if (objc_property_t property = class_getProperty(_class, string)) {
2268 PropertyAttributes attributes(property);
2269 if (const char *setter = attributes.Setter()) {
2270 SEL sel(sel_registerName(setter));
2271 JSValueRef arguments[1] = {value};
2272 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2277 size_t length(strlen(string));
2279 char set[length + 5];
2285 if (string[0] != '\0') {
2286 set[3] = toupper(string[0]);
2287 memcpy(set + 4, string + 1, length - 1);
2290 set[length + 3] = ':';
2291 set[length + 4] = '\0';
2293 if (SEL sel = sel_getUid(set))
2294 if (CYImplements(self, _class, sel, false)) {
2295 JSValueRef arguments[1] = {value};
2296 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2299 if (CYInternal *internal = CYInternal::Set(self)) {
2300 internal->SetProperty(context, property, value);
2308 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2309 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2310 id self(internal->GetValue());
2314 NSString *name(CYCastNSString(NULL, property));
2315 return [self cy$deleteProperty:name];
2320 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2321 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2322 id self(internal->GetValue());
2325 Class _class(object_getClass(self));
2329 objc_property_t *data(class_copyPropertyList(_class, &size));
2330 for (size_t i(0); i != size; ++i)
2331 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2336 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2338 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2339 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2344 static bool CYIsClass(id self) {
2345 // XXX: this is a lame object_isClass
2346 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2349 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2350 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2351 Class _class(internal->GetValue());
2352 if (!CYIsClass(_class))
2355 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2356 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2357 // XXX: this isn't always safe
2359 return [linternal->GetValue() isKindOfClass:_class];
2366 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2367 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2370 id self(internal->GetValue());
2371 const char *name(CYPoolCString(pool, property));
2373 if (object_getInstanceVariable(self, name, NULL) != NULL)
2379 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2380 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2384 id self(internal->GetValue());
2385 const char *name(CYPoolCString(pool, property));
2387 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2388 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2389 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2396 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2397 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2401 id self(internal->GetValue());
2402 const char *name(CYPoolCString(pool, property));
2404 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2405 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2406 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2414 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2415 if (Class super = class_getSuperclass(_class))
2416 Internal_getPropertyNames_(super, names);
2419 Ivar *data(class_copyIvarList(_class, &size));
2420 for (size_t i(0); i != size; ++i)
2421 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2425 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2426 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2429 id self(internal->GetValue());
2430 Class _class(object_getClass(self));
2432 Internal_getPropertyNames_(_class, names);
2435 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2436 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2437 return internal->GetOwner();
2440 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2441 Type_privateData *typical(internal->type_);
2442 sig::Type *type(typical->type_);
2446 const char *name(CYPoolCString(pool, property));
2447 size_t length(strlen(name));
2448 double number(CYCastDouble(name, length));
2450 size_t count(type->data.signature.count);
2452 if (std::isnan(number)) {
2453 if (property == NULL)
2456 sig::Element *elements(type->data.signature.elements);
2458 for (size_t local(0); local != count; ++local) {
2459 sig::Element *element(&elements[local]);
2460 if (element->name != NULL && strcmp(name, element->name) == 0) {
2468 index = static_cast<ssize_t>(number);
2469 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2474 ffi_type **elements(typical->GetFFI()->elements);
2476 base = reinterpret_cast<uint8_t *>(internal->value_);
2477 for (ssize_t local(0); local != index; ++local)
2478 base += elements[local]->size;
2483 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2484 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2485 Type_privateData *typical(internal->type_);
2487 ffi_type *ffi(typical->GetFFI());
2489 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2490 base += ffi->size * index;
2492 JSObjectRef owner(internal->GetOwner() ?: object);
2495 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2499 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2501 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2502 Type_privateData *typical(internal->type_);
2504 if (typical->type_ == NULL)
2508 if (!CYGetOffset(pool, property, offset))
2511 return Pointer_getIndex(context, object, offset, exception);
2514 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2515 return Pointer_getIndex(context, object, 0, exception);
2518 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2519 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2520 Type_privateData *typical(internal->type_);
2522 ffi_type *ffi(typical->GetFFI());
2524 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2525 base += ffi->size * index;
2528 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2533 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2535 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2536 Type_privateData *typical(internal->type_);
2538 if (typical->type_ == NULL)
2542 if (!CYGetOffset(pool, property, offset))
2545 return Pointer_setIndex(context, object, offset, value, exception);
2548 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2549 return Pointer_setIndex(context, object, 0, value, exception);
2552 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2553 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2554 Type_privateData *typical(internal->type_);
2555 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2558 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2560 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2561 Type_privateData *typical(internal->type_);
2566 if (!Index_(pool, internal, property, index, base))
2569 JSObjectRef owner(internal->GetOwner() ?: object);
2572 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2576 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2578 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2579 Type_privateData *typical(internal->type_);
2584 if (!Index_(pool, internal, property, index, base))
2588 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2593 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2594 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2595 Type_privateData *typical(internal->type_);
2596 sig::Type *type(typical->type_);
2601 size_t count(type->data.signature.count);
2602 sig::Element *elements(type->data.signature.elements);
2606 for (size_t index(0); index != count; ++index) {
2608 name = elements[index].name;
2611 sprintf(number, "%lu", index);
2615 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2619 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)()) {
2621 if (setups + count != signature->count - 1)
2622 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2624 size_t size(setups + count);
2626 memcpy(values, setup, sizeof(void *) * setups);
2628 for (size_t index(setups); index != size; ++index) {
2629 sig::Element *element(&signature->elements[index + 1]);
2630 ffi_type *ffi(cif->arg_types[index]);
2632 values[index] = new(pool) uint8_t[ffi->size];
2633 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2636 uint8_t value[cif->rtype->size];
2637 ffi_call(cif, function, value, values);
2639 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2643 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2646 NSString *name(CYCastNSString(pool, property));
2647 if (Class _class = NSClassFromString(name))
2648 return CYMakeInstance(context, _class, true);
2653 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2654 size_t size(objc_getClassList(NULL, 0));
2655 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2658 size_t writ(objc_getClassList(data, size));
2661 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2667 for (size_t i(0); i != writ; ++i)
2668 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2674 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2675 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2679 const char *name(CYPoolCString(pool, property));
2681 const char **data(objc_copyClassNamesForImage(internal, &size));
2683 for (size_t i(0); i != size; ++i)
2684 if (strcmp(name, data[i]) == 0) {
2685 if (Class _class = objc_getClass(name)) {
2686 value = CYMakeInstance(context, _class, true);
2698 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2699 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2701 const char **data(objc_copyClassNamesForImage(internal, &size));
2702 for (size_t i(0); i != size; ++i)
2703 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2707 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2710 const char *name(CYPoolCString(pool, property));
2712 const char **data(objc_copyImageNames(&size));
2713 for (size_t i(0); i != size; ++i)
2714 if (strcmp(name, data[i]) == 0) {
2723 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2724 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2729 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2731 const char **data(objc_copyImageNames(&size));
2732 for (size_t i(0); i != size; ++i)
2733 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2737 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2740 NSString *name(CYCastNSString(pool, property));
2741 if (Protocol *protocol = NSProtocolFromString(name))
2742 return CYMakeInstance(context, protocol, true);
2747 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2749 Protocol **data(objc_copyProtocolList(&size));
2750 for (size_t i(0); i != size; ++i)
2751 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2755 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
2756 Type_privateData *internal(new Type_privateData(NULL, type));
2757 return JSObjectMake(context, Type_, internal);
2760 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
2761 Type_privateData *internal(new Type_privateData(type));
2762 return JSObjectMake(context, Type_, internal);
2765 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2766 if (JSStringIsEqualToUTF8CString(property, "nil"))
2767 return Instance::Make(context, nil);
2771 NSString *name(CYCastNSString(pool, property));
2772 if (Class _class = NSClassFromString(name))
2773 return CYMakeInstance(context, _class, true);
2774 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2775 switch ([[entry objectAtIndex:0] intValue]) {
2777 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2779 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2781 // XXX: this is horrendously inefficient
2782 sig::Signature signature;
2783 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2785 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2786 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2788 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
2789 switch ([[entry objectAtIndex:0] intValue]) {
2790 // XXX: implement case 0
2792 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
2798 static bool stret(ffi_type *ffi_type) {
2799 return ffi_type->type == FFI_TYPE_STRUCT && (
2800 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2801 struct_forward_array[ffi_type->size] != 0
2806 int *_NSGetArgc(void);
2807 char ***_NSGetArgv(void);
2808 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2811 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2813 NSLog(@"%s", CYCastCString(context, arguments[0]));
2814 return CYJSUndefined(context);
2818 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2821 Class _class(object_getClass(self));
2822 if (Method method = class_getInstanceMethod(_class, _cmd))
2823 type = method_getTypeEncoding(method);
2827 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2829 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2830 type = CYPoolCString(pool, [method _typeString]);
2839 sig::Signature signature;
2840 sig::Parse(pool, &signature, type, &Structor_);
2843 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2845 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2846 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2849 static size_t Nonce_(0);
2851 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2853 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
2854 return CYCastJSValue(context, name);
2857 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2867 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2869 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2870 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2871 self = internal->GetValue();
2872 uninitialized = internal->IsUninitialized();
2874 internal->value_ = nil;
2876 self = CYCastNSObject(pool, context, arguments[0]);
2877 uninitialized = false;
2881 return CYJSNull(context);
2883 _cmd = CYCastSEL(context, arguments[1]);
2886 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2889 /* Hook: objc_registerClassPair {{{ */
2890 // XXX: replace this with associated objects
2892 MSHook(void, CYDealloc, id self, SEL sel) {
2893 CYInternal *internal;
2894 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2895 if (internal != NULL)
2897 _CYDealloc(self, sel);
2900 MSHook(void, objc_registerClassPair, Class _class) {
2901 Class super(class_getSuperclass(_class));
2902 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2903 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2904 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2907 _objc_registerClassPair(_class);
2910 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2913 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2915 Class _class(CYCastNSObject(pool, context, arguments[0]));
2916 $objc_registerClassPair(_class);
2917 return CYJSUndefined(context);
2922 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2923 JSValueRef setup[count + 2];
2926 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2927 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2930 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2932 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2934 // XXX: handle Instance::Uninitialized?
2935 id self(CYCastNSObject(pool, context, _this));
2939 setup[1] = &internal->sel_;
2941 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2944 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2946 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2947 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2950 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2953 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2954 const char *name(CYCastCString(context, arguments[0]));
2955 return CYMakeSelector(context, sel_registerName(name));
2959 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2962 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2964 void *value(CYCastPointer<void *>(context, arguments[0]));
2965 const char *type(CYCastCString(context, arguments[1]));
2969 sig::Signature signature;
2970 sig::Parse(pool, &signature, type, &Structor_);
2972 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2976 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2979 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2980 const char *type(CYCastCString(context, arguments[0]));
2981 return CYMakeType(context, type);
2985 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2986 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2991 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
2992 type.primitive = sig::pointer_P;
2993 type.data.data.size = 0;
2995 size_t index(CYGetIndex(NULL, property));
2996 if (index == _not(size_t))
2998 type.primitive = sig::array_P;
2999 type.data.data.size = index;
3005 type.data.data.type = internal->type_;
3007 return CYMakeType(context, &type);
3011 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3012 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3016 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3017 sig::Type *type(internal->type_);
3018 ffi_type *ffi(internal->GetFFI());
3020 uint8_t value[ffi->size];
3022 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3023 return CYFromFFI(context, type, ffi, value);
3027 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3030 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3031 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3033 sig::Type *type(internal->type_);
3036 if (type->primitive != sig::array_P)
3039 size = type->data.data.size;
3040 type = type->data.data.type;
3043 void *value(malloc(internal->GetFFI()->size));
3044 return CYMakePointer(context, value, type, NULL, NULL);
3048 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3051 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
3052 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3053 return Instance::Make(context, self);
3057 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3060 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
3061 const char *type(CYCastCString(context, arguments[1]));
3062 return CYMakeFunctor(context, arguments[0], type);
3066 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3067 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3068 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3071 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3072 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3073 Type_privateData *typical(internal->GetType());
3078 if (typical == NULL) {
3082 type = typical->type_;
3083 ffi = typical->ffi_;
3086 return CYMakePointer(context, &internal->value_, type, ffi, object);
3089 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3090 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3093 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3097 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3098 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3101 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3102 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3104 sprintf(string, "%p", internal->value_);
3107 return CYCastJSValue(context, string);
3111 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3112 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3113 return Instance::Make(context, object_getClass(internal->GetValue()));
3116 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3117 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3118 id self(internal->GetValue());
3119 if (!CYIsClass(self))
3120 return CYJSUndefined(context);
3122 return CYGetClassPrototype(context, self);
3126 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3127 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3128 id self(internal->GetValue());
3129 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3130 return CYJSUndefined(context);
3131 return Messages::Make(context, self);
3134 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3135 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3138 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3142 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
3147 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3148 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3151 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3155 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3156 // XXX: check for support of cy$toJSON?
3157 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3162 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3163 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3166 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3170 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3175 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3176 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3179 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3183 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3184 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3187 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3188 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3189 const char *name(sel_getName(internal->GetValue()));
3193 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3198 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3201 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
3203 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3204 Class _class(CYCastNSObject(pool, context, arguments[0]));
3205 SEL sel(internal->GetValue());
3206 Method method(class_getInstanceMethod(_class, sel));
3207 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3208 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3212 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3214 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3216 const char *type(sig::Unparse(pool, internal->type_));
3218 return CYCastJSValue(context, CYJSString(type));
3223 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3225 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3227 const char *type(sig::Unparse(pool, internal->type_));
3229 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
3234 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3235 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3238 static JSStaticValue CYValue_staticValues[2] = {
3239 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3240 {NULL, NULL, NULL, 0}
3243 static JSStaticValue Pointer_staticValues[2] = {
3244 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3245 {NULL, NULL, NULL, 0}
3248 static JSStaticFunction Pointer_staticFunctions[4] = {
3249 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3250 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3251 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3255 static JSStaticFunction Struct_staticFunctions[2] = {
3256 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3260 static JSStaticFunction Functor_staticFunctions[4] = {
3261 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3262 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3263 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3267 static JSStaticValue Instance_staticValues[5] = {
3268 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3269 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3270 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3271 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3272 {NULL, NULL, NULL, 0}
3275 static JSStaticFunction Instance_staticFunctions[5] = {
3276 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3277 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3278 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3279 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3283 static JSStaticFunction Internal_staticFunctions[2] = {
3284 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3288 static JSStaticFunction Selector_staticFunctions[5] = {
3289 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3290 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3291 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3292 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3296 static JSStaticFunction Type_staticFunctions[4] = {
3297 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3298 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3299 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3303 CYDriver::CYDriver(const std::string &filename) :
3309 filename_(filename),
3315 CYDriver::~CYDriver() {
3319 void CYDriver::Warning(const cy::location &location, const char *message) {
3323 CYDriver::Error error;
3324 error.warning_ = true;
3325 error.location_ = location;
3326 error.message_ = message;
3327 errors_.push_back(error);
3330 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
3331 CYDriver::Error error;
3332 error.warning_ = false;
3333 error.location_ = location;
3334 error.message_ = message;
3335 driver.errors_.push_back(error);
3338 void CYSetArgs(int argc, const char *argv[]) {
3339 JSContextRef context(CYGetJSContext());
3340 JSValueRef args[argc];
3341 for (int i(0); i != argc; ++i)
3342 args[i] = CYCastJSValue(context, argv[i]);
3343 JSValueRef exception(NULL);
3344 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3345 CYThrow(context, exception);
3346 CYSetProperty(context, System_, CYJSString("args"), array);
3349 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3350 return JSContextGetGlobalObject(context);
3353 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3354 JSContextRef context(CYGetJSContext());
3355 JSValueRef exception(NULL), result;
3358 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3359 } catch (const char *error) {
3363 if (exception != NULL) { error:
3368 if (JSValueIsUndefined(context, result))
3374 json = CYPoolCCYON(pool, context, result, &exception);
3375 } catch (const char *error) {
3379 if (exception != NULL)
3382 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3386 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
3387 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
3395 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
3396 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
3404 static apr_pool_t *Pool_;
3408 const char * volatile data_;
3411 // XXX: this is "tre lame"
3412 @interface CYClient_ : NSObject {
3415 - (void) execute:(NSValue *)value;
3419 @implementation CYClient_
3421 - (void) execute:(NSValue *)value {
3422 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3423 const char *data(execute->data_);
3424 execute->data_ = NULL;
3425 execute->data_ = CYExecute(execute->pool_, data);
3434 apr_thread_t *thread_;
3436 CYClient(int socket) :
3442 _syscall(close(socket_));
3445 void Handle() { _pooled
3446 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3450 if (!CYRecvAll(socket_, &size, sizeof(size)))
3454 char *data(new(pool) char[size + 1]);
3455 if (!CYRecvAll(socket_, data, size))
3459 CYDriver driver("");
3460 cy::parser parser(driver);
3462 driver.data_ = data;
3463 driver.size_ = size;
3466 if (parser.parse() != 0 || !driver.errors_.empty()) {
3468 size = _not(size_t);
3470 std::ostringstream str;
3472 driver.program_->Multiple(out);
3473 std::string code(str.str());
3474 CYExecute_ execute = {pool, code.c_str()};
3475 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3476 json = execute.data_;
3477 size = json == NULL ? _not(size_t) : strlen(json);
3480 if (!CYSendAll(socket_, &size, sizeof(size)))
3483 if (!CYSendAll(socket_, json, size))
3489 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3490 CYClient *client(reinterpret_cast<CYClient *>(data));
3496 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3497 CYClient *client(new(pool) CYClient(socket));
3498 apr_threadattr_t *attr;
3499 _aprcall(apr_threadattr_create(&attr, client->pool_));
3500 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3503 MSInitialize { _pooled
3504 _aprcall(apr_initialize());
3505 _aprcall(apr_pool_create(&Pool_, NULL));
3507 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3508 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3510 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3512 NSArray_ = objc_getClass("NSArray");
3513 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3514 NSCFType_ = objc_getClass("NSCFType");
3515 NSDictionary_ = objc_getClass("NSDictonary");
3516 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3517 NSZombie_ = objc_getClass("_NSZombie_");
3518 Object_ = objc_getClass("Object");
3521 JSGlobalContextRef CYGetJSContext() {
3522 if (Context_ == NULL) {
3523 JSClassDefinition definition;
3525 definition = kJSClassDefinitionEmpty;
3526 definition.className = "Functor";
3527 definition.staticFunctions = Functor_staticFunctions;
3528 definition.callAsFunction = &Functor_callAsFunction;
3529 definition.finalize = &Finalize;
3530 Functor_ = JSClassCreate(&definition);
3532 definition = kJSClassDefinitionEmpty;
3533 definition.className = "Instance";
3534 definition.staticValues = Instance_staticValues;
3535 definition.staticFunctions = Instance_staticFunctions;
3536 definition.hasProperty = &Instance_hasProperty;
3537 definition.getProperty = &Instance_getProperty;
3538 definition.setProperty = &Instance_setProperty;
3539 definition.deleteProperty = &Instance_deleteProperty;
3540 definition.getPropertyNames = &Instance_getPropertyNames;
3541 definition.callAsConstructor = &Instance_callAsConstructor;
3542 definition.hasInstance = &Instance_hasInstance;
3543 definition.finalize = &Finalize;
3544 Instance_ = JSClassCreate(&definition);
3546 definition = kJSClassDefinitionEmpty;
3547 definition.className = "Internal";
3548 definition.staticFunctions = Internal_staticFunctions;
3549 definition.hasProperty = &Internal_hasProperty;
3550 definition.getProperty = &Internal_getProperty;
3551 definition.setProperty = &Internal_setProperty;
3552 definition.getPropertyNames = &Internal_getPropertyNames;
3553 definition.finalize = &Finalize;
3554 Internal_ = JSClassCreate(&definition);
3556 definition = kJSClassDefinitionEmpty;
3557 definition.className = "Message";
3558 definition.staticFunctions = Functor_staticFunctions;
3559 definition.callAsFunction = &Message_callAsFunction;
3560 definition.finalize = &Finalize;
3561 Message_ = JSClassCreate(&definition);
3563 definition = kJSClassDefinitionEmpty;
3564 definition.className = "Messages";
3565 definition.hasProperty = &Messages_hasProperty;
3566 definition.getProperty = &Messages_getProperty;
3567 definition.setProperty = &Messages_setProperty;
3569 definition.deleteProperty = &Messages_deleteProperty;
3571 definition.getPropertyNames = &Messages_getPropertyNames;
3572 definition.finalize = &Finalize;
3573 Messages_ = JSClassCreate(&definition);
3575 definition = kJSClassDefinitionEmpty;
3576 definition.className = "NSArrayPrototype";
3577 //definition.hasProperty = &NSArrayPrototype_hasProperty;
3578 //definition.getProperty = &NSArrayPrototype_getProperty;
3579 //definition.setProperty = &NSArrayPrototype_setProperty;
3580 //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
3581 //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
3582 NSArrayPrototype_ = JSClassCreate(&definition);
3584 definition = kJSClassDefinitionEmpty;
3585 definition.className = "Pointer";
3586 definition.staticValues = Pointer_staticValues;
3587 definition.staticFunctions = Pointer_staticFunctions;
3588 definition.getProperty = &Pointer_getProperty;
3589 definition.setProperty = &Pointer_setProperty;
3590 definition.finalize = &Finalize;
3591 Pointer_ = JSClassCreate(&definition);
3593 definition = kJSClassDefinitionEmpty;
3594 definition.className = "Selector";
3595 definition.staticValues = CYValue_staticValues;
3596 definition.staticFunctions = Selector_staticFunctions;
3597 definition.callAsFunction = &Selector_callAsFunction;
3598 definition.finalize = &Finalize;
3599 Selector_ = JSClassCreate(&definition);
3601 definition = kJSClassDefinitionEmpty;
3602 definition.className = "Struct";
3603 definition.staticFunctions = Struct_staticFunctions;
3604 definition.getProperty = &Struct_getProperty;
3605 definition.setProperty = &Struct_setProperty;
3606 definition.getPropertyNames = &Struct_getPropertyNames;
3607 definition.finalize = &Finalize;
3608 Struct_ = JSClassCreate(&definition);
3610 definition = kJSClassDefinitionEmpty;
3611 definition.className = "Type";
3612 definition.staticFunctions = Type_staticFunctions;
3613 definition.getProperty = &Type_getProperty;
3614 definition.callAsFunction = &Type_callAsFunction;
3615 definition.callAsConstructor = &Type_callAsConstructor;
3616 definition.finalize = &Finalize;
3617 Type_ = JSClassCreate(&definition);
3619 definition = kJSClassDefinitionEmpty;
3620 definition.className = "Runtime";
3621 definition.getProperty = &Runtime_getProperty;
3622 Runtime_ = JSClassCreate(&definition);
3624 definition = kJSClassDefinitionEmpty;
3625 definition.className = "ObjectiveC::Classes";
3626 definition.getProperty = &ObjectiveC_Classes_getProperty;
3627 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3628 ObjectiveC_Classes_ = JSClassCreate(&definition);
3630 definition = kJSClassDefinitionEmpty;
3631 definition.className = "ObjectiveC::Images";
3632 definition.getProperty = &ObjectiveC_Images_getProperty;
3633 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3634 ObjectiveC_Images_ = JSClassCreate(&definition);
3636 definition = kJSClassDefinitionEmpty;
3637 definition.className = "ObjectiveC::Image::Classes";
3638 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3639 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3640 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3642 definition = kJSClassDefinitionEmpty;
3643 definition.className = "ObjectiveC::Protocols";
3644 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3645 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3646 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3648 definition = kJSClassDefinitionEmpty;
3649 //definition.getProperty = &Global_getProperty;
3650 JSClassRef Global(JSClassCreate(&definition));
3652 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3655 JSObjectRef global(CYGetGlobalObject(context));
3657 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3658 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3659 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3661 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3662 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3663 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3665 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3666 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3667 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3669 length_ = JSStringCreateWithUTF8CString("length");
3670 message_ = JSStringCreateWithUTF8CString("message");
3671 name_ = JSStringCreateWithUTF8CString("name");
3672 prototype_ = JSStringCreateWithUTF8CString("prototype");
3673 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3674 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3676 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3677 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3679 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3680 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3681 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3682 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3684 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3685 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3686 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3687 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3689 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3691 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3692 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3693 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3694 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3696 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3697 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3698 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3699 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3700 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3702 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3704 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3706 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3707 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3708 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3710 System_ = JSObjectMake(context, NULL, NULL);
3711 CYSetProperty(context, global, CYJSString("system"), System_);
3712 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3713 //CYSetProperty(context, System_, CYJSString("global"), global);
3715 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3717 Result_ = JSStringCreateWithUTF8CString("_");
3719 JSValueProtect(context, Array_);
3720 JSValueProtect(context, Function_);
3721 JSValueProtect(context, String_);
3723 JSValueProtect(context, Instance_prototype_);
3724 JSValueProtect(context, Object_prototype_);
3726 JSValueProtect(context, Array_prototype_);
3727 JSValueProtect(context, Array_pop_);
3728 JSValueProtect(context, Array_push_);
3729 JSValueProtect(context, Array_splice_);