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 // XXX: this simply does not work on the console because I'm stupid
356 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
359 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
360 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
361 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object == nil ? nil : object_getClass(object)));
365 id GetValue() const {
366 return reinterpret_cast<id>(value_);
369 bool IsUninitialized() const {
370 return (flags_ & Uninitialized) != 0;
373 virtual Type_privateData *GetType() const;
379 Messages(Class value) :
384 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
385 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
386 if (_class == NSArray_)
388 if (Class super = class_getSuperclass(_class))
389 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
391 JSObjectSetPrototype(context, value, Array_prototype_);*/
395 Class GetValue() const {
396 return reinterpret_cast<Class>(value_);
404 JSContextRef context_;
408 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
413 JSValueProtect(context_, owner_);
417 JSValueUnprotect(context_, owner_);
420 JSObjectRef GetOwner() const {
428 Internal(id value, JSContextRef context, JSObjectRef owner) :
429 CYOwned(value, context, owner)
433 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
434 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
437 id GetValue() const {
438 return reinterpret_cast<id>(value_);
444 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
446 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
447 lhs.name = apr_pstrdup(pool, rhs.name);
448 if (rhs.type == NULL)
451 lhs.type = new(pool) Type;
452 Copy(pool, *lhs.type, *rhs.type);
454 lhs.offset = rhs.offset;
457 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
458 size_t count(rhs.count);
460 lhs.elements = new(pool) Element[count];
461 for (size_t index(0); index != count; ++index)
462 Copy(pool, lhs.elements[index], rhs.elements[index]);
465 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
466 lhs.primitive = rhs.primitive;
467 lhs.name = apr_pstrdup(pool, rhs.name);
468 lhs.flags = rhs.flags;
470 if (sig::IsAggregate(rhs.primitive))
471 Copy(pool, lhs.data.signature, rhs.data.signature);
473 sig::Type *&lht(lhs.data.data.type);
474 sig::Type *&rht(rhs.data.data.type);
479 lht = new(pool) Type;
480 Copy(pool, *lht, *rht);
483 lhs.data.data.size = rhs.data.data.size;
487 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
489 lhs.alignment = rhs.alignment;
491 if (rhs.elements == NULL)
495 while (rhs.elements[count] != NULL)
498 lhs.elements = new(pool) ffi_type *[count + 1];
499 lhs.elements[count] = NULL;
501 for (size_t index(0); index != count; ++index) {
502 // XXX: if these are libffi native then you can just take them
503 ffi_type *ffi(new(pool) ffi_type);
504 lhs.elements[index] = ffi;
505 sig::Copy(pool, *ffi, *rhs.elements[index]);
512 struct CStringMapLess :
513 std::binary_function<const char *, const char *, bool>
515 _finline bool operator ()(const char *lhs, const char *rhs) const {
516 return strcmp(lhs, rhs) < 0;
520 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
525 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
526 switch ([[entry objectAtIndex:0] intValue]) {
528 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
532 sig::Signature signature;
533 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
534 type = signature.elements[0].type;
540 struct Type_privateData :
543 static Type_privateData *Object;
544 static Type_privateData *Selector;
549 void Set(sig::Type *type) {
550 type_ = new(pool_) sig::Type;
551 sig::Copy(pool_, *type_, *type);
554 Type_privateData(apr_pool_t *pool, const char *type) :
560 sig::Signature signature;
561 sig::Parse(pool_, &signature, type, &Structor_);
562 type_ = signature.elements[0].type;
565 Type_privateData(sig::Type *type) :
572 Type_privateData(sig::Type *type, ffi_type *ffi) {
573 ffi_ = new(pool_) ffi_type;
574 sig::Copy(pool_, *ffi_, *ffi);
580 ffi_ = new(pool_) ffi_type;
582 sig::Element element;
584 element.type = type_;
587 sig::Signature signature;
588 signature.elements = &element;
592 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
600 Type_privateData *Type_privateData::Object;
601 Type_privateData *Type_privateData::Selector;
603 Type_privateData *Instance::GetType() const {
604 return Type_privateData::Object;
607 Type_privateData *Selector_privateData::GetType() const {
608 return Type_privateData::Selector;
614 Type_privateData *type_;
616 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
617 CYOwned(value, context, owner),
618 type_(new(pool_) Type_privateData(type))
623 struct Struct_privateData :
626 Type_privateData *type_;
628 Struct_privateData(JSContextRef context, JSObjectRef owner) :
629 CYOwned(NULL, context, owner)
634 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
635 static TypeMap Types_;
637 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
638 Struct_privateData *internal(new Struct_privateData(context, owner));
639 apr_pool_t *pool(internal->pool_);
640 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
641 internal->type_ = typical;
644 internal->value_ = data;
646 size_t size(typical->GetFFI()->size);
647 void *copy(apr_palloc(internal->pool_, size));
648 memcpy(copy, data, size);
649 internal->value_ = copy;
652 return JSObjectMake(context, Struct_, internal);
655 struct Functor_privateData :
658 sig::Signature signature_;
662 Functor_privateData(const char *type, void (*value)()) :
663 CYValue(reinterpret_cast<void *>(value))
665 sig::Parse(pool_, &signature_, type, &Structor_);
666 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
669 void (*GetValue())() const {
670 return reinterpret_cast<void (*)()>(value_);
674 struct Closure_privateData :
677 JSContextRef context_;
678 JSObjectRef function_;
680 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
681 Functor_privateData(type, NULL),
685 JSValueProtect(context_, function_);
688 virtual ~Closure_privateData() {
689 JSValueUnprotect(context_, function_);
693 struct Message_privateData :
698 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
699 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
705 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
706 Instance::Flags flags;
709 flags = Instance::Transient;
711 flags = Instance::None;
712 object = [object retain];
715 return Instance::Make(context, object, flags);
718 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
720 return [value UTF8String];
722 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
723 char *string(new(pool) char[size]);
724 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
725 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
730 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
731 return JSValueMakeBoolean(context, value);
734 JSValueRef CYCastJSValue(JSContextRef context, double value) {
735 return JSValueMakeNumber(context, value);
738 #define CYCastJSValue_(Type_) \
739 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
740 return JSValueMakeNumber(context, static_cast<double>(value)); \
744 CYCastJSValue_(unsigned int)
745 CYCastJSValue_(long int)
746 CYCastJSValue_(long unsigned int)
747 CYCastJSValue_(long long int)
748 CYCastJSValue_(long long unsigned int)
750 JSValueRef CYJSUndefined(JSContextRef context) {
751 return JSValueMakeUndefined(context);
754 size_t CYGetIndex(const char *value) {
755 if (value[0] != '0') {
757 size_t index(strtoul(value, &end, 10));
758 if (value + strlen(value) == end)
760 } else if (value[1] == '\0')
766 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value);
768 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
769 return CYGetIndex(CYPoolCString(pool, value));
772 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
773 return CYGetIndex(CYPoolCString(pool, value));
776 bool CYGetOffset(const char *value, ssize_t &index) {
777 if (value[0] != '0') {
779 index = strtol(value, &end, 10);
780 if (value + strlen(value) == end)
782 } else if (value[1] == '\0') {
790 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
791 return CYGetOffset(CYPoolCString(pool, value), index);
794 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
796 @interface NSMethodSignature (Cycript)
797 - (NSString *) _typeString;
800 @interface NSObject (Cycript)
802 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
803 - (JSType) cy$JSType;
805 - (NSObject *) cy$toJSON:(NSString *)key;
806 - (NSString *) cy$toCYON;
807 - (NSString *) cy$toKey;
809 - (bool) cy$hasProperty:(NSString *)name;
810 - (NSObject *) cy$getProperty:(NSString *)name;
811 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
812 - (bool) cy$deleteProperty:(NSString *)name;
817 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
820 @interface NSString (Cycript)
821 - (void *) cy$symbol;
824 struct PropertyAttributes {
829 const char *variable;
842 PropertyAttributes(objc_property_t property) :
854 name = property_getName(property);
855 const char *attributes(property_getAttributes(property));
857 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
859 case 'R': readonly = true; break;
860 case 'C': copy = true; break;
861 case '&': retain = true; break;
862 case 'N': nonatomic = true; break;
863 case 'G': getter_ = token + 1; break;
864 case 'S': setter_ = token + 1; break;
865 case 'V': variable = token + 1; break;
869 /*if (variable == NULL) {
870 variable = property_getName(property);
871 size_t size(strlen(variable));
872 char *name(new(pool_) char[size + 2]);
874 memcpy(name + 1, variable, size);
875 name[size + 1] = '\0';
880 const char *Getter() {
882 getter_ = apr_pstrdup(pool_, name);
886 const char *Setter() {
887 if (setter_ == NULL && !readonly) {
888 size_t length(strlen(name));
890 char *temp(new(pool_) char[length + 5]);
896 temp[3] = toupper(name[0]);
897 memcpy(temp + 4, name + 1, length - 1);
900 temp[length + 3] = ':';
901 temp[length + 4] = '\0';
910 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
911 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
914 /* Bridge: NSArray {{{ */
915 @implementation NSArray (Cycript)
917 - (NSString *) cy$toCYON {
918 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
919 [json appendString:@"["];
922 for (id object in self) {
924 [json appendString:@","];
927 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
928 [json appendString:CYPoolNSCYON(NULL, object)];
930 [json appendString:@","];
935 [json appendString:@"]"];
939 - (bool) cy$hasProperty:(NSString *)name {
940 if ([name isEqualToString:@"length"])
943 size_t index(CYGetIndex(NULL, name));
944 if (index == _not(size_t) || index >= [self count])
945 return [super cy$hasProperty:name];
950 - (NSObject *) cy$getProperty:(NSString *)name {
951 if ([name isEqualToString:@"length"])
952 return [NSNumber numberWithUnsignedInteger:[self count]];
954 size_t index(CYGetIndex(NULL, name));
955 if (index == _not(size_t) || index >= [self count])
956 return [super cy$getProperty:name];
958 return [self objectAtIndex:index];
963 /* Bridge: NSDictionary {{{ */
964 @implementation NSDictionary (Cycript)
966 - (NSString *) cy$toCYON {
967 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
968 [json appendString:@"{"];
971 for (id key in self) {
973 [json appendString:@","];
976 [json appendString:[key cy$toKey]];
977 [json appendString:@":"];
978 NSObject *object([self objectForKey:key]);
979 [json appendString:CYPoolNSCYON(NULL, object)];
982 [json appendString:@"}"];
986 - (bool) cy$hasProperty:(NSString *)name {
987 return [self objectForKey:name] != nil;
990 - (NSObject *) cy$getProperty:(NSString *)name {
991 return [self objectForKey:name];
996 /* Bridge: NSMutableArray {{{ */
997 @implementation NSMutableArray (Cycript)
999 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1000 if ([name isEqualToString:@"length"]) {
1001 // XXX: is this not intelligent?
1002 NSUInteger size([(NSNumber *)value unsignedIntegerValue]);
1003 NSUInteger count([self count]);
1005 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1006 else if (size != count) {
1007 WebUndefined *undefined([WebUndefined undefined]);
1008 for (size_t i(count); i != size; ++i)
1009 [self addObject:undefined];
1014 size_t index(CYGetIndex(NULL, name));
1015 if (index == _not(size_t))
1016 return [super cy$setProperty:name to:value];
1018 id object(value ?: [NSNull null]);
1020 size_t count([self count]);
1022 [self replaceObjectAtIndex:index withObject:object];
1024 if (index != count) {
1025 WebUndefined *undefined([WebUndefined undefined]);
1026 for (size_t i(count); i != index; ++i)
1027 [self addObject:undefined];
1030 [self addObject:object];
1036 - (bool) cy$deleteProperty:(NSString *)name {
1037 size_t index(CYGetIndex(NULL, name));
1038 if (index == _not(size_t) || index >= [self count])
1039 return [super cy$deleteProperty:name];
1040 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1046 /* Bridge: NSMutableDictionary {{{ */
1047 @implementation NSMutableDictionary (Cycript)
1049 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1050 [self setObject:(value ?: [NSNull null]) forKey:name];
1054 - (bool) cy$deleteProperty:(NSString *)name {
1055 if ([self objectForKey:name] == nil)
1058 [self removeObjectForKey:name];
1065 /* Bridge: NSNumber {{{ */
1066 @implementation NSNumber (Cycript)
1068 - (JSType) cy$JSType {
1069 // XXX: this just seems stupid
1070 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
1073 - (NSObject *) cy$toJSON:(NSString *)key {
1077 - (NSString *) cy$toCYON {
1078 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1081 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1082 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1087 /* Bridge: NSNull {{{ */
1088 @implementation NSNull (Cycript)
1090 - (JSType) cy$JSType {
1094 - (NSObject *) cy$toJSON:(NSString *)key {
1098 - (NSString *) cy$toCYON {
1104 /* Bridge: NSObject {{{ */
1105 @implementation NSObject (Cycript)
1107 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1108 return CYMakeInstance(context, self, false);
1111 - (JSType) cy$JSType {
1112 return kJSTypeObject;
1115 - (NSObject *) cy$toJSON:(NSString *)key {
1116 return [self description];
1119 - (NSString *) cy$toCYON {
1120 return [[self cy$toJSON:@""] cy$toCYON];
1123 - (NSString *) cy$toKey {
1124 return [self cy$toCYON];
1127 - (bool) cy$hasProperty:(NSString *)name {
1131 - (NSObject *) cy$getProperty:(NSString *)name {
1135 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1139 - (bool) cy$deleteProperty:(NSString *)name {
1145 /* Bridge: NSProxy {{{ */
1146 @implementation NSProxy (Cycript)
1148 - (NSObject *) cy$toJSON:(NSString *)key {
1149 return [self description];
1152 - (NSString *) cy$toCYON {
1153 return [[self cy$toJSON:@""] cy$toCYON];
1158 /* Bridge: NSString {{{ */
1159 @implementation NSString (Cycript)
1161 - (JSType) cy$JSType {
1162 return kJSTypeString;
1165 - (NSObject *) cy$toJSON:(NSString *)key {
1169 - (NSString *) cy$toCYON {
1170 // XXX: this should use the better code from Output.cpp
1171 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
1173 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
1174 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
1175 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
1176 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
1177 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
1179 CFStringInsert(json, 0, CFSTR("\""));
1180 CFStringAppend(json, CFSTR("\""));
1182 return [reinterpret_cast<const NSString *>(json) autorelease];
1185 - (NSString *) cy$toKey {
1186 const char *value([self UTF8String]);
1187 size_t size(strlen(value));
1192 if (DigitRange_[value[0]]) {
1193 size_t index(CYGetIndex(NULL, self));
1194 if (index == _not(size_t))
1197 if (!WordStartRange_[value[0]])
1199 for (size_t i(1); i != size; ++i)
1200 if (!WordEndRange_[value[i]])
1207 return [self cy$toCYON];
1210 - (void *) cy$symbol {
1212 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1217 /* Bridge: WebUndefined {{{ */
1218 @implementation WebUndefined (Cycript)
1220 - (JSType) cy$JSType {
1221 return kJSTypeUndefined;
1224 - (NSObject *) cy$toJSON:(NSString *)key {
1228 - (NSString *) cy$toCYON {
1229 return @"undefined";
1232 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1233 return CYJSUndefined(context);
1239 @interface CYJSObject : NSMutableDictionary {
1240 JSObjectRef object_;
1241 JSContextRef context_;
1244 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1246 - (NSString *) cy$toJSON:(NSString *)key;
1248 - (NSUInteger) count;
1249 - (id) objectForKey:(id)key;
1250 - (NSEnumerator *) keyEnumerator;
1251 - (void) setObject:(id)object forKey:(id)key;
1252 - (void) removeObjectForKey:(id)key;
1256 @interface CYJSArray : NSMutableArray {
1257 JSObjectRef object_;
1258 JSContextRef context_;
1261 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1263 - (NSUInteger) count;
1264 - (id) objectAtIndex:(NSUInteger)index;
1266 - (void) addObject:(id)anObject;
1267 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1268 - (void) removeLastObject;
1269 - (void) removeObjectAtIndex:(NSUInteger)index;
1270 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1274 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1275 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1276 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1281 @catch (id error) { \
1282 CYThrow(context, error, exception); \
1286 apr_status_t CYPoolRelease_(void *data) {
1287 id object(reinterpret_cast<id>(data));
1292 id CYPoolRelease(apr_pool_t *pool, id object) {
1295 else if (pool == NULL)
1296 return [object autorelease];
1298 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1303 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1304 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1307 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1308 JSValueRef exception(NULL);
1309 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1310 CYThrow(context, exception);
1311 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1312 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1315 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1316 if (!JSValueIsObjectOfClass(context, object, Instance_))
1317 return CYCastNSObject_(pool, context, object);
1319 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1320 return internal->GetValue();
1324 double CYCastDouble(const char *value, size_t size) {
1326 double number(strtod(value, &end));
1327 if (end != value + size)
1332 double CYCastDouble(const char *value) {
1333 return CYCastDouble(value, strlen(value));
1336 double CYCastDouble(JSContextRef context, JSValueRef value) {
1337 JSValueRef exception(NULL);
1338 double number(JSValueToNumber(context, value, &exception));
1339 CYThrow(context, exception);
1343 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1344 double number(CYCastDouble(context, value));
1345 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1348 CFStringRef CYCopyCFString(const char *value) {
1349 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1352 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1353 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1356 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1357 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1360 bool CYCastBool(JSContextRef context, JSValueRef value) {
1361 return JSValueToBoolean(context, value);
1364 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1368 switch (JSType type = JSValueGetType(context, value)) {
1369 case kJSTypeUndefined:
1370 object = [WebUndefined undefined];
1378 case kJSTypeBoolean:
1379 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1384 object = CYCopyCFNumber(context, value);
1389 object = CYCopyCFString(context, value);
1394 // XXX: this might could be more efficient
1395 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1400 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1407 return CYPoolRelease(pool, object);
1409 return CFRetain(object);
1412 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1413 return CYCFType(pool, context, value, true);
1416 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1417 return CYCFType(pool, context, value, false);
1420 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1422 size_t size(JSPropertyNameArrayGetCount(names));
1423 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1424 for (size_t index(0); index != size; ++index)
1425 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1429 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1430 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1433 void CYThrow(JSContextRef context, JSValueRef value) {
1436 @throw CYCastNSObject(NULL, context, value);
1439 JSValueRef CYJSNull(JSContextRef context) {
1440 return JSValueMakeNull(context);
1443 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1444 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1447 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1448 return CYCastJSValue(context, CYJSString(value));
1451 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1453 return CYJSNull(context);
1454 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1455 return [value cy$JSValueInContext:context];
1457 return CYMakeInstance(context, value, false);
1460 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1461 JSValueRef exception(NULL);
1462 JSObjectRef object(JSValueToObject(context, value, &exception));
1463 CYThrow(context, exception);
1467 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1468 if (exception == NULL)
1470 *exception = CYCastJSValue(context, error);
1473 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1474 JSValueRef exception(NULL);
1475 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1476 CYThrow(context, exception);
1480 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1481 // XXX: this isn't actually correct
1482 return value != NULL && JSValueIsObject(context, value);
1485 @implementation CYJSObject
1487 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1488 if ((self = [super init]) != nil) {
1491 JSValueProtect(context_, object_);
1496 JSValueUnprotect(context_, object_);
1500 - (NSObject *) cy$toJSON:(NSString *)key {
1501 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1502 if (!CYIsCallable(context_, toJSON))
1503 return [super cy$toJSON:key];
1505 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1506 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1507 // XXX: do I really want an NSNull here?!
1508 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1512 - (NSString *) cy$toCYON {
1513 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1514 if (!CYIsCallable(context_, toCYON)) super:
1515 return [super cy$toCYON];
1516 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1517 return CYCastNSString(NULL, CYJSString(context_, value));
1521 - (NSUInteger) count {
1522 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1523 size_t size(JSPropertyNameArrayGetCount(names));
1524 JSPropertyNameArrayRelease(names);
1528 - (id) objectForKey:(id)key {
1529 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1530 if (JSValueIsUndefined(context_, value))
1532 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1535 - (NSEnumerator *) keyEnumerator {
1536 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1537 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1538 JSPropertyNameArrayRelease(names);
1542 - (void) setObject:(id)object forKey:(id)key {
1543 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1546 - (void) removeObjectForKey:(id)key {
1547 JSValueRef exception(NULL);
1548 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1549 CYThrow(context_, exception);
1554 @implementation CYJSArray
1556 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1557 if ((self = [super init]) != nil) {
1560 JSValueProtect(context_, object_);
1565 JSValueUnprotect(context_, object_);
1569 - (NSUInteger) count {
1570 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1573 - (id) objectAtIndex:(NSUInteger)index {
1574 size_t bounds([self count]);
1575 if (index >= bounds)
1576 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1577 JSValueRef exception(NULL);
1578 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1579 CYThrow(context_, exception);
1580 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1583 - (void) addObject:(id)object {
1584 JSValueRef exception(NULL);
1585 JSValueRef arguments[1];
1586 arguments[0] = CYCastJSValue(context_, object);
1587 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1588 CYThrow(context_, exception);
1591 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1592 size_t bounds([self count] + 1);
1593 if (index >= bounds)
1594 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1595 JSValueRef exception(NULL);
1596 JSValueRef arguments[3];
1597 arguments[0] = CYCastJSValue(context_, index);
1598 arguments[1] = CYCastJSValue(context_, 0);
1599 arguments[2] = CYCastJSValue(context_, object);
1600 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1601 CYThrow(context_, exception);
1604 - (void) removeLastObject {
1605 JSValueRef exception(NULL);
1606 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1607 CYThrow(context_, exception);
1610 - (void) removeObjectAtIndex:(NSUInteger)index {
1611 size_t bounds([self count]);
1612 if (index >= bounds)
1613 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1614 JSValueRef exception(NULL);
1615 JSValueRef arguments[2];
1616 arguments[0] = CYCastJSValue(context_, index);
1617 arguments[1] = CYCastJSValue(context_, 1);
1618 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1619 CYThrow(context_, exception);
1622 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1623 size_t bounds([self count]);
1624 if (index >= bounds)
1625 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1626 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1631 NSString *CYCopyNSCYON(id value) {
1637 Class _class(object_getClass(value));
1638 SEL sel(@selector(cy$toCYON));
1640 if (Method toCYON = class_getInstanceMethod(_class, sel))
1641 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1642 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1643 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1644 string = [value cy$toCYON];
1647 if (value == NSZombie_)
1648 string = @"_NSZombie_";
1649 else if (_class == NSZombie_)
1650 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1651 // XXX: frowny /in/ the pants
1652 else if (value == NSMessageBuilder_ || value == Object_)
1655 string = [NSString stringWithFormat:@"%@", value];
1658 // XXX: frowny pants
1660 string = @"undefined";
1663 return [string retain];
1666 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1667 if (JSValueIsNull(context, value))
1668 return [@"null" retain];
1672 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1677 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1678 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1681 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1682 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1683 const char *string(CYPoolCString(pool, json));
1689 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1693 JSObjectRef object_;
1701 // XXX: delete object_? ;(
1704 static CYInternal *Get(id self) {
1705 CYInternal *internal(NULL);
1706 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1707 // XXX: do something epic? ;P
1713 static CYInternal *Set(id self) {
1714 CYInternal *internal(NULL);
1715 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1716 if (internal == NULL) {
1717 internal = new CYInternal();
1718 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1721 // XXX: do something epic? ;P
1727 bool HasProperty(JSContextRef context, JSStringRef name) {
1728 if (object_ == NULL)
1730 return JSObjectHasProperty(context, object_, name);
1733 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1734 if (object_ == NULL)
1736 return CYGetProperty(context, object_, name);
1739 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1740 if (object_ == NULL)
1741 object_ = JSObjectMake(context, NULL, NULL);
1742 CYSetProperty(context, object_, name, value);
1746 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1747 Selector_privateData *internal(new Selector_privateData(sel));
1748 return JSObjectMake(context, Selector_, internal);
1751 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1752 Pointer *internal(new Pointer(pointer, context, owner, type));
1753 return JSObjectMake(context, Pointer_, internal);
1756 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1757 Functor_privateData *internal(new Functor_privateData(type, function));
1758 return JSObjectMake(context, Functor_, internal);
1761 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1763 // XXX: this could be much more efficient
1764 const char *string([CYCastNSString(NULL, value) UTF8String]);
1767 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1768 char *string(new(pool) char[size]);
1769 JSStringGetUTF8CString(value, string, size);
1774 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1775 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1778 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1779 return CYGetOffset(CYPoolCString(pool, value), index);
1782 // XXX: this macro is unhygenic
1783 #define CYCastCString(context, value) ({ \
1785 if (value == NULL) \
1787 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1788 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1789 utf8 = reinterpret_cast<char *>(alloca(size)); \
1790 JSStringGetUTF8CString(string, utf8, size); \
1791 JSStringRelease(string); \
1797 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1798 switch (JSValueGetType(context, value)) {
1801 /*case kJSTypeString:
1802 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1804 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1805 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1806 return internal->value_;
1809 double number(CYCastDouble(context, value));
1810 if (std::isnan(number))
1811 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1812 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1816 template <typename Type_>
1817 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1818 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1821 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1822 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1823 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1824 return reinterpret_cast<SEL>(internal->value_);
1826 return CYCastPointer<SEL>(context, value);
1829 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1830 switch (type->primitive) {
1831 case sig::boolean_P:
1832 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1835 #define CYPoolFFI_(primitive, native) \
1836 case sig::primitive ## _P: \
1837 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1840 CYPoolFFI_(uchar, unsigned char)
1841 CYPoolFFI_(char, char)
1842 CYPoolFFI_(ushort, unsigned short)
1843 CYPoolFFI_(short, short)
1844 CYPoolFFI_(ulong, unsigned long)
1845 CYPoolFFI_(long, long)
1846 CYPoolFFI_(uint, unsigned int)
1847 CYPoolFFI_(int, int)
1848 CYPoolFFI_(ulonglong, unsigned long long)
1849 CYPoolFFI_(longlong, long long)
1850 CYPoolFFI_(float, float)
1851 CYPoolFFI_(double, double)
1854 case sig::typename_P:
1855 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1858 case sig::selector_P:
1859 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1862 case sig::pointer_P:
1863 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1867 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1870 case sig::struct_P: {
1871 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1872 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1873 for (size_t index(0); index != type->data.signature.count; ++index) {
1874 sig::Element *element(&type->data.signature.elements[index]);
1875 ffi_type *field(ffi->elements[index]);
1878 if (aggregate == NULL)
1881 rhs = CYGetProperty(context, aggregate, index);
1882 if (JSValueIsUndefined(context, rhs)) {
1883 if (element->name != NULL)
1884 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1887 if (JSValueIsUndefined(context, rhs)) undefined:
1888 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1892 CYPoolFFI(pool, context, element->type, field, base, rhs);
1894 base += field->size;
1902 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1907 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1910 switch (type->primitive) {
1911 case sig::boolean_P:
1912 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1915 #define CYFromFFI_(primitive, native) \
1916 case sig::primitive ## _P: \
1917 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1920 CYFromFFI_(uchar, unsigned char)
1921 CYFromFFI_(char, char)
1922 CYFromFFI_(ushort, unsigned short)
1923 CYFromFFI_(short, short)
1924 CYFromFFI_(ulong, unsigned long)
1925 CYFromFFI_(long, long)
1926 CYFromFFI_(uint, unsigned int)
1927 CYFromFFI_(int, int)
1928 CYFromFFI_(ulonglong, unsigned long long)
1929 CYFromFFI_(longlong, long long)
1930 CYFromFFI_(float, float)
1931 CYFromFFI_(double, double)
1933 case sig::object_P: {
1934 if (id object = *reinterpret_cast<id *>(data)) {
1935 value = CYCastJSValue(context, object);
1941 case sig::typename_P:
1942 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1945 case sig::selector_P:
1946 if (SEL sel = *reinterpret_cast<SEL *>(data))
1947 value = CYMakeSelector(context, sel);
1951 case sig::pointer_P:
1952 if (void *pointer = *reinterpret_cast<void **>(data))
1953 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1958 if (char *utf8 = *reinterpret_cast<char **>(data))
1959 value = CYCastJSValue(context, utf8);
1964 value = CYMakeStruct(context, data, type, ffi, owner);
1968 value = CYJSUndefined(context);
1972 value = CYJSNull(context);
1976 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1983 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1984 if (Method method = class_getInstanceMethod(_class, selector)) {
1988 method_getReturnType(method, type, sizeof(type));
1993 // XXX: possibly use a more "awesome" check?
1997 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
1999 return method_getTypeEncoding(method);
2000 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2001 return CYPoolCString(pool, type);
2006 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2007 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2009 JSContextRef context(internal->context_);
2011 size_t count(internal->cif_.nargs);
2012 JSValueRef values[count];
2014 for (size_t index(0); index != count; ++index)
2015 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2017 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2018 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2021 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2022 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2024 JSContextRef context(internal->context_);
2026 size_t count(internal->cif_.nargs);
2027 JSValueRef values[count];
2029 for (size_t index(0); index != count; ++index)
2030 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2032 JSObjectRef _this(CYCastJSObject(context, values[0]));
2034 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2035 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2038 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2039 // XXX: in case of exceptions this will leak
2040 // XXX: in point of fact, this may /need/ to leak :(
2041 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2043 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2044 NULL, sizeof(ffi_closure),
2045 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2049 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2050 _assert(status == FFI_OK);
2052 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2054 internal->value_ = closure;
2059 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2060 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2061 return JSObjectMake(context, Functor_, internal);
2064 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2065 JSValueRef exception(NULL);
2066 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2067 CYThrow(context, exception);
2070 JSObjectRef function(CYCastJSObject(context, value));
2071 return CYMakeFunctor(context, function, type);
2073 void (*function)()(CYCastPointer<void (*)()>(context, value));
2074 return CYMakeFunctor(context, function, type);
2078 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2079 Message_privateData *internal(new Message_privateData(sel, type, imp));
2080 return JSObjectMake(context, Message_, internal);
2083 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2084 JSObjectRef function(CYCastJSObject(context, value));
2085 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2086 return reinterpret_cast<IMP>(internal->GetValue());
2089 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2090 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2091 Class _class(internal->GetValue());
2094 const char *name(CYPoolCString(pool, property));
2096 if (SEL sel = sel_getUid(name))
2097 if (class_getInstanceMethod(_class, sel) != NULL)
2103 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2104 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2105 Class _class(internal->GetValue());
2108 const char *name(CYPoolCString(pool, property));
2110 if (SEL sel = sel_getUid(name))
2111 if (Method method = class_getInstanceMethod(_class, sel))
2112 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2117 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2118 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2119 Class _class(internal->GetValue());
2122 const char *name(CYPoolCString(pool, property));
2124 SEL sel(sel_registerName(name));
2126 Method method(class_getInstanceMethod(_class, sel));
2131 if (JSValueIsObjectOfClass(context, value, Message_)) {
2132 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2133 type = sig::Unparse(pool, &message->signature_);
2134 imp = reinterpret_cast<IMP>(message->GetValue());
2136 type = CYPoolTypeEncoding(pool, _class, sel, method);
2137 imp = CYMakeMessage(context, value, type);
2141 method_setImplementation(method, imp);
2143 class_replaceMethod(_class, sel, imp, type);
2149 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2150 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2151 Class _class(internal->GetValue());
2154 const char *name(CYPoolCString(pool, property));
2156 if (SEL sel = sel_getUid(name))
2157 if (Method method = class_getInstanceMethod(_class, sel)) {
2158 objc_method_list list = {NULL, 1, {method}};
2159 class_removeMethods(_class, &list);
2167 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2168 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2169 Class _class(internal->GetValue());
2172 Method *data(class_copyMethodList(_class, &size));
2173 for (size_t i(0); i != size; ++i)
2174 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2178 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2179 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2180 id self(internal->GetValue());
2182 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2186 NSString *name(CYCastNSString(pool, property));
2188 if (CYInternal *internal = CYInternal::Get(self))
2189 if (internal->HasProperty(context, property))
2192 Class _class(object_getClass(self));
2195 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2196 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2197 if ([self cy$hasProperty:name])
2199 } CYPoolCatch(false)
2201 const char *string(CYPoolCString(pool, name));
2203 if (class_getProperty(_class, string) != NULL)
2206 if (SEL sel = sel_getUid(string))
2207 if (CYImplements(self, _class, sel, true))
2213 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2214 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2215 id self(internal->GetValue());
2217 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2218 return Internal::Make(context, self, object);
2222 NSString *name(CYCastNSString(pool, property));
2224 if (CYInternal *internal = CYInternal::Get(self))
2225 if (JSValueRef value = internal->GetProperty(context, property))
2229 if (NSObject *data = [self cy$getProperty:name])
2230 return CYCastJSValue(context, data);
2233 const char *string(CYPoolCString(pool, name));
2234 Class _class(object_getClass(self));
2236 if (objc_property_t property = class_getProperty(_class, string)) {
2237 PropertyAttributes attributes(property);
2238 SEL sel(sel_registerName(attributes.Getter()));
2239 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2242 if (SEL sel = sel_getUid(string))
2243 if (CYImplements(self, _class, sel, true))
2244 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2250 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2251 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2252 id self(internal->GetValue());
2257 NSString *name(CYCastNSString(pool, property));
2258 NSString *data(CYCastNSObject(pool, context, value));
2261 if ([self cy$setProperty:name to:data])
2265 const char *string(CYPoolCString(pool, name));
2266 Class _class(object_getClass(self));
2268 if (objc_property_t property = class_getProperty(_class, string)) {
2269 PropertyAttributes attributes(property);
2270 if (const char *setter = attributes.Setter()) {
2271 SEL sel(sel_registerName(setter));
2272 JSValueRef arguments[1] = {value};
2273 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2278 size_t length(strlen(string));
2280 char set[length + 5];
2286 if (string[0] != '\0') {
2287 set[3] = toupper(string[0]);
2288 memcpy(set + 4, string + 1, length - 1);
2291 set[length + 3] = ':';
2292 set[length + 4] = '\0';
2294 if (SEL sel = sel_getUid(set))
2295 if (CYImplements(self, _class, sel, false)) {
2296 JSValueRef arguments[1] = {value};
2297 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2300 if (CYInternal *internal = CYInternal::Set(self)) {
2301 internal->SetProperty(context, property, value);
2309 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2310 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2311 id self(internal->GetValue());
2315 NSString *name(CYCastNSString(NULL, property));
2316 return [self cy$deleteProperty:name];
2321 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2322 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2323 id self(internal->GetValue());
2326 Class _class(object_getClass(self));
2330 objc_property_t *data(class_copyPropertyList(_class, &size));
2331 for (size_t i(0); i != size; ++i)
2332 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2337 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2339 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2340 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2345 static bool CYIsClass(id self) {
2346 // XXX: this is a lame object_isClass
2347 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2350 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2351 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2352 Class _class(internal->GetValue());
2353 if (!CYIsClass(_class))
2356 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2357 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2358 // XXX: this isn't always safe
2360 return [linternal->GetValue() isKindOfClass:_class];
2367 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2368 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2371 id self(internal->GetValue());
2372 const char *name(CYPoolCString(pool, property));
2374 if (object_getInstanceVariable(self, name, NULL) != NULL)
2380 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2381 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2385 id self(internal->GetValue());
2386 const char *name(CYPoolCString(pool, property));
2388 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2389 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2390 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2397 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2398 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2402 id self(internal->GetValue());
2403 const char *name(CYPoolCString(pool, property));
2405 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2406 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2407 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2415 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2416 if (Class super = class_getSuperclass(_class))
2417 Internal_getPropertyNames_(super, names);
2420 Ivar *data(class_copyIvarList(_class, &size));
2421 for (size_t i(0); i != size; ++i)
2422 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2426 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2427 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2430 id self(internal->GetValue());
2431 Class _class(object_getClass(self));
2433 Internal_getPropertyNames_(_class, names);
2436 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2437 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2438 return internal->GetOwner();
2441 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2442 Type_privateData *typical(internal->type_);
2443 sig::Type *type(typical->type_);
2447 const char *name(CYPoolCString(pool, property));
2448 size_t length(strlen(name));
2449 double number(CYCastDouble(name, length));
2451 size_t count(type->data.signature.count);
2453 if (std::isnan(number)) {
2454 if (property == NULL)
2457 sig::Element *elements(type->data.signature.elements);
2459 for (size_t local(0); local != count; ++local) {
2460 sig::Element *element(&elements[local]);
2461 if (element->name != NULL && strcmp(name, element->name) == 0) {
2469 index = static_cast<ssize_t>(number);
2470 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2475 ffi_type **elements(typical->GetFFI()->elements);
2477 base = reinterpret_cast<uint8_t *>(internal->value_);
2478 for (ssize_t local(0); local != index; ++local)
2479 base += elements[local]->size;
2484 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2485 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2486 Type_privateData *typical(internal->type_);
2488 ffi_type *ffi(typical->GetFFI());
2490 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2491 base += ffi->size * index;
2493 JSObjectRef owner(internal->GetOwner() ?: object);
2496 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2500 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2502 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2503 Type_privateData *typical(internal->type_);
2505 if (typical->type_ == NULL)
2509 if (!CYGetOffset(pool, property, offset))
2512 return Pointer_getIndex(context, object, offset, exception);
2515 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2516 return Pointer_getIndex(context, object, 0, exception);
2519 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2520 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2521 Type_privateData *typical(internal->type_);
2523 ffi_type *ffi(typical->GetFFI());
2525 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2526 base += ffi->size * index;
2529 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2534 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2536 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2537 Type_privateData *typical(internal->type_);
2539 if (typical->type_ == NULL)
2543 if (!CYGetOffset(pool, property, offset))
2546 return Pointer_setIndex(context, object, offset, value, exception);
2549 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2550 return Pointer_setIndex(context, object, 0, value, exception);
2553 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2554 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2555 Type_privateData *typical(internal->type_);
2556 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2559 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2561 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2562 Type_privateData *typical(internal->type_);
2567 if (!Index_(pool, internal, property, index, base))
2570 JSObjectRef owner(internal->GetOwner() ?: object);
2573 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2577 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2579 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2580 Type_privateData *typical(internal->type_);
2585 if (!Index_(pool, internal, property, index, base))
2589 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2594 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2595 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2596 Type_privateData *typical(internal->type_);
2597 sig::Type *type(typical->type_);
2602 size_t count(type->data.signature.count);
2603 sig::Element *elements(type->data.signature.elements);
2607 for (size_t index(0); index != count; ++index) {
2609 name = elements[index].name;
2612 sprintf(number, "%lu", index);
2616 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2620 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)()) {
2622 if (setups + count != signature->count - 1)
2623 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2625 size_t size(setups + count);
2627 memcpy(values, setup, sizeof(void *) * setups);
2629 for (size_t index(setups); index != size; ++index) {
2630 sig::Element *element(&signature->elements[index + 1]);
2631 ffi_type *ffi(cif->arg_types[index]);
2633 values[index] = new(pool) uint8_t[ffi->size];
2634 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2637 uint8_t value[cif->rtype->size];
2638 ffi_call(cif, function, value, values);
2640 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2644 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2647 NSString *name(CYCastNSString(pool, property));
2648 if (Class _class = NSClassFromString(name))
2649 return CYMakeInstance(context, _class, true);
2654 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2655 size_t size(objc_getClassList(NULL, 0));
2656 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2659 size_t writ(objc_getClassList(data, size));
2662 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2668 for (size_t i(0); i != writ; ++i)
2669 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2675 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2676 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2680 const char *name(CYPoolCString(pool, property));
2682 const char **data(objc_copyClassNamesForImage(internal, &size));
2684 for (size_t i(0); i != size; ++i)
2685 if (strcmp(name, data[i]) == 0) {
2686 if (Class _class = objc_getClass(name)) {
2687 value = CYMakeInstance(context, _class, true);
2699 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2700 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2702 const char **data(objc_copyClassNamesForImage(internal, &size));
2703 for (size_t i(0); i != size; ++i)
2704 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2708 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2711 const char *name(CYPoolCString(pool, property));
2713 const char **data(objc_copyImageNames(&size));
2714 for (size_t i(0); i != size; ++i)
2715 if (strcmp(name, data[i]) == 0) {
2724 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2725 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2730 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2732 const char **data(objc_copyImageNames(&size));
2733 for (size_t i(0); i != size; ++i)
2734 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2738 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2741 NSString *name(CYCastNSString(pool, property));
2742 if (Protocol *protocol = NSProtocolFromString(name))
2743 return CYMakeInstance(context, protocol, true);
2748 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2750 Protocol **data(objc_copyProtocolList(&size));
2751 for (size_t i(0); i != size; ++i)
2752 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2756 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
2757 Type_privateData *internal(new Type_privateData(NULL, type));
2758 return JSObjectMake(context, Type_, internal);
2761 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
2762 Type_privateData *internal(new Type_privateData(type));
2763 return JSObjectMake(context, Type_, internal);
2766 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2767 if (JSStringIsEqualToUTF8CString(property, "nil"))
2768 return Instance::Make(context, nil);
2772 NSString *name(CYCastNSString(pool, property));
2773 if (Class _class = NSClassFromString(name))
2774 return CYMakeInstance(context, _class, true);
2775 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2776 switch ([[entry objectAtIndex:0] intValue]) {
2778 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2780 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2782 // XXX: this is horrendously inefficient
2783 sig::Signature signature;
2784 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2786 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2787 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2789 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
2790 switch ([[entry objectAtIndex:0] intValue]) {
2791 // XXX: implement case 0
2793 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
2799 static bool stret(ffi_type *ffi_type) {
2800 return ffi_type->type == FFI_TYPE_STRUCT && (
2801 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2802 struct_forward_array[ffi_type->size] != 0
2807 int *_NSGetArgc(void);
2808 char ***_NSGetArgv(void);
2811 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2816 NSLog(@"%s", CYCastCString(context, arguments[0]));
2817 return CYJSUndefined(context);
2821 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2824 Class _class(object_getClass(self));
2825 if (Method method = class_getInstanceMethod(_class, _cmd))
2826 type = method_getTypeEncoding(method);
2830 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2832 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2833 type = CYPoolCString(pool, [method _typeString]);
2842 sig::Signature signature;
2843 sig::Parse(pool, &signature, type, &Structor_);
2846 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2848 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2849 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2852 static size_t Nonce_(0);
2854 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2856 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
2857 return CYCastJSValue(context, name);
2860 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2870 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2872 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2873 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2874 self = internal->GetValue();
2875 uninitialized = internal->IsUninitialized();
2877 internal->value_ = nil;
2879 self = CYCastNSObject(pool, context, arguments[0]);
2880 uninitialized = false;
2884 return CYJSNull(context);
2886 _cmd = CYCastSEL(context, arguments[1]);
2889 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2892 /* Hook: objc_registerClassPair {{{ */
2893 // XXX: replace this with associated objects
2895 MSHook(void, CYDealloc, id self, SEL sel) {
2896 CYInternal *internal;
2897 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2898 if (internal != NULL)
2900 _CYDealloc(self, sel);
2903 MSHook(void, objc_registerClassPair, Class _class) {
2904 Class super(class_getSuperclass(_class));
2905 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2906 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2907 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2910 _objc_registerClassPair(_class);
2913 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2916 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2918 Class _class(CYCastNSObject(pool, context, arguments[0]));
2919 $objc_registerClassPair(_class);
2920 return CYJSUndefined(context);
2925 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2926 JSGarbageCollect(context);
2927 return CYJSUndefined(context);
2930 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2931 JSValueRef setup[count + 2];
2934 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2935 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2938 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2940 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2942 // XXX: handle Instance::Uninitialized?
2943 id self(CYCastNSObject(pool, context, _this));
2947 setup[1] = &internal->sel_;
2949 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2952 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2954 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2955 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2958 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2961 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2962 const char *name(CYCastCString(context, arguments[0]));
2963 return CYMakeSelector(context, sel_registerName(name));
2967 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2970 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2972 void *value(CYCastPointer<void *>(context, arguments[0]));
2973 const char *type(CYCastCString(context, arguments[1]));
2977 sig::Signature signature;
2978 sig::Parse(pool, &signature, type, &Structor_);
2980 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2984 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2987 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2988 const char *type(CYCastCString(context, arguments[0]));
2989 return CYMakeType(context, type);
2993 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2994 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2999 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3000 type.primitive = sig::pointer_P;
3001 type.data.data.size = 0;
3003 size_t index(CYGetIndex(NULL, property));
3004 if (index == _not(size_t))
3006 type.primitive = sig::array_P;
3007 type.data.data.size = index;
3013 type.data.data.type = internal->type_;
3015 return CYMakeType(context, &type);
3019 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3020 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3024 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3025 sig::Type *type(internal->type_);
3026 ffi_type *ffi(internal->GetFFI());
3028 uint8_t value[ffi->size];
3030 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3031 return CYFromFFI(context, type, ffi, value);
3035 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3038 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3039 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3041 sig::Type *type(internal->type_);
3044 if (type->primitive != sig::array_P)
3047 size = type->data.data.size;
3048 type = type->data.data.type;
3051 void *value(malloc(internal->GetFFI()->size));
3052 return CYMakePointer(context, value, type, NULL, NULL);
3056 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3059 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
3060 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3061 return Instance::Make(context, self);
3065 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3068 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
3069 const char *type(CYCastCString(context, arguments[1]));
3070 return CYMakeFunctor(context, arguments[0], type);
3074 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3075 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3076 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3079 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3080 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3081 Type_privateData *typical(internal->GetType());
3086 if (typical == NULL) {
3090 type = typical->type_;
3091 ffi = typical->ffi_;
3094 return CYMakePointer(context, &internal->value_, type, ffi, object);
3097 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3098 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3101 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3105 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3106 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3109 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3110 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3112 sprintf(string, "%p", internal->value_);
3115 return CYCastJSValue(context, string);
3119 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3120 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3121 return Instance::Make(context, object_getClass(internal->GetValue()));
3124 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3125 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3126 id self(internal->GetValue());
3127 if (!CYIsClass(self))
3128 return CYJSUndefined(context);
3130 return CYGetClassPrototype(context, self);
3134 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3135 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3136 id self(internal->GetValue());
3137 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3138 return CYJSUndefined(context);
3139 return Messages::Make(context, self);
3142 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3143 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3146 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3150 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
3155 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3156 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3159 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3163 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3164 // XXX: check for support of cy$toJSON?
3165 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3170 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3171 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3174 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3178 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3183 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3184 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3187 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3191 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3192 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3195 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3196 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3197 const char *name(sel_getName(internal->GetValue()));
3201 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3206 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3209 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
3211 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3212 Class _class(CYCastNSObject(pool, context, arguments[0]));
3213 SEL sel(internal->GetValue());
3214 Method method(class_getInstanceMethod(_class, sel));
3215 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3216 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3220 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3222 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3224 const char *type(sig::Unparse(pool, internal->type_));
3226 return CYCastJSValue(context, CYJSString(type));
3231 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3233 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3235 const char *type(sig::Unparse(pool, internal->type_));
3237 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
3242 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3243 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3246 static JSStaticValue CYValue_staticValues[2] = {
3247 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3248 {NULL, NULL, NULL, 0}
3251 static JSStaticValue Pointer_staticValues[2] = {
3252 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3253 {NULL, NULL, NULL, 0}
3256 static JSStaticFunction Pointer_staticFunctions[4] = {
3257 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3258 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3259 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3263 static JSStaticFunction Struct_staticFunctions[2] = {
3264 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3268 static JSStaticFunction Functor_staticFunctions[4] = {
3269 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3270 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3271 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3275 static JSStaticValue Instance_staticValues[5] = {
3276 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3277 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3278 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3279 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3280 {NULL, NULL, NULL, 0}
3283 static JSStaticFunction Instance_staticFunctions[5] = {
3284 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3285 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3286 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3287 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3291 static JSStaticFunction Internal_staticFunctions[2] = {
3292 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3296 static JSStaticFunction Selector_staticFunctions[5] = {
3297 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3298 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3299 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3300 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3304 static JSStaticFunction Type_staticFunctions[4] = {
3305 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3306 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3307 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3311 CYDriver::CYDriver(const std::string &filename) :
3317 filename_(filename),
3323 CYDriver::~CYDriver() {
3327 void CYDriver::Warning(const cy::location &location, const char *message) {
3331 CYDriver::Error error;
3332 error.warning_ = true;
3333 error.location_ = location;
3334 error.message_ = message;
3335 errors_.push_back(error);
3338 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
3339 CYDriver::Error error;
3340 error.warning_ = false;
3341 error.location_ = location;
3342 error.message_ = message;
3343 driver.errors_.push_back(error);
3346 void CYSetArgs(int argc, const char *argv[]) {
3347 JSContextRef context(CYGetJSContext());
3348 JSValueRef args[argc];
3349 for (int i(0); i != argc; ++i)
3350 args[i] = CYCastJSValue(context, argv[i]);
3351 JSValueRef exception(NULL);
3352 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3353 CYThrow(context, exception);
3354 CYSetProperty(context, System_, CYJSString("args"), array);
3357 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3358 return JSContextGetGlobalObject(context);
3361 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3362 JSContextRef context(CYGetJSContext());
3363 JSValueRef exception(NULL), result;
3366 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3367 } catch (const char *error) {
3371 if (exception != NULL) { error:
3376 if (JSValueIsUndefined(context, result))
3382 json = CYPoolCCYON(pool, context, result, &exception);
3383 } catch (const char *error) {
3387 if (exception != NULL)
3390 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3394 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
3395 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
3403 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
3404 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
3412 static apr_pool_t *Pool_;
3416 const char * volatile data_;
3419 // XXX: this is "tre lame"
3420 @interface CYClient_ : NSObject {
3423 - (void) execute:(NSValue *)value;
3427 @implementation CYClient_
3429 - (void) execute:(NSValue *)value {
3430 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3431 const char *data(execute->data_);
3432 execute->data_ = NULL;
3433 execute->data_ = CYExecute(execute->pool_, data);
3442 apr_thread_t *thread_;
3444 CYClient(int socket) :
3450 _syscall(close(socket_));
3453 void Handle() { _pooled
3454 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3458 if (!CYRecvAll(socket_, &size, sizeof(size)))
3462 char *data(new(pool) char[size + 1]);
3463 if (!CYRecvAll(socket_, data, size))
3467 CYDriver driver("");
3468 cy::parser parser(driver);
3470 driver.data_ = data;
3471 driver.size_ = size;
3474 if (parser.parse() != 0 || !driver.errors_.empty()) {
3476 size = _not(size_t);
3478 std::ostringstream str;
3480 driver.program_->Multiple(out);
3481 std::string code(str.str());
3482 CYExecute_ execute = {pool, code.c_str()};
3483 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3484 json = execute.data_;
3485 size = json == NULL ? _not(size_t) : strlen(json);
3488 if (!CYSendAll(socket_, &size, sizeof(size)))
3491 if (!CYSendAll(socket_, json, size))
3497 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3498 CYClient *client(reinterpret_cast<CYClient *>(data));
3504 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3505 CYClient *client(new(pool) CYClient(socket));
3506 apr_threadattr_t *attr;
3507 _aprcall(apr_threadattr_create(&attr, client->pool_));
3508 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3511 MSInitialize { _pooled
3512 _aprcall(apr_initialize());
3513 _aprcall(apr_pool_create(&Pool_, NULL));
3515 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3516 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3518 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3520 NSArray_ = objc_getClass("NSArray");
3521 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3522 NSCFType_ = objc_getClass("NSCFType");
3523 NSDictionary_ = objc_getClass("NSDictonary");
3524 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3525 NSZombie_ = objc_getClass("_NSZombie_");
3526 Object_ = objc_getClass("Object");
3529 JSGlobalContextRef CYGetJSContext() {
3530 if (Context_ == NULL) {
3531 JSClassDefinition definition;
3533 definition = kJSClassDefinitionEmpty;
3534 definition.className = "Functor";
3535 definition.staticFunctions = Functor_staticFunctions;
3536 definition.callAsFunction = &Functor_callAsFunction;
3537 definition.finalize = &Finalize;
3538 Functor_ = JSClassCreate(&definition);
3540 definition = kJSClassDefinitionEmpty;
3541 definition.className = "Instance";
3542 definition.staticValues = Instance_staticValues;
3543 definition.staticFunctions = Instance_staticFunctions;
3544 definition.hasProperty = &Instance_hasProperty;
3545 definition.getProperty = &Instance_getProperty;
3546 definition.setProperty = &Instance_setProperty;
3547 definition.deleteProperty = &Instance_deleteProperty;
3548 definition.getPropertyNames = &Instance_getPropertyNames;
3549 definition.callAsConstructor = &Instance_callAsConstructor;
3550 definition.hasInstance = &Instance_hasInstance;
3551 definition.finalize = &Finalize;
3552 Instance_ = JSClassCreate(&definition);
3554 definition = kJSClassDefinitionEmpty;
3555 definition.className = "Internal";
3556 definition.staticFunctions = Internal_staticFunctions;
3557 definition.hasProperty = &Internal_hasProperty;
3558 definition.getProperty = &Internal_getProperty;
3559 definition.setProperty = &Internal_setProperty;
3560 definition.getPropertyNames = &Internal_getPropertyNames;
3561 definition.finalize = &Finalize;
3562 Internal_ = JSClassCreate(&definition);
3564 definition = kJSClassDefinitionEmpty;
3565 definition.className = "Message";
3566 definition.staticFunctions = Functor_staticFunctions;
3567 definition.callAsFunction = &Message_callAsFunction;
3568 definition.finalize = &Finalize;
3569 Message_ = JSClassCreate(&definition);
3571 definition = kJSClassDefinitionEmpty;
3572 definition.className = "Messages";
3573 definition.hasProperty = &Messages_hasProperty;
3574 definition.getProperty = &Messages_getProperty;
3575 definition.setProperty = &Messages_setProperty;
3577 definition.deleteProperty = &Messages_deleteProperty;
3579 definition.getPropertyNames = &Messages_getPropertyNames;
3580 definition.finalize = &Finalize;
3581 Messages_ = JSClassCreate(&definition);
3583 definition = kJSClassDefinitionEmpty;
3584 definition.className = "NSArrayPrototype";
3585 //definition.hasProperty = &NSArrayPrototype_hasProperty;
3586 //definition.getProperty = &NSArrayPrototype_getProperty;
3587 //definition.setProperty = &NSArrayPrototype_setProperty;
3588 //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
3589 //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
3590 NSArrayPrototype_ = JSClassCreate(&definition);
3592 definition = kJSClassDefinitionEmpty;
3593 definition.className = "Pointer";
3594 definition.staticValues = Pointer_staticValues;
3595 definition.staticFunctions = Pointer_staticFunctions;
3596 definition.getProperty = &Pointer_getProperty;
3597 definition.setProperty = &Pointer_setProperty;
3598 definition.finalize = &Finalize;
3599 Pointer_ = JSClassCreate(&definition);
3601 definition = kJSClassDefinitionEmpty;
3602 definition.className = "Selector";
3603 definition.staticValues = CYValue_staticValues;
3604 definition.staticFunctions = Selector_staticFunctions;
3605 definition.callAsFunction = &Selector_callAsFunction;
3606 definition.finalize = &Finalize;
3607 Selector_ = JSClassCreate(&definition);
3609 definition = kJSClassDefinitionEmpty;
3610 definition.className = "Struct";
3611 definition.staticFunctions = Struct_staticFunctions;
3612 definition.getProperty = &Struct_getProperty;
3613 definition.setProperty = &Struct_setProperty;
3614 definition.getPropertyNames = &Struct_getPropertyNames;
3615 definition.finalize = &Finalize;
3616 Struct_ = JSClassCreate(&definition);
3618 definition = kJSClassDefinitionEmpty;
3619 definition.className = "Type";
3620 definition.staticFunctions = Type_staticFunctions;
3621 definition.getProperty = &Type_getProperty;
3622 definition.callAsFunction = &Type_callAsFunction;
3623 definition.callAsConstructor = &Type_callAsConstructor;
3624 definition.finalize = &Finalize;
3625 Type_ = JSClassCreate(&definition);
3627 definition = kJSClassDefinitionEmpty;
3628 definition.className = "Runtime";
3629 definition.getProperty = &Runtime_getProperty;
3630 Runtime_ = JSClassCreate(&definition);
3632 definition = kJSClassDefinitionEmpty;
3633 definition.className = "ObjectiveC::Classes";
3634 definition.getProperty = &ObjectiveC_Classes_getProperty;
3635 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3636 ObjectiveC_Classes_ = JSClassCreate(&definition);
3638 definition = kJSClassDefinitionEmpty;
3639 definition.className = "ObjectiveC::Images";
3640 definition.getProperty = &ObjectiveC_Images_getProperty;
3641 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3642 ObjectiveC_Images_ = JSClassCreate(&definition);
3644 definition = kJSClassDefinitionEmpty;
3645 definition.className = "ObjectiveC::Image::Classes";
3646 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3647 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3648 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3650 definition = kJSClassDefinitionEmpty;
3651 definition.className = "ObjectiveC::Protocols";
3652 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3653 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3654 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3656 definition = kJSClassDefinitionEmpty;
3657 //definition.getProperty = &Global_getProperty;
3658 JSClassRef Global(JSClassCreate(&definition));
3660 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3663 JSObjectRef global(CYGetGlobalObject(context));
3665 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3666 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3667 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3669 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3670 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3671 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3673 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3674 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3675 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3677 length_ = JSStringCreateWithUTF8CString("length");
3678 message_ = JSStringCreateWithUTF8CString("message");
3679 name_ = JSStringCreateWithUTF8CString("name");
3680 prototype_ = JSStringCreateWithUTF8CString("prototype");
3681 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3682 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3684 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3685 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3687 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3688 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3689 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3690 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3692 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3693 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3694 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3695 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3697 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3699 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3700 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3701 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3702 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3704 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3705 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3706 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3707 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3708 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3710 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3712 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3714 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
3715 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
3716 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
3718 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3719 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3720 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3722 System_ = JSObjectMake(context, NULL, NULL);
3723 CYSetProperty(context, global, CYJSString("system"), System_);
3724 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3725 //CYSetProperty(context, System_, CYJSString("global"), global);
3727 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3729 Result_ = JSStringCreateWithUTF8CString("_");
3731 JSValueProtect(context, Array_);
3732 JSValueProtect(context, Function_);
3733 JSValueProtect(context, String_);
3735 JSValueProtect(context, Instance_prototype_);
3736 JSValueProtect(context, Object_prototype_);
3738 JSValueProtect(context, Array_prototype_);
3739 JSValueProtect(context, Array_pop_);
3740 JSValueProtect(context, Array_push_);
3741 JSValueProtect(context, Array_splice_);