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 <JavaScriptCore/JSStringRefCF.h>
55 #include <WebKit/WebScriptObject.h>
60 #include <ext/stdio_filebuf.h>
68 #include "Cycript.tab.hh"
70 #include <apr_thread_proc.h>
75 #define _assert(test) do { \
77 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
80 #define _trace() do { \
81 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
86 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
88 #define CYPoolCatch(value) \
89 @catch (NSException *error) { \
90 _saved = [error retain]; \
96 [_saved autorelease]; \
100 void CYThrow(JSContextRef context, JSValueRef value);
102 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception);
103 JSStringRef CYCopyJSString(const char *value);
105 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value);
107 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)());
108 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
110 /* JavaScript Properties {{{ */
111 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
112 JSValueRef exception(NULL);
113 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
114 CYThrow(context, exception);
118 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
119 JSValueRef exception(NULL);
120 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
121 CYThrow(context, exception);
125 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
126 JSValueRef exception(NULL);
127 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
128 CYThrow(context, exception);
131 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
132 JSValueRef exception(NULL);
133 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
134 CYThrow(context, exception);
137 /* JavaScript Strings {{{ */
138 JSStringRef CYCopyJSString(id value) {
139 // XXX: this definition scares me; is anyone using this?!
140 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
143 JSStringRef CYCopyJSString(const char *value) {
144 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
147 JSStringRef CYCopyJSString(JSStringRef value) {
148 return value == NULL ? NULL : JSStringRetain(value);
151 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
152 if (JSValueIsNull(context, value))
154 JSValueRef exception(NULL);
155 JSStringRef string(JSValueToStringCopy(context, value, &exception));
156 CYThrow(context, exception);
166 JSStringRelease(string_);
170 CYJSString(const CYJSString &rhs) :
171 string_(CYCopyJSString(rhs.string_))
175 template <typename Arg0_>
176 CYJSString(Arg0_ arg0) :
177 string_(CYCopyJSString(arg0))
181 template <typename Arg0_, typename Arg1_>
182 CYJSString(Arg0_ arg0, Arg1_ arg1) :
183 string_(CYCopyJSString(arg0, arg1))
187 CYJSString &operator =(const CYJSString &rhs) {
189 string_ = CYCopyJSString(rhs.string_);
202 operator JSStringRef() const {
207 CFStringRef CYCopyCFString(JSStringRef value) {
208 return JSStringCopyCFString(kCFAllocatorDefault, value);
211 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
212 return CYCopyCFString(CYJSString(context, value));
217 static JSGlobalContextRef Context_;
218 static JSObjectRef System_;
219 static JSObjectRef ObjectiveC_;
221 static JSClassRef Functor_;
222 static JSClassRef Instance_;
223 static JSClassRef Internal_;
224 static JSClassRef Message_;
225 static JSClassRef Messages_;
226 static JSClassRef NSArrayPrototype_;
227 static JSClassRef Pointer_;
228 static JSClassRef Runtime_;
229 static JSClassRef Selector_;
230 static JSClassRef Struct_;
231 static JSClassRef Type_;
233 static JSClassRef ObjectiveC_Classes_;
234 static JSClassRef ObjectiveC_Image_Classes_;
235 static JSClassRef ObjectiveC_Images_;
236 static JSClassRef ObjectiveC_Protocols_;
238 static JSObjectRef Array_;
239 static JSObjectRef Function_;
240 static JSObjectRef String_;
242 static JSStringRef Result_;
244 static JSStringRef length_;
245 static JSStringRef message_;
246 static JSStringRef name_;
247 static JSStringRef prototype_;
248 static JSStringRef toCYON_;
249 static JSStringRef toJSON_;
251 static JSObjectRef Instance_prototype_;
252 static JSObjectRef Object_prototype_;
254 static JSObjectRef Array_prototype_;
255 static JSObjectRef Array_pop_;
256 static JSObjectRef Array_push_;
257 static JSObjectRef Array_splice_;
259 static Class NSArray_;
260 static Class NSCFBoolean_;
261 static Class NSCFType_;
262 static Class NSDictionary_;
263 static Class NSMessageBuilder_;
264 static Class NSZombie_;
265 static Class Object_;
267 static NSArray *Bridge_;
269 static void Finalize(JSObjectRef object) {
270 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
273 class Type_privateData;
283 CYValue(void *value) :
288 CYValue(const CYValue &rhs) :
293 virtual Type_privateData *GetType() const {
298 struct Selector_privateData :
301 Selector_privateData(SEL value) :
306 SEL GetValue() const {
307 return reinterpret_cast<SEL>(value_);
310 virtual Type_privateData *GetType() const;
313 // XXX: trick this out with associated objects!
314 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
316 return Instance_prototype_;
318 // XXX: I need to think through multi-context
319 typedef std::map<Class, JSValueRef> CacheMap;
320 static CacheMap cache_;
322 JSValueRef &value(cache_[self]);
326 JSClassRef _class(NULL);
327 JSValueRef prototype;
329 if (self == NSArray_)
330 prototype = Array_prototype_;
331 else if (self == NSDictionary_)
332 prototype = Object_prototype_;
334 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
336 JSObjectRef object(JSObjectMake(context, _class, NULL));
337 JSObjectSetPrototype(context, object, prototype);
339 JSValueProtect(context, object);
349 Transient = (1 << 0),
350 Uninitialized = (1 << 1),
355 Instance(id value, Flags flags) :
361 virtual ~Instance() {
362 if ((flags_ & Transient) == 0)
363 // XXX: does this handle background threads correctly?
364 // XXX: this simply does not work on the console because I'm stupid
365 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
368 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
369 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
370 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object == nil ? nil : object_getClass(object)));
374 id GetValue() const {
375 return reinterpret_cast<id>(value_);
378 bool IsUninitialized() const {
379 return (flags_ & Uninitialized) != 0;
382 virtual Type_privateData *GetType() const;
388 Messages(Class value) :
393 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
394 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
395 if (_class == NSArray_)
397 if (Class super = class_getSuperclass(_class))
398 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
400 JSObjectSetPrototype(context, value, Array_prototype_);*/
404 Class GetValue() const {
405 return reinterpret_cast<Class>(value_);
413 JSContextRef context_;
417 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
422 JSValueProtect(context_, owner_);
426 JSValueUnprotect(context_, owner_);
429 JSObjectRef GetOwner() const {
437 Internal(id value, JSContextRef context, JSObjectRef owner) :
438 CYOwned(value, context, owner)
442 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
443 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
446 id GetValue() const {
447 return reinterpret_cast<id>(value_);
453 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
455 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
456 lhs.name = apr_pstrdup(pool, rhs.name);
457 if (rhs.type == NULL)
460 lhs.type = new(pool) Type;
461 Copy(pool, *lhs.type, *rhs.type);
463 lhs.offset = rhs.offset;
466 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
467 size_t count(rhs.count);
469 lhs.elements = new(pool) Element[count];
470 for (size_t index(0); index != count; ++index)
471 Copy(pool, lhs.elements[index], rhs.elements[index]);
474 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
475 lhs.primitive = rhs.primitive;
476 lhs.name = apr_pstrdup(pool, rhs.name);
477 lhs.flags = rhs.flags;
479 if (sig::IsAggregate(rhs.primitive))
480 Copy(pool, lhs.data.signature, rhs.data.signature);
482 sig::Type *&lht(lhs.data.data.type);
483 sig::Type *&rht(rhs.data.data.type);
488 lht = new(pool) Type;
489 Copy(pool, *lht, *rht);
492 lhs.data.data.size = rhs.data.data.size;
496 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
498 lhs.alignment = rhs.alignment;
500 if (rhs.elements == NULL)
504 while (rhs.elements[count] != NULL)
507 lhs.elements = new(pool) ffi_type *[count + 1];
508 lhs.elements[count] = NULL;
510 for (size_t index(0); index != count; ++index) {
511 // XXX: if these are libffi native then you can just take them
512 ffi_type *ffi(new(pool) ffi_type);
513 lhs.elements[index] = ffi;
514 sig::Copy(pool, *ffi, *rhs.elements[index]);
521 struct CStringMapLess :
522 std::binary_function<const char *, const char *, bool>
524 _finline bool operator ()(const char *lhs, const char *rhs) const {
525 return strcmp(lhs, rhs) < 0;
529 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
534 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
535 switch ([[entry objectAtIndex:0] intValue]) {
537 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
541 sig::Signature signature;
542 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
543 type = signature.elements[0].type;
549 struct Type_privateData :
552 static Type_privateData *Object;
553 static Type_privateData *Selector;
558 void Set(sig::Type *type) {
559 type_ = new(pool_) sig::Type;
560 sig::Copy(pool_, *type_, *type);
563 Type_privateData(apr_pool_t *pool, const char *type) :
569 sig::Signature signature;
570 sig::Parse(pool_, &signature, type, &Structor_);
571 type_ = signature.elements[0].type;
574 Type_privateData(sig::Type *type) :
581 Type_privateData(sig::Type *type, ffi_type *ffi) {
582 ffi_ = new(pool_) ffi_type;
583 sig::Copy(pool_, *ffi_, *ffi);
589 ffi_ = new(pool_) ffi_type;
591 sig::Element element;
593 element.type = type_;
596 sig::Signature signature;
597 signature.elements = &element;
601 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
609 Type_privateData *Type_privateData::Object;
610 Type_privateData *Type_privateData::Selector;
612 Type_privateData *Instance::GetType() const {
613 return Type_privateData::Object;
616 Type_privateData *Selector_privateData::GetType() const {
617 return Type_privateData::Selector;
623 Type_privateData *type_;
625 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
626 CYOwned(value, context, owner),
627 type_(new(pool_) Type_privateData(type))
632 struct Struct_privateData :
635 Type_privateData *type_;
637 Struct_privateData(JSContextRef context, JSObjectRef owner) :
638 CYOwned(NULL, context, owner)
643 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
644 static TypeMap Types_;
646 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
647 Struct_privateData *internal(new Struct_privateData(context, owner));
648 apr_pool_t *pool(internal->pool_);
649 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
650 internal->type_ = typical;
653 internal->value_ = data;
655 size_t size(typical->GetFFI()->size);
656 void *copy(apr_palloc(internal->pool_, size));
657 memcpy(copy, data, size);
658 internal->value_ = copy;
661 return JSObjectMake(context, Struct_, internal);
664 struct Functor_privateData :
667 sig::Signature signature_;
671 Functor_privateData(const char *type, void (*value)()) :
672 CYValue(reinterpret_cast<void *>(value))
674 sig::Parse(pool_, &signature_, type, &Structor_);
675 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
678 void (*GetValue())() const {
679 return reinterpret_cast<void (*)()>(value_);
683 struct Closure_privateData :
686 JSContextRef context_;
687 JSObjectRef function_;
689 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
690 Functor_privateData(type, NULL),
694 JSValueProtect(context_, function_);
697 virtual ~Closure_privateData() {
698 JSValueUnprotect(context_, function_);
702 struct Message_privateData :
707 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
708 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
714 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
715 Instance::Flags flags;
718 flags = Instance::Transient;
720 flags = Instance::None;
721 object = [object retain];
724 return Instance::Make(context, object, flags);
727 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
729 return [value UTF8String];
731 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
732 char *string(new(pool) char[size]);
733 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
734 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
739 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
740 return JSValueMakeBoolean(context, value);
743 JSValueRef CYCastJSValue(JSContextRef context, double value) {
744 return JSValueMakeNumber(context, value);
747 #define CYCastJSValue_(Type_) \
748 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
749 return JSValueMakeNumber(context, static_cast<double>(value)); \
753 CYCastJSValue_(unsigned int)
754 CYCastJSValue_(long int)
755 CYCastJSValue_(long unsigned int)
756 CYCastJSValue_(long long int)
757 CYCastJSValue_(long long unsigned int)
759 JSValueRef CYJSUndefined(JSContextRef context) {
760 return JSValueMakeUndefined(context);
763 size_t CYGetIndex(const char *value) {
764 if (value[0] != '0') {
766 size_t index(strtoul(value, &end, 10));
767 if (value + strlen(value) == end)
769 } else if (value[1] == '\0')
775 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value);
777 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
778 return CYGetIndex(CYPoolCString(pool, value));
781 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
782 return CYGetIndex(CYPoolCString(pool, value));
785 bool CYGetOffset(const char *value, ssize_t &index) {
786 if (value[0] != '0') {
788 index = strtol(value, &end, 10);
789 if (value + strlen(value) == end)
791 } else if (value[1] == '\0') {
799 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
800 return CYGetOffset(CYPoolCString(pool, value), index);
803 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
805 @interface NSMethodSignature (Cycript)
806 - (NSString *) _typeString;
809 @interface NSObject (Cycript)
811 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
812 - (JSType) cy$JSType;
814 - (NSObject *) cy$toJSON:(NSString *)key;
815 - (NSString *) cy$toCYON;
816 - (NSString *) cy$toKey;
818 - (bool) cy$hasProperty:(NSString *)name;
819 - (NSObject *) cy$getProperty:(NSString *)name;
820 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
821 - (bool) cy$deleteProperty:(NSString *)name;
826 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
829 @interface NSString (Cycript)
830 - (void *) cy$symbol;
833 struct PropertyAttributes {
838 const char *variable;
851 PropertyAttributes(objc_property_t property) :
863 name = property_getName(property);
864 const char *attributes(property_getAttributes(property));
866 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
868 case 'R': readonly = true; break;
869 case 'C': copy = true; break;
870 case '&': retain = true; break;
871 case 'N': nonatomic = true; break;
872 case 'G': getter_ = token + 1; break;
873 case 'S': setter_ = token + 1; break;
874 case 'V': variable = token + 1; break;
878 /*if (variable == NULL) {
879 variable = property_getName(property);
880 size_t size(strlen(variable));
881 char *name(new(pool_) char[size + 2]);
883 memcpy(name + 1, variable, size);
884 name[size + 1] = '\0';
889 const char *Getter() {
891 getter_ = apr_pstrdup(pool_, name);
895 const char *Setter() {
896 if (setter_ == NULL && !readonly) {
897 size_t length(strlen(name));
899 char *temp(new(pool_) char[length + 5]);
905 temp[3] = toupper(name[0]);
906 memcpy(temp + 4, name + 1, length - 1);
909 temp[length + 3] = ':';
910 temp[length + 4] = '\0';
919 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
920 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
923 /* Bridge: NSArray {{{ */
924 @implementation NSArray (Cycript)
926 - (NSString *) cy$toCYON {
927 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
928 [json appendString:@"["];
931 for (id object in self) {
933 [json appendString:@","];
936 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
937 [json appendString:CYPoolNSCYON(NULL, object)];
939 [json appendString:@","];
944 [json appendString:@"]"];
948 - (bool) cy$hasProperty:(NSString *)name {
949 if ([name isEqualToString:@"length"])
952 size_t index(CYGetIndex(NULL, name));
953 if (index == _not(size_t) || index >= [self count])
954 return [super cy$hasProperty:name];
959 - (NSObject *) cy$getProperty:(NSString *)name {
960 if ([name isEqualToString:@"length"])
961 return [NSNumber numberWithUnsignedInteger:[self count]];
963 size_t index(CYGetIndex(NULL, name));
964 if (index == _not(size_t) || index >= [self count])
965 return [super cy$getProperty:name];
967 return [self objectAtIndex:index];
972 /* Bridge: NSDictionary {{{ */
973 @implementation NSDictionary (Cycript)
975 - (NSString *) cy$toCYON {
976 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
977 [json appendString:@"{"];
980 for (id key in self) {
982 [json appendString:@","];
985 [json appendString:[key cy$toKey]];
986 [json appendString:@":"];
987 NSObject *object([self objectForKey:key]);
988 [json appendString:CYPoolNSCYON(NULL, object)];
991 [json appendString:@"}"];
995 - (bool) cy$hasProperty:(NSString *)name {
996 return [self objectForKey:name] != nil;
999 - (NSObject *) cy$getProperty:(NSString *)name {
1000 return [self objectForKey:name];
1005 /* Bridge: NSMutableArray {{{ */
1006 @implementation NSMutableArray (Cycript)
1008 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1009 if ([name isEqualToString:@"length"]) {
1010 // XXX: is this not intelligent?
1011 NSUInteger size([(NSNumber *)value unsignedIntegerValue]);
1012 NSUInteger count([self count]);
1014 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1015 else if (size != count) {
1016 WebUndefined *undefined([WebUndefined undefined]);
1017 for (size_t i(count); i != size; ++i)
1018 [self addObject:undefined];
1023 size_t index(CYGetIndex(NULL, name));
1024 if (index == _not(size_t))
1025 return [super cy$setProperty:name to:value];
1027 id object(value ?: [NSNull null]);
1029 size_t count([self count]);
1031 [self replaceObjectAtIndex:index withObject:object];
1033 if (index != count) {
1034 WebUndefined *undefined([WebUndefined undefined]);
1035 for (size_t i(count); i != index; ++i)
1036 [self addObject:undefined];
1039 [self addObject:object];
1045 - (bool) cy$deleteProperty:(NSString *)name {
1046 size_t index(CYGetIndex(NULL, name));
1047 if (index == _not(size_t) || index >= [self count])
1048 return [super cy$deleteProperty:name];
1049 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1055 /* Bridge: NSMutableDictionary {{{ */
1056 @implementation NSMutableDictionary (Cycript)
1058 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1059 [self setObject:(value ?: [NSNull null]) forKey:name];
1063 - (bool) cy$deleteProperty:(NSString *)name {
1064 if ([self objectForKey:name] == nil)
1067 [self removeObjectForKey:name];
1074 /* Bridge: NSNumber {{{ */
1075 @implementation NSNumber (Cycript)
1077 - (JSType) cy$JSType {
1078 // XXX: this just seems stupid
1079 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
1082 - (NSObject *) cy$toJSON:(NSString *)key {
1086 - (NSString *) cy$toCYON {
1087 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1090 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1091 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1096 /* Bridge: NSNull {{{ */
1097 @implementation NSNull (Cycript)
1099 - (JSType) cy$JSType {
1103 - (NSObject *) cy$toJSON:(NSString *)key {
1107 - (NSString *) cy$toCYON {
1113 /* Bridge: NSObject {{{ */
1114 @implementation NSObject (Cycript)
1116 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1117 return CYMakeInstance(context, self, false);
1120 - (JSType) cy$JSType {
1121 return kJSTypeObject;
1124 - (NSObject *) cy$toJSON:(NSString *)key {
1125 return [self description];
1128 - (NSString *) cy$toCYON {
1129 return [[self cy$toJSON:@""] cy$toCYON];
1132 - (NSString *) cy$toKey {
1133 return [self cy$toCYON];
1136 - (bool) cy$hasProperty:(NSString *)name {
1140 - (NSObject *) cy$getProperty:(NSString *)name {
1144 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1148 - (bool) cy$deleteProperty:(NSString *)name {
1154 /* Bridge: NSProxy {{{ */
1155 @implementation NSProxy (Cycript)
1157 - (NSObject *) cy$toJSON:(NSString *)key {
1158 return [self description];
1161 - (NSString *) cy$toCYON {
1162 return [[self cy$toJSON:@""] cy$toCYON];
1167 /* Bridge: NSString {{{ */
1168 @implementation NSString (Cycript)
1170 - (JSType) cy$JSType {
1171 return kJSTypeString;
1174 - (NSObject *) cy$toJSON:(NSString *)key {
1178 - (NSString *) cy$toCYON {
1179 // XXX: this should use the better code from Output.cpp
1180 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
1182 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
1183 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
1184 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
1185 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
1186 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
1188 CFStringInsert(json, 0, CFSTR("\""));
1189 CFStringAppend(json, CFSTR("\""));
1191 return [reinterpret_cast<const NSString *>(json) autorelease];
1194 - (NSString *) cy$toKey {
1195 const char *value([self UTF8String]);
1196 size_t size(strlen(value));
1201 if (DigitRange_[value[0]]) {
1202 size_t index(CYGetIndex(NULL, self));
1203 if (index == _not(size_t))
1206 if (!WordStartRange_[value[0]])
1208 for (size_t i(1); i != size; ++i)
1209 if (!WordEndRange_[value[i]])
1216 return [self cy$toCYON];
1219 - (void *) cy$symbol {
1221 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1226 /* Bridge: WebUndefined {{{ */
1227 @implementation WebUndefined (Cycript)
1229 - (JSType) cy$JSType {
1230 return kJSTypeUndefined;
1233 - (NSObject *) cy$toJSON:(NSString *)key {
1237 - (NSString *) cy$toCYON {
1238 return @"undefined";
1241 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1242 return CYJSUndefined(context);
1248 @interface CYJSObject : NSMutableDictionary {
1249 JSObjectRef object_;
1250 JSContextRef context_;
1253 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1255 - (NSString *) cy$toJSON:(NSString *)key;
1257 - (NSUInteger) count;
1258 - (id) objectForKey:(id)key;
1259 - (NSEnumerator *) keyEnumerator;
1260 - (void) setObject:(id)object forKey:(id)key;
1261 - (void) removeObjectForKey:(id)key;
1265 @interface CYJSArray : NSMutableArray {
1266 JSObjectRef object_;
1267 JSContextRef context_;
1270 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1272 - (NSUInteger) count;
1273 - (id) objectAtIndex:(NSUInteger)index;
1275 - (void) addObject:(id)anObject;
1276 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1277 - (void) removeLastObject;
1278 - (void) removeObjectAtIndex:(NSUInteger)index;
1279 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1286 @catch (id error) { \
1287 CYThrow(context, error, exception); \
1291 apr_status_t CYPoolRelease_(void *data) {
1292 id object(reinterpret_cast<id>(data));
1297 id CYPoolRelease(apr_pool_t *pool, id object) {
1300 else if (pool == NULL)
1301 return [object autorelease];
1303 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1308 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1309 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1312 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1313 JSValueRef exception(NULL);
1314 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1315 CYThrow(context, exception);
1316 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1317 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1320 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1321 if (!JSValueIsObjectOfClass(context, object, Instance_))
1322 return CYCastNSObject_(pool, context, object);
1324 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1325 return internal->GetValue();
1329 double CYCastDouble(const char *value, size_t size) {
1331 double number(strtod(value, &end));
1332 if (end != value + size)
1337 double CYCastDouble(const char *value) {
1338 return CYCastDouble(value, strlen(value));
1341 double CYCastDouble(JSContextRef context, JSValueRef value) {
1342 JSValueRef exception(NULL);
1343 double number(JSValueToNumber(context, value, &exception));
1344 CYThrow(context, exception);
1348 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1349 double number(CYCastDouble(context, value));
1350 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1353 CFStringRef CYCopyCFString(const char *value) {
1354 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1357 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1358 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1361 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1362 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1365 bool CYCastBool(JSContextRef context, JSValueRef value) {
1366 return JSValueToBoolean(context, value);
1369 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1373 switch (JSType type = JSValueGetType(context, value)) {
1374 case kJSTypeUndefined:
1375 object = [WebUndefined undefined];
1383 case kJSTypeBoolean:
1384 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1389 object = CYCopyCFNumber(context, value);
1394 object = CYCopyCFString(context, value);
1399 // XXX: this might could be more efficient
1400 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1405 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1412 return CYPoolRelease(pool, object);
1414 return CFRetain(object);
1417 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1418 return CYCFType(pool, context, value, true);
1421 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1422 return CYCFType(pool, context, value, false);
1425 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1427 size_t size(JSPropertyNameArrayGetCount(names));
1428 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1429 for (size_t index(0); index != size; ++index)
1430 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1434 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1435 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1438 void CYThrow(JSContextRef context, JSValueRef value) {
1441 @throw CYCastNSObject(NULL, context, value);
1444 JSValueRef CYJSNull(JSContextRef context) {
1445 return JSValueMakeNull(context);
1448 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1449 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1452 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1453 return CYCastJSValue(context, CYJSString(value));
1456 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1458 return CYJSNull(context);
1459 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1460 return [value cy$JSValueInContext:context];
1462 return CYMakeInstance(context, value, false);
1465 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1466 JSValueRef exception(NULL);
1467 JSObjectRef object(JSValueToObject(context, value, &exception));
1468 CYThrow(context, exception);
1472 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1473 if (exception == NULL)
1475 *exception = CYCastJSValue(context, error);
1478 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1479 JSValueRef exception(NULL);
1480 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1481 CYThrow(context, exception);
1485 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1486 // XXX: this isn't actually correct
1487 return value != NULL && JSValueIsObject(context, value);
1490 @implementation CYJSObject
1492 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1493 if ((self = [super init]) != nil) {
1496 JSValueProtect(context_, object_);
1501 JSValueUnprotect(context_, object_);
1505 - (NSObject *) cy$toJSON:(NSString *)key {
1506 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1507 if (!CYIsCallable(context_, toJSON))
1508 return [super cy$toJSON:key];
1510 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1511 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1512 // XXX: do I really want an NSNull here?!
1513 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1517 - (NSString *) cy$toCYON {
1518 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1519 if (!CYIsCallable(context_, toCYON)) super:
1520 return [super cy$toCYON];
1521 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1522 return CYCastNSString(NULL, CYJSString(context_, value));
1526 - (NSUInteger) count {
1527 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1528 size_t size(JSPropertyNameArrayGetCount(names));
1529 JSPropertyNameArrayRelease(names);
1533 - (id) objectForKey:(id)key {
1534 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1535 if (JSValueIsUndefined(context_, value))
1537 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1540 - (NSEnumerator *) keyEnumerator {
1541 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1542 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1543 JSPropertyNameArrayRelease(names);
1547 - (void) setObject:(id)object forKey:(id)key {
1548 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1551 - (void) removeObjectForKey:(id)key {
1552 JSValueRef exception(NULL);
1553 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1554 CYThrow(context_, exception);
1559 @implementation CYJSArray
1561 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1562 if ((self = [super init]) != nil) {
1565 JSValueProtect(context_, object_);
1570 JSValueUnprotect(context_, object_);
1574 - (NSUInteger) count {
1575 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1578 - (id) objectAtIndex:(NSUInteger)index {
1579 size_t bounds([self count]);
1580 if (index >= bounds)
1581 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1582 JSValueRef exception(NULL);
1583 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1584 CYThrow(context_, exception);
1585 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1588 - (void) addObject:(id)object {
1589 JSValueRef exception(NULL);
1590 JSValueRef arguments[1];
1591 arguments[0] = CYCastJSValue(context_, object);
1592 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1593 CYThrow(context_, exception);
1596 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1597 size_t bounds([self count] + 1);
1598 if (index >= bounds)
1599 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1600 JSValueRef exception(NULL);
1601 JSValueRef arguments[3];
1602 arguments[0] = CYCastJSValue(context_, index);
1603 arguments[1] = CYCastJSValue(context_, 0);
1604 arguments[2] = CYCastJSValue(context_, object);
1605 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1606 CYThrow(context_, exception);
1609 - (void) removeLastObject {
1610 JSValueRef exception(NULL);
1611 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1612 CYThrow(context_, exception);
1615 - (void) removeObjectAtIndex:(NSUInteger)index {
1616 size_t bounds([self count]);
1617 if (index >= bounds)
1618 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1619 JSValueRef exception(NULL);
1620 JSValueRef arguments[2];
1621 arguments[0] = CYCastJSValue(context_, index);
1622 arguments[1] = CYCastJSValue(context_, 1);
1623 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1624 CYThrow(context_, exception);
1627 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1628 size_t bounds([self count]);
1629 if (index >= bounds)
1630 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1631 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1636 NSString *CYCopyNSCYON(id value) {
1642 Class _class(object_getClass(value));
1643 SEL sel(@selector(cy$toCYON));
1645 if (Method toCYON = class_getInstanceMethod(_class, sel))
1646 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1647 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1648 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1649 string = [value cy$toCYON];
1652 if (value == NSZombie_)
1653 string = @"_NSZombie_";
1654 else if (_class == NSZombie_)
1655 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1656 // XXX: frowny /in/ the pants
1657 else if (value == NSMessageBuilder_ || value == Object_)
1660 string = [NSString stringWithFormat:@"%@", value];
1663 // XXX: frowny pants
1665 string = @"undefined";
1668 return [string retain];
1671 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1672 if (JSValueIsNull(context, value))
1673 return [@"null" retain];
1677 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1682 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1683 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1686 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1687 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1688 const char *string(CYPoolCString(pool, json));
1694 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1698 JSObjectRef object_;
1706 // XXX: delete object_? ;(
1709 static CYInternal *Get(id self) {
1710 CYInternal *internal(NULL);
1711 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1712 // XXX: do something epic? ;P
1718 static CYInternal *Set(id self) {
1719 CYInternal *internal(NULL);
1720 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1721 if (internal == NULL) {
1722 internal = new CYInternal();
1723 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1726 // XXX: do something epic? ;P
1732 bool HasProperty(JSContextRef context, JSStringRef name) {
1733 if (object_ == NULL)
1735 return JSObjectHasProperty(context, object_, name);
1738 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1739 if (object_ == NULL)
1741 return CYGetProperty(context, object_, name);
1744 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1745 if (object_ == NULL)
1746 object_ = JSObjectMake(context, NULL, NULL);
1747 CYSetProperty(context, object_, name, value);
1751 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1752 Selector_privateData *internal(new Selector_privateData(sel));
1753 return JSObjectMake(context, Selector_, internal);
1756 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1757 Pointer *internal(new Pointer(pointer, context, owner, type));
1758 return JSObjectMake(context, Pointer_, internal);
1761 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1762 Functor_privateData *internal(new Functor_privateData(type, function));
1763 return JSObjectMake(context, Functor_, internal);
1766 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1768 // XXX: this could be much more efficient
1769 const char *string([CYCastNSString(NULL, value) UTF8String]);
1772 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1773 char *string(new(pool) char[size]);
1774 JSStringGetUTF8CString(value, string, size);
1779 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1780 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1783 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1784 return CYGetOffset(CYPoolCString(pool, value), index);
1787 // XXX: this macro is unhygenic
1788 #define CYCastCString(context, value) ({ \
1790 if (value == NULL) \
1792 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1793 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1794 utf8 = reinterpret_cast<char *>(alloca(size)); \
1795 JSStringGetUTF8CString(string, utf8, size); \
1796 JSStringRelease(string); \
1802 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1803 switch (JSValueGetType(context, value)) {
1806 /*case kJSTypeString:
1807 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1809 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1810 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1811 return internal->value_;
1814 double number(CYCastDouble(context, value));
1815 if (std::isnan(number))
1816 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1817 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1821 template <typename Type_>
1822 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1823 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1826 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1827 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1828 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1829 return reinterpret_cast<SEL>(internal->value_);
1831 return CYCastPointer<SEL>(context, value);
1834 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1835 switch (type->primitive) {
1836 case sig::boolean_P:
1837 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1840 #define CYPoolFFI_(primitive, native) \
1841 case sig::primitive ## _P: \
1842 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1845 CYPoolFFI_(uchar, unsigned char)
1846 CYPoolFFI_(char, char)
1847 CYPoolFFI_(ushort, unsigned short)
1848 CYPoolFFI_(short, short)
1849 CYPoolFFI_(ulong, unsigned long)
1850 CYPoolFFI_(long, long)
1851 CYPoolFFI_(uint, unsigned int)
1852 CYPoolFFI_(int, int)
1853 CYPoolFFI_(ulonglong, unsigned long long)
1854 CYPoolFFI_(longlong, long long)
1855 CYPoolFFI_(float, float)
1856 CYPoolFFI_(double, double)
1859 case sig::typename_P:
1860 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1863 case sig::selector_P:
1864 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1867 case sig::pointer_P:
1868 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1872 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1875 case sig::struct_P: {
1876 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1877 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1878 for (size_t index(0); index != type->data.signature.count; ++index) {
1879 sig::Element *element(&type->data.signature.elements[index]);
1880 ffi_type *field(ffi->elements[index]);
1883 if (aggregate == NULL)
1886 rhs = CYGetProperty(context, aggregate, index);
1887 if (JSValueIsUndefined(context, rhs)) {
1888 if (element->name != NULL)
1889 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1892 if (JSValueIsUndefined(context, rhs)) undefined:
1893 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1897 CYPoolFFI(pool, context, element->type, field, base, rhs);
1899 base += field->size;
1907 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1912 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1915 switch (type->primitive) {
1916 case sig::boolean_P:
1917 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1920 #define CYFromFFI_(primitive, native) \
1921 case sig::primitive ## _P: \
1922 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1925 CYFromFFI_(uchar, unsigned char)
1926 CYFromFFI_(char, char)
1927 CYFromFFI_(ushort, unsigned short)
1928 CYFromFFI_(short, short)
1929 CYFromFFI_(ulong, unsigned long)
1930 CYFromFFI_(long, long)
1931 CYFromFFI_(uint, unsigned int)
1932 CYFromFFI_(int, int)
1933 CYFromFFI_(ulonglong, unsigned long long)
1934 CYFromFFI_(longlong, long long)
1935 CYFromFFI_(float, float)
1936 CYFromFFI_(double, double)
1938 case sig::object_P: {
1939 if (id object = *reinterpret_cast<id *>(data)) {
1940 value = CYCastJSValue(context, object);
1946 case sig::typename_P:
1947 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1950 case sig::selector_P:
1951 if (SEL sel = *reinterpret_cast<SEL *>(data))
1952 value = CYMakeSelector(context, sel);
1956 case sig::pointer_P:
1957 if (void *pointer = *reinterpret_cast<void **>(data))
1958 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1963 if (char *utf8 = *reinterpret_cast<char **>(data))
1964 value = CYCastJSValue(context, utf8);
1969 value = CYMakeStruct(context, data, type, ffi, owner);
1973 value = CYJSUndefined(context);
1977 value = CYJSNull(context);
1981 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1988 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1989 if (Method method = class_getInstanceMethod(_class, selector)) {
1993 method_getReturnType(method, type, sizeof(type));
1998 // XXX: possibly use a more "awesome" check?
2002 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
2004 return method_getTypeEncoding(method);
2005 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2006 return CYPoolCString(pool, type);
2011 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2012 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2014 JSContextRef context(internal->context_);
2016 size_t count(internal->cif_.nargs);
2017 JSValueRef values[count];
2019 for (size_t index(0); index != count; ++index)
2020 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2022 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2023 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2026 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2027 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2029 JSContextRef context(internal->context_);
2031 size_t count(internal->cif_.nargs);
2032 JSValueRef values[count];
2034 for (size_t index(0); index != count; ++index)
2035 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2037 JSObjectRef _this(CYCastJSObject(context, values[0]));
2039 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2040 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2043 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2044 // XXX: in case of exceptions this will leak
2045 // XXX: in point of fact, this may /need/ to leak :(
2046 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2048 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2049 NULL, sizeof(ffi_closure),
2050 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2054 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2055 _assert(status == FFI_OK);
2057 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2059 internal->value_ = closure;
2064 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2065 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2066 return JSObjectMake(context, Functor_, internal);
2069 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2070 JSValueRef exception(NULL);
2071 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2072 CYThrow(context, exception);
2075 JSObjectRef function(CYCastJSObject(context, value));
2076 return CYMakeFunctor(context, function, type);
2078 void (*function)()(CYCastPointer<void (*)()>(context, value));
2079 return CYMakeFunctor(context, function, type);
2083 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2084 Message_privateData *internal(new Message_privateData(sel, type, imp));
2085 return JSObjectMake(context, Message_, internal);
2088 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2089 JSObjectRef function(CYCastJSObject(context, value));
2090 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2091 return reinterpret_cast<IMP>(internal->GetValue());
2094 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2095 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2096 Class _class(internal->GetValue());
2099 const char *name(CYPoolCString(pool, property));
2101 if (SEL sel = sel_getUid(name))
2102 if (class_getInstanceMethod(_class, sel) != NULL)
2108 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2109 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2110 Class _class(internal->GetValue());
2113 const char *name(CYPoolCString(pool, property));
2115 if (SEL sel = sel_getUid(name))
2116 if (Method method = class_getInstanceMethod(_class, sel))
2117 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2122 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2123 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2124 Class _class(internal->GetValue());
2127 const char *name(CYPoolCString(pool, property));
2129 SEL sel(sel_registerName(name));
2131 Method method(class_getInstanceMethod(_class, sel));
2136 if (JSValueIsObjectOfClass(context, value, Message_)) {
2137 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2138 type = sig::Unparse(pool, &message->signature_);
2139 imp = reinterpret_cast<IMP>(message->GetValue());
2141 type = CYPoolTypeEncoding(pool, _class, sel, method);
2142 imp = CYMakeMessage(context, value, type);
2146 method_setImplementation(method, imp);
2148 class_replaceMethod(_class, sel, imp, type);
2154 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2155 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2156 Class _class(internal->GetValue());
2159 const char *name(CYPoolCString(pool, property));
2161 if (SEL sel = sel_getUid(name))
2162 if (Method method = class_getInstanceMethod(_class, sel)) {
2163 objc_method_list list = {NULL, 1, {method}};
2164 class_removeMethods(_class, &list);
2172 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2173 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2174 Class _class(internal->GetValue());
2177 Method *data(class_copyMethodList(_class, &size));
2178 for (size_t i(0); i != size; ++i)
2179 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2183 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2184 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2185 id self(internal->GetValue());
2187 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2191 NSString *name(CYCastNSString(pool, property));
2193 if (CYInternal *internal = CYInternal::Get(self))
2194 if (internal->HasProperty(context, property))
2197 Class _class(object_getClass(self));
2200 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2201 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2202 if ([self cy$hasProperty:name])
2204 } CYPoolCatch(false)
2206 const char *string(CYPoolCString(pool, name));
2208 if (class_getProperty(_class, string) != NULL)
2211 if (SEL sel = sel_getUid(string))
2212 if (CYImplements(self, _class, sel, true))
2218 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2219 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2220 id self(internal->GetValue());
2222 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2223 return Internal::Make(context, self, object);
2227 NSString *name(CYCastNSString(pool, property));
2229 if (CYInternal *internal = CYInternal::Get(self))
2230 if (JSValueRef value = internal->GetProperty(context, property))
2234 if (NSObject *data = [self cy$getProperty:name])
2235 return CYCastJSValue(context, data);
2238 const char *string(CYPoolCString(pool, name));
2239 Class _class(object_getClass(self));
2241 if (objc_property_t property = class_getProperty(_class, string)) {
2242 PropertyAttributes attributes(property);
2243 SEL sel(sel_registerName(attributes.Getter()));
2244 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2247 if (SEL sel = sel_getUid(string))
2248 if (CYImplements(self, _class, sel, true))
2249 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2255 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2256 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2257 id self(internal->GetValue());
2262 NSString *name(CYCastNSString(pool, property));
2263 NSString *data(CYCastNSObject(pool, context, value));
2266 if ([self cy$setProperty:name to:data])
2270 const char *string(CYPoolCString(pool, name));
2271 Class _class(object_getClass(self));
2273 if (objc_property_t property = class_getProperty(_class, string)) {
2274 PropertyAttributes attributes(property);
2275 if (const char *setter = attributes.Setter()) {
2276 SEL sel(sel_registerName(setter));
2277 JSValueRef arguments[1] = {value};
2278 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2283 size_t length(strlen(string));
2285 char set[length + 5];
2291 if (string[0] != '\0') {
2292 set[3] = toupper(string[0]);
2293 memcpy(set + 4, string + 1, length - 1);
2296 set[length + 3] = ':';
2297 set[length + 4] = '\0';
2299 if (SEL sel = sel_getUid(set))
2300 if (CYImplements(self, _class, sel, false)) {
2301 JSValueRef arguments[1] = {value};
2302 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2305 if (CYInternal *internal = CYInternal::Set(self)) {
2306 internal->SetProperty(context, property, value);
2314 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2315 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2316 id self(internal->GetValue());
2320 NSString *name(CYCastNSString(NULL, property));
2321 return [self cy$deleteProperty:name];
2326 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2327 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2328 id self(internal->GetValue());
2331 Class _class(object_getClass(self));
2335 objc_property_t *data(class_copyPropertyList(_class, &size));
2336 for (size_t i(0); i != size; ++i)
2337 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2342 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2344 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2345 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2350 static bool CYIsClass(id self) {
2351 // XXX: this is a lame object_isClass
2352 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2355 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2356 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2357 Class _class(internal->GetValue());
2358 if (!CYIsClass(_class))
2361 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2362 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2363 // XXX: this isn't always safe
2365 return [linternal->GetValue() isKindOfClass:_class];
2372 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2373 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2376 id self(internal->GetValue());
2377 const char *name(CYPoolCString(pool, property));
2379 if (object_getInstanceVariable(self, name, NULL) != NULL)
2385 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2386 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2390 id self(internal->GetValue());
2391 const char *name(CYPoolCString(pool, property));
2393 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2394 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2395 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2402 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2403 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2407 id self(internal->GetValue());
2408 const char *name(CYPoolCString(pool, property));
2410 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2411 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2412 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2420 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2421 if (Class super = class_getSuperclass(_class))
2422 Internal_getPropertyNames_(super, names);
2425 Ivar *data(class_copyIvarList(_class, &size));
2426 for (size_t i(0); i != size; ++i)
2427 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2431 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2432 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2435 id self(internal->GetValue());
2436 Class _class(object_getClass(self));
2438 Internal_getPropertyNames_(_class, names);
2441 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2442 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2443 return internal->GetOwner();
2446 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2447 Type_privateData *typical(internal->type_);
2448 sig::Type *type(typical->type_);
2452 const char *name(CYPoolCString(pool, property));
2453 size_t length(strlen(name));
2454 double number(CYCastDouble(name, length));
2456 size_t count(type->data.signature.count);
2458 if (std::isnan(number)) {
2459 if (property == NULL)
2462 sig::Element *elements(type->data.signature.elements);
2464 for (size_t local(0); local != count; ++local) {
2465 sig::Element *element(&elements[local]);
2466 if (element->name != NULL && strcmp(name, element->name) == 0) {
2474 index = static_cast<ssize_t>(number);
2475 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2480 ffi_type **elements(typical->GetFFI()->elements);
2482 base = reinterpret_cast<uint8_t *>(internal->value_);
2483 for (ssize_t local(0); local != index; ++local)
2484 base += elements[local]->size;
2489 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2490 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2491 Type_privateData *typical(internal->type_);
2493 ffi_type *ffi(typical->GetFFI());
2495 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2496 base += ffi->size * index;
2498 JSObjectRef owner(internal->GetOwner() ?: object);
2501 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2505 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2507 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2508 Type_privateData *typical(internal->type_);
2510 if (typical->type_ == NULL)
2514 if (!CYGetOffset(pool, property, offset))
2517 return Pointer_getIndex(context, object, offset, exception);
2520 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2521 return Pointer_getIndex(context, object, 0, exception);
2524 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2525 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2526 Type_privateData *typical(internal->type_);
2528 ffi_type *ffi(typical->GetFFI());
2530 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2531 base += ffi->size * index;
2534 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2539 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2541 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2542 Type_privateData *typical(internal->type_);
2544 if (typical->type_ == NULL)
2548 if (!CYGetOffset(pool, property, offset))
2551 return Pointer_setIndex(context, object, offset, value, exception);
2554 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2555 return Pointer_setIndex(context, object, 0, value, exception);
2558 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2559 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2560 Type_privateData *typical(internal->type_);
2561 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2564 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2566 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2567 Type_privateData *typical(internal->type_);
2572 if (!Index_(pool, internal, property, index, base))
2575 JSObjectRef owner(internal->GetOwner() ?: object);
2578 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2582 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2584 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2585 Type_privateData *typical(internal->type_);
2590 if (!Index_(pool, internal, property, index, base))
2594 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2599 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2600 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2601 Type_privateData *typical(internal->type_);
2602 sig::Type *type(typical->type_);
2607 size_t count(type->data.signature.count);
2608 sig::Element *elements(type->data.signature.elements);
2612 for (size_t index(0); index != count; ++index) {
2614 name = elements[index].name;
2617 sprintf(number, "%lu", index);
2621 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2625 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)()) {
2627 if (setups + count != signature->count - 1)
2628 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2630 size_t size(setups + count);
2632 memcpy(values, setup, sizeof(void *) * setups);
2634 for (size_t index(setups); index != size; ++index) {
2635 sig::Element *element(&signature->elements[index + 1]);
2636 ffi_type *ffi(cif->arg_types[index]);
2638 values[index] = new(pool) uint8_t[ffi->size];
2639 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2642 uint8_t value[cif->rtype->size];
2643 ffi_call(cif, function, value, values);
2645 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2649 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2652 NSString *name(CYCastNSString(pool, property));
2653 if (Class _class = NSClassFromString(name))
2654 return CYMakeInstance(context, _class, true);
2659 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2660 size_t size(objc_getClassList(NULL, 0));
2661 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2664 size_t writ(objc_getClassList(data, size));
2667 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2673 for (size_t i(0); i != writ; ++i)
2674 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2680 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2681 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2685 const char *name(CYPoolCString(pool, property));
2687 const char **data(objc_copyClassNamesForImage(internal, &size));
2689 for (size_t i(0); i != size; ++i)
2690 if (strcmp(name, data[i]) == 0) {
2691 if (Class _class = objc_getClass(name)) {
2692 value = CYMakeInstance(context, _class, true);
2704 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2705 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2707 const char **data(objc_copyClassNamesForImage(internal, &size));
2708 for (size_t i(0); i != size; ++i)
2709 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2713 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2716 const char *name(CYPoolCString(pool, property));
2718 const char **data(objc_copyImageNames(&size));
2719 for (size_t i(0); i != size; ++i)
2720 if (strcmp(name, data[i]) == 0) {
2729 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2730 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2735 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2737 const char **data(objc_copyImageNames(&size));
2738 for (size_t i(0); i != size; ++i)
2739 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2743 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2746 NSString *name(CYCastNSString(pool, property));
2747 if (Protocol *protocol = NSProtocolFromString(name))
2748 return CYMakeInstance(context, protocol, true);
2753 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2755 Protocol **data(objc_copyProtocolList(&size));
2756 for (size_t i(0); i != size; ++i)
2757 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2761 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
2762 Type_privateData *internal(new Type_privateData(NULL, type));
2763 return JSObjectMake(context, Type_, internal);
2766 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
2767 Type_privateData *internal(new Type_privateData(type));
2768 return JSObjectMake(context, Type_, internal);
2771 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2772 if (JSStringIsEqualToUTF8CString(property, "nil"))
2773 return Instance::Make(context, nil);
2777 NSString *name(CYCastNSString(pool, property));
2778 if (Class _class = NSClassFromString(name))
2779 return CYMakeInstance(context, _class, true);
2780 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2781 switch ([[entry objectAtIndex:0] intValue]) {
2783 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2785 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2787 // XXX: this is horrendously inefficient
2788 sig::Signature signature;
2789 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2791 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2792 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2794 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
2795 switch ([[entry objectAtIndex:0] intValue]) {
2796 // XXX: implement case 0
2798 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
2804 static bool stret(ffi_type *ffi_type) {
2805 return ffi_type->type == FFI_TYPE_STRUCT && (
2806 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2807 struct_forward_array[ffi_type->size] != 0
2812 int *_NSGetArgc(void);
2813 char ***_NSGetArgv(void);
2816 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2821 NSLog(@"%s", CYCastCString(context, arguments[0]));
2822 return CYJSUndefined(context);
2826 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2829 Class _class(object_getClass(self));
2830 if (Method method = class_getInstanceMethod(_class, _cmd))
2831 type = method_getTypeEncoding(method);
2835 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2837 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2838 type = CYPoolCString(pool, [method _typeString]);
2847 sig::Signature signature;
2848 sig::Parse(pool, &signature, type, &Structor_);
2851 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2853 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2854 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2857 static size_t Nonce_(0);
2859 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2861 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
2862 return CYCastJSValue(context, name);
2865 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2875 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2877 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2878 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2879 self = internal->GetValue();
2880 uninitialized = internal->IsUninitialized();
2882 internal->value_ = nil;
2884 self = CYCastNSObject(pool, context, arguments[0]);
2885 uninitialized = false;
2889 return CYJSNull(context);
2891 _cmd = CYCastSEL(context, arguments[1]);
2894 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2897 /* Hook: objc_registerClassPair {{{ */
2898 // XXX: replace this with associated objects
2900 MSHook(void, CYDealloc, id self, SEL sel) {
2901 CYInternal *internal;
2902 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2903 if (internal != NULL)
2905 _CYDealloc(self, sel);
2908 MSHook(void, objc_registerClassPair, Class _class) {
2909 Class super(class_getSuperclass(_class));
2910 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2911 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2912 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2915 _objc_registerClassPair(_class);
2918 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2921 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2923 Class _class(CYCastNSObject(pool, context, arguments[0]));
2924 $objc_registerClassPair(_class);
2925 return CYJSUndefined(context);
2930 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2931 JSGarbageCollect(context);
2932 return CYJSUndefined(context);
2935 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2936 JSValueRef setup[count + 2];
2939 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2940 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2943 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2945 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2947 // XXX: handle Instance::Uninitialized?
2948 id self(CYCastNSObject(pool, context, _this));
2952 setup[1] = &internal->sel_;
2954 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2957 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2959 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2960 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2963 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2966 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2967 const char *name(CYCastCString(context, arguments[0]));
2968 return CYMakeSelector(context, sel_registerName(name));
2972 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2975 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2977 void *value(CYCastPointer<void *>(context, arguments[0]));
2978 const char *type(CYCastCString(context, arguments[1]));
2982 sig::Signature signature;
2983 sig::Parse(pool, &signature, type, &Structor_);
2985 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2989 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2992 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2993 const char *type(CYCastCString(context, arguments[0]));
2994 return CYMakeType(context, type);
2998 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2999 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3004 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3005 type.primitive = sig::pointer_P;
3006 type.data.data.size = 0;
3008 size_t index(CYGetIndex(NULL, property));
3009 if (index == _not(size_t))
3011 type.primitive = sig::array_P;
3012 type.data.data.size = index;
3018 type.data.data.type = internal->type_;
3020 return CYMakeType(context, &type);
3024 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3025 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3029 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3030 sig::Type *type(internal->type_);
3031 ffi_type *ffi(internal->GetFFI());
3033 uint8_t value[ffi->size];
3035 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3036 return CYFromFFI(context, type, ffi, value);
3040 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3043 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3044 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3046 sig::Type *type(internal->type_);
3049 if (type->primitive != sig::array_P)
3052 size = type->data.data.size;
3053 type = type->data.data.type;
3056 void *value(malloc(internal->GetFFI()->size));
3057 return CYMakePointer(context, value, type, NULL, NULL);
3061 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3064 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
3065 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3066 return Instance::Make(context, self);
3070 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3073 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
3074 const char *type(CYCastCString(context, arguments[1]));
3075 return CYMakeFunctor(context, arguments[0], type);
3079 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3080 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3081 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3084 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3085 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3086 Type_privateData *typical(internal->GetType());
3091 if (typical == NULL) {
3095 type = typical->type_;
3096 ffi = typical->ffi_;
3099 return CYMakePointer(context, &internal->value_, type, ffi, object);
3102 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3103 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3106 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3110 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3111 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3114 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3115 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3117 sprintf(string, "%p", internal->value_);
3120 return CYCastJSValue(context, string);
3124 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3125 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3126 return Instance::Make(context, object_getClass(internal->GetValue()));
3129 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3130 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3131 id self(internal->GetValue());
3132 if (!CYIsClass(self))
3133 return CYJSUndefined(context);
3135 return CYGetClassPrototype(context, self);
3139 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3140 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3141 id self(internal->GetValue());
3142 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3143 return CYJSUndefined(context);
3144 return Messages::Make(context, self);
3147 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3148 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3151 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3155 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
3160 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3161 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3164 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3168 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3169 // XXX: check for support of cy$toJSON?
3170 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3175 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3176 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3179 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3183 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3188 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3189 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3192 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3196 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3197 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3200 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3201 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3202 const char *name(sel_getName(internal->GetValue()));
3206 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3211 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3214 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
3216 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3217 Class _class(CYCastNSObject(pool, context, arguments[0]));
3218 SEL sel(internal->GetValue());
3219 Method method(class_getInstanceMethod(_class, sel));
3220 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3221 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3225 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3227 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3229 const char *type(sig::Unparse(pool, internal->type_));
3231 return CYCastJSValue(context, CYJSString(type));
3236 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3238 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3240 const char *type(sig::Unparse(pool, internal->type_));
3242 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
3247 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3248 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3251 static JSStaticValue CYValue_staticValues[2] = {
3252 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3253 {NULL, NULL, NULL, 0}
3256 static JSStaticValue Pointer_staticValues[2] = {
3257 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3258 {NULL, NULL, NULL, 0}
3261 static JSStaticFunction Pointer_staticFunctions[4] = {
3262 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3263 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3264 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3268 static JSStaticFunction Struct_staticFunctions[2] = {
3269 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3273 static JSStaticFunction Functor_staticFunctions[4] = {
3274 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3275 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3276 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3280 static JSStaticValue Instance_staticValues[5] = {
3281 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3282 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3283 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3284 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3285 {NULL, NULL, NULL, 0}
3288 static JSStaticFunction Instance_staticFunctions[5] = {
3289 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3290 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3291 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3292 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3296 static JSStaticFunction Internal_staticFunctions[2] = {
3297 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3301 static JSStaticFunction Selector_staticFunctions[5] = {
3302 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3303 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3304 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3305 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3309 static JSStaticFunction Type_staticFunctions[4] = {
3310 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3311 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3312 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3316 void CYSetArgs(int argc, const char *argv[]) {
3317 JSContextRef context(CYGetJSContext());
3318 JSValueRef args[argc];
3319 for (int i(0); i != argc; ++i)
3320 args[i] = CYCastJSValue(context, argv[i]);
3321 JSValueRef exception(NULL);
3322 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3323 CYThrow(context, exception);
3324 CYSetProperty(context, System_, CYJSString("args"), array);
3327 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3328 return JSContextGetGlobalObject(context);
3331 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3332 JSContextRef context(CYGetJSContext());
3333 JSValueRef exception(NULL), result;
3336 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3337 } catch (const char *error) {
3341 if (exception != NULL) { error:
3346 if (JSValueIsUndefined(context, result))
3352 json = CYPoolCCYON(pool, context, result, &exception);
3353 } catch (const char *error) {
3357 if (exception != NULL)
3360 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3364 static apr_pool_t *Pool_;
3368 const char * volatile data_;
3371 // XXX: this is "tre lame"
3372 @interface CYClient_ : NSObject {
3375 - (void) execute:(NSValue *)value;
3379 @implementation CYClient_
3381 - (void) execute:(NSValue *)value {
3382 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3383 const char *data(execute->data_);
3384 execute->data_ = NULL;
3385 execute->data_ = CYExecute(execute->pool_, data);
3394 apr_thread_t *thread_;
3396 CYClient(int socket) :
3402 _syscall(close(socket_));
3405 void Handle() { _pooled
3406 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3410 if (!CYRecvAll(socket_, &size, sizeof(size)))
3414 char *data(new(pool) char[size + 1]);
3415 if (!CYRecvAll(socket_, data, size))
3419 CYDriver driver("");
3420 cy::parser parser(driver);
3422 driver.data_ = data;
3423 driver.size_ = size;
3426 if (parser.parse() != 0 || !driver.errors_.empty()) {
3428 size = _not(size_t);
3430 CYContext context(driver.pool_);
3431 driver.program_->Replace(context);
3432 std::ostringstream str;
3434 out << *driver.program_;
3435 std::string code(str.str());
3436 CYExecute_ execute = {pool, code.c_str()};
3437 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3438 json = execute.data_;
3439 size = json == NULL ? _not(size_t) : strlen(json);
3442 if (!CYSendAll(socket_, &size, sizeof(size)))
3445 if (!CYSendAll(socket_, json, size))
3451 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3452 CYClient *client(reinterpret_cast<CYClient *>(data));
3458 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3459 CYClient *client(new(pool) CYClient(socket));
3460 apr_threadattr_t *attr;
3461 _aprcall(apr_threadattr_create(&attr, client->pool_));
3462 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3465 MSInitialize { _pooled
3466 _aprcall(apr_initialize());
3467 _aprcall(apr_pool_create(&Pool_, NULL));
3469 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3470 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3472 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3474 NSArray_ = objc_getClass("NSArray");
3475 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3476 NSCFType_ = objc_getClass("NSCFType");
3477 NSDictionary_ = objc_getClass("NSDictonary");
3478 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3479 NSZombie_ = objc_getClass("_NSZombie_");
3480 Object_ = objc_getClass("Object");
3483 JSGlobalContextRef CYGetJSContext() {
3484 if (Context_ == NULL) {
3485 JSClassDefinition definition;
3487 definition = kJSClassDefinitionEmpty;
3488 definition.className = "Functor";
3489 definition.staticFunctions = Functor_staticFunctions;
3490 definition.callAsFunction = &Functor_callAsFunction;
3491 definition.finalize = &Finalize;
3492 Functor_ = JSClassCreate(&definition);
3494 definition = kJSClassDefinitionEmpty;
3495 definition.className = "Instance";
3496 definition.staticValues = Instance_staticValues;
3497 definition.staticFunctions = Instance_staticFunctions;
3498 definition.hasProperty = &Instance_hasProperty;
3499 definition.getProperty = &Instance_getProperty;
3500 definition.setProperty = &Instance_setProperty;
3501 definition.deleteProperty = &Instance_deleteProperty;
3502 definition.getPropertyNames = &Instance_getPropertyNames;
3503 definition.callAsConstructor = &Instance_callAsConstructor;
3504 definition.hasInstance = &Instance_hasInstance;
3505 definition.finalize = &Finalize;
3506 Instance_ = JSClassCreate(&definition);
3508 definition = kJSClassDefinitionEmpty;
3509 definition.className = "Internal";
3510 definition.staticFunctions = Internal_staticFunctions;
3511 definition.hasProperty = &Internal_hasProperty;
3512 definition.getProperty = &Internal_getProperty;
3513 definition.setProperty = &Internal_setProperty;
3514 definition.getPropertyNames = &Internal_getPropertyNames;
3515 definition.finalize = &Finalize;
3516 Internal_ = JSClassCreate(&definition);
3518 definition = kJSClassDefinitionEmpty;
3519 definition.className = "Message";
3520 definition.staticFunctions = Functor_staticFunctions;
3521 definition.callAsFunction = &Message_callAsFunction;
3522 definition.finalize = &Finalize;
3523 Message_ = JSClassCreate(&definition);
3525 definition = kJSClassDefinitionEmpty;
3526 definition.className = "Messages";
3527 definition.hasProperty = &Messages_hasProperty;
3528 definition.getProperty = &Messages_getProperty;
3529 definition.setProperty = &Messages_setProperty;
3531 definition.deleteProperty = &Messages_deleteProperty;
3533 definition.getPropertyNames = &Messages_getPropertyNames;
3534 definition.finalize = &Finalize;
3535 Messages_ = JSClassCreate(&definition);
3537 definition = kJSClassDefinitionEmpty;
3538 definition.className = "NSArrayPrototype";
3539 //definition.hasProperty = &NSArrayPrototype_hasProperty;
3540 //definition.getProperty = &NSArrayPrototype_getProperty;
3541 //definition.setProperty = &NSArrayPrototype_setProperty;
3542 //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
3543 //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
3544 NSArrayPrototype_ = JSClassCreate(&definition);
3546 definition = kJSClassDefinitionEmpty;
3547 definition.className = "Pointer";
3548 definition.staticValues = Pointer_staticValues;
3549 definition.staticFunctions = Pointer_staticFunctions;
3550 definition.getProperty = &Pointer_getProperty;
3551 definition.setProperty = &Pointer_setProperty;
3552 definition.finalize = &Finalize;
3553 Pointer_ = JSClassCreate(&definition);
3555 definition = kJSClassDefinitionEmpty;
3556 definition.className = "Selector";
3557 definition.staticValues = CYValue_staticValues;
3558 definition.staticFunctions = Selector_staticFunctions;
3559 definition.callAsFunction = &Selector_callAsFunction;
3560 definition.finalize = &Finalize;
3561 Selector_ = JSClassCreate(&definition);
3563 definition = kJSClassDefinitionEmpty;
3564 definition.className = "Struct";
3565 definition.staticFunctions = Struct_staticFunctions;
3566 definition.getProperty = &Struct_getProperty;
3567 definition.setProperty = &Struct_setProperty;
3568 definition.getPropertyNames = &Struct_getPropertyNames;
3569 definition.finalize = &Finalize;
3570 Struct_ = JSClassCreate(&definition);
3572 definition = kJSClassDefinitionEmpty;
3573 definition.className = "Type";
3574 definition.staticFunctions = Type_staticFunctions;
3575 definition.getProperty = &Type_getProperty;
3576 definition.callAsFunction = &Type_callAsFunction;
3577 definition.callAsConstructor = &Type_callAsConstructor;
3578 definition.finalize = &Finalize;
3579 Type_ = JSClassCreate(&definition);
3581 definition = kJSClassDefinitionEmpty;
3582 definition.className = "Runtime";
3583 definition.getProperty = &Runtime_getProperty;
3584 Runtime_ = JSClassCreate(&definition);
3586 definition = kJSClassDefinitionEmpty;
3587 definition.className = "ObjectiveC::Classes";
3588 definition.getProperty = &ObjectiveC_Classes_getProperty;
3589 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3590 ObjectiveC_Classes_ = JSClassCreate(&definition);
3592 definition = kJSClassDefinitionEmpty;
3593 definition.className = "ObjectiveC::Images";
3594 definition.getProperty = &ObjectiveC_Images_getProperty;
3595 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3596 ObjectiveC_Images_ = JSClassCreate(&definition);
3598 definition = kJSClassDefinitionEmpty;
3599 definition.className = "ObjectiveC::Image::Classes";
3600 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3601 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3602 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3604 definition = kJSClassDefinitionEmpty;
3605 definition.className = "ObjectiveC::Protocols";
3606 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3607 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3608 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3610 definition = kJSClassDefinitionEmpty;
3611 //definition.getProperty = &Global_getProperty;
3612 JSClassRef Global(JSClassCreate(&definition));
3614 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3617 JSObjectRef global(CYGetGlobalObject(context));
3619 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3620 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3621 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3623 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3624 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3625 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3627 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3628 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3629 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3631 length_ = JSStringCreateWithUTF8CString("length");
3632 message_ = JSStringCreateWithUTF8CString("message");
3633 name_ = JSStringCreateWithUTF8CString("name");
3634 prototype_ = JSStringCreateWithUTF8CString("prototype");
3635 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3636 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3638 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3639 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3641 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3642 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3643 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3644 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3646 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3647 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3648 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3649 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3651 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3653 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3654 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3655 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3656 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3658 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3659 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3660 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3661 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3662 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3664 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3666 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3668 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
3669 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
3670 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
3672 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3673 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3674 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3676 System_ = JSObjectMake(context, NULL, NULL);
3677 CYSetProperty(context, global, CYJSString("system"), System_);
3678 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3679 //CYSetProperty(context, System_, CYJSString("global"), global);
3681 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3683 Result_ = JSStringCreateWithUTF8CString("_");
3685 JSValueProtect(context, Array_);
3686 JSValueProtect(context, Function_);
3687 JSValueProtect(context, String_);
3689 JSValueProtect(context, Instance_prototype_);
3690 JSValueProtect(context, Object_prototype_);
3692 JSValueProtect(context, Array_prototype_);
3693 JSValueProtect(context, Array_pop_);
3694 JSValueProtect(context, Array_push_);
3695 JSValueProtect(context, Array_splice_);