1 /* Cycript - Remote 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.
40 #include <substrate.h>
43 #include "cycript.hpp"
45 #include "sig/parse.hpp"
46 #include "sig/ffi_type.hpp"
48 #include "Pooling.hpp"
52 #include <CoreFoundation/CoreFoundation.h>
53 #include <CoreFoundation/CFLogUtilities.h>
54 #include <JavaScriptCore/JSStringRefCF.h>
59 #include <WebKit/WebScriptObject.h>
61 #include <Foundation/Foundation.h>
67 #include <ext/stdio_filebuf.h>
75 #include "Cycript.tab.hh"
81 #define _throw(name, args...) \
82 @throw [NSException exceptionWithName:name reason:[NSString stringWithFormat:@args] userInfo:nil]
84 #define _throw(name, args...) \
88 #define _assert(test) do { \
90 _throw(NSInternalInconsistencyException, "*** _assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__); \
93 #define _trace() do { \
94 fprintf(stderr, "_trace():%u\n", __LINE__); \
100 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
102 #define CYPoolCatch(value) \
103 @catch (NSException *error) { \
104 _saved = [error retain]; \
110 [_saved autorelease]; \
115 #define CYPoolCatch }
119 #define class_getSuperclass GSObjCSuper
120 #define object_getClass GSObjCClass
123 void CYThrow(JSContextRef context, JSValueRef value);
125 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception);
126 JSStringRef CYCopyJSString(const char *value);
128 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value);
130 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)());
131 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
133 /* JavaScript Properties {{{ */
134 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
135 JSValueRef exception(NULL);
136 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
137 CYThrow(context, exception);
141 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
142 JSValueRef exception(NULL);
143 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
144 CYThrow(context, exception);
148 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
149 JSValueRef exception(NULL);
150 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
151 CYThrow(context, exception);
154 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
155 JSValueRef exception(NULL);
156 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
157 CYThrow(context, exception);
160 /* JavaScript Strings {{{ */
161 JSStringRef CYCopyJSString(const char *value) {
162 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
165 JSStringRef CYCopyJSString(JSStringRef value) {
166 return value == NULL ? NULL : JSStringRetain(value);
169 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
170 if (JSValueIsNull(context, value))
172 JSValueRef exception(NULL);
173 JSStringRef string(JSValueToStringCopy(context, value, &exception));
174 CYThrow(context, exception);
184 JSStringRelease(string_);
188 CYJSString(const CYJSString &rhs) :
189 string_(CYCopyJSString(rhs.string_))
193 template <typename Arg0_>
194 CYJSString(Arg0_ arg0) :
195 string_(CYCopyJSString(arg0))
199 template <typename Arg0_, typename Arg1_>
200 CYJSString(Arg0_ arg0, Arg1_ arg1) :
201 string_(CYCopyJSString(arg0, arg1))
205 CYJSString &operator =(const CYJSString &rhs) {
207 string_ = CYCopyJSString(rhs.string_);
220 operator JSStringRef() const {
226 // XXX: this macro is unhygenic
227 #define CYCastCString_(string) ({ \
229 if (string == NULL) \
232 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
233 utf8 = reinterpret_cast<char *>(alloca(size)); \
234 JSStringGetUTF8CString(string, utf8, size); \
239 // XXX: this macro is unhygenic
240 #define CYCastCString(context, value) ({ \
244 else if (JSStringRef string = CYCopyJSString(context, value)) { \
245 utf8 = CYCastCString_(string); \
246 JSStringRelease(string); \
255 /* Objective-C Strings {{{ */
256 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
258 return [value UTF8String];
260 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
261 char *string(new(pool) char[size]);
262 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
263 _throw(NSInternalInconsistencyException, "[NSString getCString:maxLength:encoding:] == NO");
268 JSStringRef CYCopyJSString_(NSString *value) {
270 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
273 return CYCopyJSString(CYPoolCString(pool, value));
277 JSStringRef CYCopyJSString(id value) {
280 // XXX: this definition scares me; is anyone using this?!
281 NSString *string([value description]);
282 return CYCopyJSString_(string);
286 CFStringRef CYCopyCFString(JSStringRef value) {
287 return JSStringCopyCFString(kCFAllocatorDefault, value);
290 CFStringRef CYCopyCFString(const char *value) {
291 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
294 template <typename Type_>
295 NSString *CYCopyNSString(Type_ value) {
296 return (NSString *) CYCopyCFString(value);
299 NSString *CYCopyNSString(const char *value) {
300 return [NSString stringWithUTF8String:value];
303 NSString *CYCopyNSString(JSStringRef value) {
304 return CYCopyNSString(CYCastCString_(value));
308 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
309 return CYCopyNSString(CYJSString(context, value));
312 /* Objective-C Pool Release {{{ */
313 apr_status_t CYPoolRelease_(void *data) {
314 id object(reinterpret_cast<id>(data));
319 id CYPoolRelease_(apr_pool_t *pool, id object) {
322 else if (pool == NULL)
323 return [object autorelease];
325 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
330 template <typename Type_>
331 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
332 return (Type_) CYPoolRelease_(pool, (id) object);
337 static JSGlobalContextRef Context_;
338 static JSObjectRef System_;
339 static JSObjectRef ObjectiveC_;
341 static JSClassRef Functor_;
342 static JSClassRef Instance_;
343 static JSClassRef Internal_;
344 static JSClassRef Message_;
345 static JSClassRef Messages_;
346 static JSClassRef Pointer_;
347 static JSClassRef Runtime_;
348 static JSClassRef Selector_;
349 static JSClassRef Struct_;
351 static JSClassRef ObjectiveC_Classes_;
352 static JSClassRef ObjectiveC_Image_Classes_;
353 static JSClassRef ObjectiveC_Images_;
354 static JSClassRef ObjectiveC_Protocols_;
356 static JSObjectRef Array_;
357 static JSObjectRef Function_;
358 static JSObjectRef String_;
360 static JSStringRef Result_;
362 static JSStringRef length_;
363 static JSStringRef message_;
364 static JSStringRef name_;
365 static JSStringRef prototype_;
366 static JSStringRef toCYON_;
367 static JSStringRef toJSON_;
369 static JSObjectRef Instance_prototype_;
370 static JSObjectRef Object_prototype_;
372 static JSObjectRef Array_prototype_;
373 static JSObjectRef Array_pop_;
374 static JSObjectRef Array_push_;
375 static JSObjectRef Array_splice_;
379 static Class NSCFBoolean_;
380 static Class NSCFType_;
383 static Class NSArray_;
384 static Class NSDictionary_;
385 static Class NSMessageBuilder_;
386 static Class NSZombie_;
387 static Class Object_;
390 static NSArray *Bridge_;
392 static void Finalize(JSObjectRef object) {
393 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
396 class Type_privateData;
406 CYValue(const void *value) :
407 value_(const_cast<void *>(value))
411 CYValue(const CYValue &rhs) :
416 virtual Type_privateData *GetType() const {
425 JSContextRef context_;
429 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
434 JSValueProtect(context_, owner_);
438 JSValueUnprotect(context_, owner_);
441 JSObjectRef GetOwner() const {
447 struct Selector_privateData :
450 Selector_privateData(SEL value) :
455 SEL GetValue() const {
456 return reinterpret_cast<SEL>(value_);
459 virtual Type_privateData *GetType() const;
462 // XXX: trick this out with associated objects!
463 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
465 return Instance_prototype_;
467 // XXX: I need to think through multi-context
468 typedef std::map<id, JSValueRef> CacheMap;
469 static CacheMap cache_;
471 JSValueRef &value(cache_[self]);
475 JSClassRef _class(NULL);
476 JSValueRef prototype;
478 if (self == NSArray_)
479 prototype = Array_prototype_;
480 else if (self == NSDictionary_)
481 prototype = Object_prototype_;
483 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
485 JSObjectRef object(JSObjectMake(context, _class, NULL));
486 JSObjectSetPrototype(context, object, prototype);
488 JSValueProtect(context, object);
498 Transient = (1 << 0),
499 Uninitialized = (1 << 1),
504 Instance(id value, Flags flags) :
510 virtual ~Instance() {
511 if ((flags_ & Transient) == 0)
512 // XXX: does this handle background threads correctly?
513 // XXX: this simply does not work on the console because I'm stupid
514 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
517 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
518 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
519 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
523 id GetValue() const {
524 return reinterpret_cast<id>(value_);
527 bool IsUninitialized() const {
528 return (flags_ & Uninitialized) != 0;
531 virtual Type_privateData *GetType() const;
537 Messages(Class value) :
542 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
543 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
544 if (_class == NSArray_)
546 if (Class super = class_getSuperclass(_class))
547 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
549 JSObjectSetPrototype(context, value, Array_prototype_);*/
553 Class GetValue() const {
554 return reinterpret_cast<Class>(value_);
561 Internal(id value, JSContextRef context, JSObjectRef owner) :
562 CYOwned(value, context, owner)
566 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
567 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
570 id GetValue() const {
571 return reinterpret_cast<id>(value_);
578 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
580 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
581 lhs.name = apr_pstrdup(pool, rhs.name);
582 if (rhs.type == NULL)
585 lhs.type = new(pool) Type;
586 Copy(pool, *lhs.type, *rhs.type);
588 lhs.offset = rhs.offset;
591 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
592 size_t count(rhs.count);
594 lhs.elements = new(pool) Element[count];
595 for (size_t index(0); index != count; ++index)
596 Copy(pool, lhs.elements[index], rhs.elements[index]);
599 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
600 lhs.primitive = rhs.primitive;
601 lhs.name = apr_pstrdup(pool, rhs.name);
602 lhs.flags = rhs.flags;
604 if (sig::IsAggregate(rhs.primitive))
605 Copy(pool, lhs.data.signature, rhs.data.signature);
607 sig::Type *&lht(lhs.data.data.type);
608 sig::Type *&rht(rhs.data.data.type);
613 lht = new(pool) Type;
614 Copy(pool, *lht, *rht);
617 lhs.data.data.size = rhs.data.data.size;
621 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
623 lhs.alignment = rhs.alignment;
625 if (rhs.elements == NULL)
629 while (rhs.elements[count] != NULL)
632 lhs.elements = new(pool) ffi_type *[count + 1];
633 lhs.elements[count] = NULL;
635 for (size_t index(0); index != count; ++index) {
636 // XXX: if these are libffi native then you can just take them
637 ffi_type *ffi(new(pool) ffi_type);
638 lhs.elements[index] = ffi;
639 sig::Copy(pool, *ffi, *rhs.elements[index]);
646 struct CStringMapLess :
647 std::binary_function<const char *, const char *, bool>
649 _finline bool operator ()(const char *lhs, const char *rhs) const {
650 return strcmp(lhs, rhs) < 0;
654 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
659 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
660 switch ([[entry objectAtIndex:0] intValue]) {
662 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
666 sig::Signature signature;
667 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
668 type = signature.elements[0].type;
674 struct Type_privateData :
678 static Type_privateData *Object;
679 static Type_privateData *Selector;
682 static JSClassRef Class_;
687 void Set(sig::Type *type) {
688 type_ = new(pool_) sig::Type;
689 sig::Copy(pool_, *type_, *type);
692 Type_privateData(apr_pool_t *pool, const char *type) :
698 sig::Signature signature;
699 sig::Parse(pool_, &signature, type, &Structor_);
700 type_ = signature.elements[0].type;
703 Type_privateData(sig::Type *type) :
710 Type_privateData(sig::Type *type, ffi_type *ffi) {
711 ffi_ = new(pool_) ffi_type;
712 sig::Copy(pool_, *ffi_, *ffi);
718 ffi_ = new(pool_) ffi_type;
720 sig::Element element;
722 element.type = type_;
725 sig::Signature signature;
726 signature.elements = &element;
730 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
738 JSClassRef Type_privateData::Class_;
741 Type_privateData *Type_privateData::Object;
742 Type_privateData *Type_privateData::Selector;
744 Type_privateData *Instance::GetType() const {
745 return Type_privateData::Object;
748 Type_privateData *Selector_privateData::GetType() const {
749 return Type_privateData::Selector;
756 Type_privateData *type_;
758 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
759 CYOwned(value, context, owner),
760 type_(new(pool_) Type_privateData(type))
765 struct Struct_privateData :
768 Type_privateData *type_;
770 Struct_privateData(JSContextRef context, JSObjectRef owner) :
771 CYOwned(NULL, context, owner)
776 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
777 static TypeMap Types_;
779 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
780 Struct_privateData *internal(new Struct_privateData(context, owner));
781 apr_pool_t *pool(internal->pool_);
782 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
783 internal->type_ = typical;
786 internal->value_ = data;
788 size_t size(typical->GetFFI()->size);
789 void *copy(apr_palloc(internal->pool_, size));
790 memcpy(copy, data, size);
791 internal->value_ = copy;
794 return JSObjectMake(context, Struct_, internal);
797 struct Functor_privateData :
800 sig::Signature signature_;
804 Functor_privateData(const char *type, void (*value)()) :
805 CYValue(reinterpret_cast<void *>(value))
807 sig::Parse(pool_, &signature_, type, &Structor_);
808 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
811 void (*GetValue())() const {
812 return reinterpret_cast<void (*)()>(value_);
816 struct Closure_privateData :
819 JSContextRef context_;
820 JSObjectRef function_;
822 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
823 Functor_privateData(type, NULL),
827 JSValueProtect(context_, function_);
830 virtual ~Closure_privateData() {
831 JSValueUnprotect(context_, function_);
836 struct Message_privateData :
841 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
842 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
848 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
849 Instance::Flags flags;
852 flags = Instance::Transient;
854 flags = Instance::None;
855 object = [object retain];
858 return Instance::Make(context, object, flags);
862 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
863 return JSValueMakeBoolean(context, value);
866 JSValueRef CYCastJSValue(JSContextRef context, double value) {
867 return JSValueMakeNumber(context, value);
870 #define CYCastJSValue_(Type_) \
871 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
872 return JSValueMakeNumber(context, static_cast<double>(value)); \
876 CYCastJSValue_(unsigned int)
877 CYCastJSValue_(long int)
878 CYCastJSValue_(long unsigned int)
879 CYCastJSValue_(long long int)
880 CYCastJSValue_(long long unsigned int)
882 JSValueRef CYJSUndefined(JSContextRef context) {
883 return JSValueMakeUndefined(context);
886 size_t CYGetIndex(const char *value) {
887 if (value[0] != '0') {
889 size_t index(strtoul(value, &end, 10));
890 if (value + strlen(value) == end)
892 } else if (value[1] == '\0')
898 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value);
900 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
901 return CYGetIndex(CYPoolCString(pool, value));
904 bool CYGetOffset(const char *value, ssize_t &index) {
905 if (value[0] != '0') {
907 index = strtol(value, &end, 10);
908 if (value + strlen(value) == end)
910 } else if (value[1] == '\0') {
919 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
920 return CYGetIndex(CYPoolCString(pool, value));
923 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
924 return CYGetOffset(CYPoolCString(pool, value), index);
929 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
931 @interface NSMethodSignature (Cycript)
932 - (NSString *) _typeString;
935 @interface NSObject (Cycript)
937 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
938 - (JSType) cy$JSType;
940 - (NSObject *) cy$toJSON:(NSString *)key;
941 - (NSString *) cy$toCYON;
942 - (NSString *) cy$toKey;
944 - (bool) cy$hasProperty:(NSString *)name;
945 - (NSObject *) cy$getProperty:(NSString *)name;
946 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
947 - (bool) cy$deleteProperty:(NSString *)name;
952 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
955 @interface NSString (Cycript)
956 - (void *) cy$symbol;
962 struct PropertyAttributes {
967 const char *variable;
980 PropertyAttributes(objc_property_t property) :
992 name = property_getName(property);
993 const char *attributes(property_getAttributes(property));
995 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
997 case 'R': readonly = true; break;
998 case 'C': copy = true; break;
999 case '&': retain = true; break;
1000 case 'N': nonatomic = true; break;
1001 case 'G': getter_ = token + 1; break;
1002 case 'S': setter_ = token + 1; break;
1003 case 'V': variable = token + 1; break;
1007 /*if (variable == NULL) {
1008 variable = property_getName(property);
1009 size_t size(strlen(variable));
1010 char *name(new(pool_) char[size + 2]);
1012 memcpy(name + 1, variable, size);
1013 name[size + 1] = '\0';
1018 const char *Getter() {
1019 if (getter_ == NULL)
1020 getter_ = apr_pstrdup(pool_, name);
1024 const char *Setter() {
1025 if (setter_ == NULL && !readonly) {
1026 size_t length(strlen(name));
1028 char *temp(new(pool_) char[length + 5]);
1034 temp[3] = toupper(name[0]);
1035 memcpy(temp + 4, name + 1, length - 1);
1038 temp[length + 3] = ':';
1039 temp[length + 4] = '\0';
1052 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
1053 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
1060 @interface CYWebUndefined : NSObject {
1063 + (CYWebUndefined *) undefined;
1067 @implementation CYWebUndefined
1069 + (CYWebUndefined *) undefined {
1070 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
1076 #define WebUndefined CYWebUndefined
1081 /* Bridge: NSArray {{{ */
1082 @implementation NSArray (Cycript)
1084 - (NSString *) cy$toCYON {
1085 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1086 [json appendString:@"["];
1090 for (id object in self) {
1093 for (size_t index(0), count([self count]); index != count; ++index) {
1094 object = [self objectAtIndex:index];
1097 [json appendString:@","];
1100 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
1101 [json appendString:CYPoolNSCYON(NULL, object)];
1103 [json appendString:@","];
1108 [json appendString:@"]"];
1112 - (bool) cy$hasProperty:(NSString *)name {
1113 if ([name isEqualToString:@"length"])
1116 size_t index(CYGetIndex(NULL, name));
1117 if (index == _not(size_t) || index >= [self count])
1118 return [super cy$hasProperty:name];
1123 - (NSObject *) cy$getProperty:(NSString *)name {
1124 if ([name isEqualToString:@"length"]) {
1125 NSUInteger count([self count]);
1127 return [NSNumber numberWithUnsignedInteger:count];
1129 return [NSNumber numberWithUnsignedInt:count];
1133 size_t index(CYGetIndex(NULL, name));
1134 if (index == _not(size_t) || index >= [self count])
1135 return [super cy$getProperty:name];
1137 return [self objectAtIndex:index];
1142 /* Bridge: NSDictionary {{{ */
1143 @implementation NSDictionary (Cycript)
1145 - (NSString *) cy$toCYON {
1146 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1147 [json appendString:@"{"];
1151 for (id key in self) {
1153 NSEnumerator *keys([self keyEnumerator]);
1154 while (id key = [keys nextObject]) {
1157 [json appendString:@","];
1160 [json appendString:[key cy$toKey]];
1161 [json appendString:@":"];
1162 NSObject *object([self objectForKey:key]);
1163 [json appendString:CYPoolNSCYON(NULL, object)];
1166 [json appendString:@"}"];
1170 - (bool) cy$hasProperty:(NSString *)name {
1171 return [self objectForKey:name] != nil;
1174 - (NSObject *) cy$getProperty:(NSString *)name {
1175 return [self objectForKey:name];
1180 /* Bridge: NSMutableArray {{{ */
1181 @implementation NSMutableArray (Cycript)
1183 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1184 if ([name isEqualToString:@"length"]) {
1185 // XXX: is this not intelligent?
1186 NSNumber *number(reinterpret_cast<NSNumber *>(value));
1188 NSUInteger size([number unsignedIntegerValue]);
1190 NSUInteger size([number unsignedIntValue]);
1192 NSUInteger count([self count]);
1194 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1195 else if (size != count) {
1196 WebUndefined *undefined([WebUndefined undefined]);
1197 for (size_t i(count); i != size; ++i)
1198 [self addObject:undefined];
1203 size_t index(CYGetIndex(NULL, name));
1204 if (index == _not(size_t))
1205 return [super cy$setProperty:name to:value];
1207 id object(value ?: [NSNull null]);
1209 size_t count([self count]);
1211 [self replaceObjectAtIndex:index withObject:object];
1213 if (index != count) {
1214 WebUndefined *undefined([WebUndefined undefined]);
1215 for (size_t i(count); i != index; ++i)
1216 [self addObject:undefined];
1219 [self addObject:object];
1225 - (bool) cy$deleteProperty:(NSString *)name {
1226 size_t index(CYGetIndex(NULL, name));
1227 if (index == _not(size_t) || index >= [self count])
1228 return [super cy$deleteProperty:name];
1229 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1235 /* Bridge: NSMutableDictionary {{{ */
1236 @implementation NSMutableDictionary (Cycript)
1238 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1239 [self setObject:(value ?: [NSNull null]) forKey:name];
1243 - (bool) cy$deleteProperty:(NSString *)name {
1244 if ([self objectForKey:name] == nil)
1247 [self removeObjectForKey:name];
1254 /* Bridge: NSNumber {{{ */
1255 @implementation NSNumber (Cycript)
1257 - (JSType) cy$JSType {
1259 // XXX: this just seems stupid
1260 if ([self class] == NSCFBoolean_)
1261 return kJSTypeBoolean;
1263 return kJSTypeNumber;
1266 - (NSObject *) cy$toJSON:(NSString *)key {
1270 - (NSString *) cy$toCYON {
1271 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1274 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1275 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1280 /* Bridge: NSNull {{{ */
1281 @implementation NSNull (Cycript)
1283 - (JSType) cy$JSType {
1287 - (NSObject *) cy$toJSON:(NSString *)key {
1291 - (NSString *) cy$toCYON {
1297 /* Bridge: NSObject {{{ */
1298 @implementation NSObject (Cycript)
1300 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1301 return CYMakeInstance(context, self, false);
1304 - (JSType) cy$JSType {
1305 return kJSTypeObject;
1308 - (NSObject *) cy$toJSON:(NSString *)key {
1309 return [self description];
1312 - (NSString *) cy$toCYON {
1313 return [[self cy$toJSON:@""] cy$toCYON];
1316 - (NSString *) cy$toKey {
1317 return [self cy$toCYON];
1320 - (bool) cy$hasProperty:(NSString *)name {
1324 - (NSObject *) cy$getProperty:(NSString *)name {
1328 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1332 - (bool) cy$deleteProperty:(NSString *)name {
1338 /* Bridge: NSProxy {{{ */
1339 @implementation NSProxy (Cycript)
1341 - (NSObject *) cy$toJSON:(NSString *)key {
1342 return [self description];
1345 - (NSString *) cy$toCYON {
1346 return [[self cy$toJSON:@""] cy$toCYON];
1351 /* Bridge: NSString {{{ */
1352 @implementation NSString (Cycript)
1354 - (JSType) cy$JSType {
1355 return kJSTypeString;
1358 - (NSObject *) cy$toJSON:(NSString *)key {
1362 - (NSString *) cy$toCYON {
1363 // XXX: this should use the better code from Output.cpp
1365 NSMutableString *json([self mutableCopy]);
1367 [json replaceOccurrencesOfString:@"\\" withString:@"\\\\" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
1368 [json replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
1369 [json replaceOccurrencesOfString:@"\t" withString:@"\\t" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
1370 [json replaceOccurrencesOfString:@"\r" withString:@"\\r" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
1371 [json replaceOccurrencesOfString:@"\n" withString:@"\\n" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
1373 [json appendString:@"\""];
1374 [json insertString:@"\"" atIndex:0];
1379 - (NSString *) cy$toKey {
1380 const char *value([self UTF8String]);
1381 size_t size(strlen(value));
1386 if (DigitRange_[value[0]]) {
1387 size_t index(CYGetIndex(NULL, self));
1388 if (index == _not(size_t))
1391 if (!WordStartRange_[value[0]])
1393 for (size_t i(1); i != size; ++i)
1394 if (!WordEndRange_[value[i]])
1401 return [self cy$toCYON];
1404 - (void *) cy$symbol {
1406 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1411 /* Bridge: WebUndefined {{{ */
1412 @implementation WebUndefined (Cycript)
1414 - (JSType) cy$JSType {
1415 return kJSTypeUndefined;
1418 - (NSObject *) cy$toJSON:(NSString *)key {
1422 - (NSString *) cy$toCYON {
1423 return @"undefined";
1426 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1427 return CYJSUndefined(context);
1433 /* Bridge: CYJSObject {{{ */
1434 @interface CYJSObject : NSMutableDictionary {
1435 JSObjectRef object_;
1436 JSContextRef context_;
1439 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1441 - (NSObject *) cy$toJSON:(NSString *)key;
1443 - (NSUInteger) count;
1444 - (id) objectForKey:(id)key;
1445 - (NSEnumerator *) keyEnumerator;
1446 - (void) setObject:(id)object forKey:(id)key;
1447 - (void) removeObjectForKey:(id)key;
1451 /* Bridge: CYJSArray {{{ */
1452 @interface CYJSArray : NSMutableArray {
1453 JSObjectRef object_;
1454 JSContextRef context_;
1457 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1459 - (NSUInteger) count;
1460 - (id) objectAtIndex:(NSUInteger)index;
1462 - (void) addObject:(id)anObject;
1463 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1464 - (void) removeLastObject;
1465 - (void) removeObjectAtIndex:(NSUInteger)index;
1466 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1475 catch (id error) { \
1476 CYThrow(context, error, exception); \
1479 *exception = CYCastJSValue(context, "catch(...)"); \
1485 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1486 JSValueRef exception(NULL);
1487 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1488 CYThrow(context, exception);
1489 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1490 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1493 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1494 if (!JSValueIsObjectOfClass(context, object, Instance_))
1495 return CYCastNSObject_(pool, context, object);
1497 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1498 return internal->GetValue();
1503 double CYCastDouble(const char *value, size_t size) {
1505 double number(strtod(value, &end));
1506 if (end != value + size)
1511 double CYCastDouble(const char *value) {
1512 return CYCastDouble(value, strlen(value));
1515 double CYCastDouble(JSContextRef context, JSValueRef value) {
1516 JSValueRef exception(NULL);
1517 double number(JSValueToNumber(context, value, &exception));
1518 CYThrow(context, exception);
1523 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
1524 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
1527 template <typename Type_>
1528 NSString *CYCastNSString(apr_pool_t *pool, Type_ value) {
1529 return CYPoolRelease(pool, CYCopyNSString(value));
1533 bool CYCastBool(JSContextRef context, JSValueRef value) {
1534 return JSValueToBoolean(context, value);
1538 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1542 switch (JSType type = JSValueGetType(context, value)) {
1543 case kJSTypeUndefined:
1544 object = [WebUndefined undefined];
1552 case kJSTypeBoolean:
1554 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
1557 object = [[NSNumber alloc] initWithBool:CYCastBool(context, value)];
1563 object = CYCopyNSNumber(context, value);
1568 object = CYCopyNSString(context, value);
1573 // XXX: this might could be more efficient
1574 object = CYCastNSObject(pool, context, (JSObjectRef) value);
1579 _throw(NSInternalInconsistencyException, "JSValueGetType() == 0x%x", type);
1586 return CYPoolRelease(pool, object);
1588 return [object retain];
1591 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1592 return CYNSObject(pool, context, value, true);
1595 id CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1596 return CYNSObject(pool, context, value, false);
1599 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1601 size_t size(JSPropertyNameArrayGetCount(names));
1602 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1603 for (size_t index(0); index != size; ++index)
1604 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1609 void CYThrow(JSContextRef context, JSValueRef value) {
1613 @throw CYCastNSObject(NULL, context, value);
1620 JSValueRef CYJSNull(JSContextRef context) {
1621 return JSValueMakeNull(context);
1624 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1625 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1628 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1629 return CYCastJSValue(context, CYJSString(value));
1633 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1635 return CYJSNull(context);
1636 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1637 return [value cy$JSValueInContext:context];
1639 return CYMakeInstance(context, value, false);
1643 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1644 JSValueRef exception(NULL);
1645 JSObjectRef object(JSValueToObject(context, value, &exception));
1646 CYThrow(context, exception);
1650 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1651 if (exception == NULL)
1653 *exception = CYCastJSValue(context, error);
1656 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1657 JSValueRef exception(NULL);
1658 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1659 CYThrow(context, exception);
1663 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1664 // XXX: this isn't actually correct
1665 return value != NULL && JSValueIsObject(context, value);
1669 @implementation CYJSObject
1671 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1672 if ((self = [super init]) != nil) {
1675 JSValueProtect(context_, object_);
1680 JSValueUnprotect(context_, object_);
1684 - (NSObject *) cy$toJSON:(NSString *)key {
1685 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1686 if (!CYIsCallable(context_, toJSON))
1687 return [super cy$toJSON:key];
1689 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1690 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1691 // XXX: do I really want an NSNull here?!
1692 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1696 - (NSString *) cy$toCYON {
1697 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1698 if (!CYIsCallable(context_, toCYON)) super:
1699 return [super cy$toCYON];
1700 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1701 return CYCastNSString(NULL, CYJSString(context_, value));
1705 - (NSUInteger) count {
1706 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1707 size_t size(JSPropertyNameArrayGetCount(names));
1708 JSPropertyNameArrayRelease(names);
1712 - (id) objectForKey:(id)key {
1713 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1714 if (JSValueIsUndefined(context_, value))
1716 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1719 - (NSEnumerator *) keyEnumerator {
1720 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1721 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1722 JSPropertyNameArrayRelease(names);
1726 - (void) setObject:(id)object forKey:(id)key {
1727 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1730 - (void) removeObjectForKey:(id)key {
1731 JSValueRef exception(NULL);
1732 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1733 CYThrow(context_, exception);
1738 @implementation CYJSArray
1740 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1741 if ((self = [super init]) != nil) {
1744 JSValueProtect(context_, object_);
1749 JSValueUnprotect(context_, object_);
1753 - (NSUInteger) count {
1754 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1757 - (id) objectAtIndex:(NSUInteger)index {
1758 size_t bounds([self count]);
1759 if (index >= bounds)
1760 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1761 JSValueRef exception(NULL);
1762 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1763 CYThrow(context_, exception);
1764 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1767 - (void) addObject:(id)object {
1768 JSValueRef exception(NULL);
1769 JSValueRef arguments[1];
1770 arguments[0] = CYCastJSValue(context_, object);
1771 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1772 CYThrow(context_, exception);
1775 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1776 size_t bounds([self count] + 1);
1777 if (index >= bounds)
1778 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1779 JSValueRef exception(NULL);
1780 JSValueRef arguments[3];
1781 arguments[0] = CYCastJSValue(context_, index);
1782 arguments[1] = CYCastJSValue(context_, 0);
1783 arguments[2] = CYCastJSValue(context_, object);
1784 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1785 CYThrow(context_, exception);
1788 - (void) removeLastObject {
1789 JSValueRef exception(NULL);
1790 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1791 CYThrow(context_, exception);
1794 - (void) removeObjectAtIndex:(NSUInteger)index {
1795 size_t bounds([self count]);
1796 if (index >= bounds)
1797 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1798 JSValueRef exception(NULL);
1799 JSValueRef arguments[2];
1800 arguments[0] = CYCastJSValue(context_, index);
1801 arguments[1] = CYCastJSValue(context_, 1);
1802 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1803 CYThrow(context_, exception);
1806 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1807 size_t bounds([self count]);
1808 if (index >= bounds)
1809 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1810 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1816 NSString *CYCopyNSCYON(id value) {
1822 Class _class(object_getClass(value));
1823 SEL sel(@selector(cy$toCYON));
1825 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
1826 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1827 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1828 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1829 string = [value cy$toCYON];
1832 if (value == NSZombie_)
1833 string = @"_NSZombie_";
1834 else if (_class == NSZombie_)
1835 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1836 // XXX: frowny /in/ the pants
1837 else if (value == NSMessageBuilder_ || value == Object_)
1840 string = [NSString stringWithFormat:@"%@", value];
1843 // XXX: frowny pants
1845 string = @"undefined";
1848 return [string retain];
1851 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1852 if (JSValueIsNull(context, value))
1853 return [@"null" retain];
1857 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1862 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1863 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1866 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1867 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1868 const char *string(CYPoolCString(pool, json));
1875 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1879 JSObjectRef object_;
1887 // XXX: delete object_? ;(
1890 static CYInternal *Get(id self) {
1891 CYInternal *internal(NULL);
1892 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1893 // XXX: do something epic? ;P
1899 static CYInternal *Set(id self) {
1900 CYInternal *internal(NULL);
1901 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1902 if (internal == NULL) {
1903 internal = new CYInternal();
1904 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1907 // XXX: do something epic? ;P
1913 bool HasProperty(JSContextRef context, JSStringRef name) {
1914 if (object_ == NULL)
1916 return JSObjectHasProperty(context, object_, name);
1919 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1920 if (object_ == NULL)
1922 return CYGetProperty(context, object_, name);
1925 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1926 if (object_ == NULL)
1927 object_ = JSObjectMake(context, NULL, NULL);
1928 CYSetProperty(context, object_, name, value);
1934 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1935 Selector_privateData *internal(new Selector_privateData(sel));
1936 return JSObjectMake(context, Selector_, internal);
1940 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1941 Pointer *internal(new Pointer(pointer, context, owner, type));
1942 return JSObjectMake(context, Pointer_, internal);
1945 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1946 Functor_privateData *internal(new Functor_privateData(type, function));
1947 return JSObjectMake(context, Functor_, internal);
1950 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1952 // XXX: this could be much more efficient
1953 const char *string([CYCastNSString(NULL, value) UTF8String]);
1956 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1957 char *string(new(pool) char[size]);
1958 JSStringGetUTF8CString(value, string, size);
1963 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1964 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1967 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1968 return CYGetOffset(CYPoolCString(pool, value), index);
1971 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1972 switch (JSValueGetType(context, value)) {
1975 /*case kJSTypeString:
1976 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1978 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1979 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1980 return internal->value_;
1983 double number(CYCastDouble(context, value));
1984 if (std::isnan(number))
1985 _throw(NSInvalidArgumentException, "cannot convert value to pointer");
1986 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1990 template <typename Type_>
1991 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1992 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1996 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1997 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1998 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1999 return reinterpret_cast<SEL>(internal->value_);
2001 return CYCastPointer<SEL>(context, value);
2005 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
2006 switch (type->primitive) {
2007 case sig::boolean_P:
2008 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
2011 #define CYPoolFFI_(primitive, native) \
2012 case sig::primitive ## _P: \
2013 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
2016 CYPoolFFI_(uchar, unsigned char)
2017 CYPoolFFI_(char, char)
2018 CYPoolFFI_(ushort, unsigned short)
2019 CYPoolFFI_(short, short)
2020 CYPoolFFI_(ulong, unsigned long)
2021 CYPoolFFI_(long, long)
2022 CYPoolFFI_(uint, unsigned int)
2023 CYPoolFFI_(int, int)
2024 CYPoolFFI_(ulonglong, unsigned long long)
2025 CYPoolFFI_(longlong, long long)
2026 CYPoolFFI_(float, float)
2027 CYPoolFFI_(double, double)
2031 case sig::typename_P:
2032 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
2035 case sig::selector_P:
2036 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
2040 case sig::pointer_P:
2041 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
2045 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
2048 case sig::struct_P: {
2049 uint8_t *base(reinterpret_cast<uint8_t *>(data));
2050 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
2051 for (size_t index(0); index != type->data.signature.count; ++index) {
2052 sig::Element *element(&type->data.signature.elements[index]);
2053 ffi_type *field(ffi->elements[index]);
2056 if (aggregate == NULL)
2059 rhs = CYGetProperty(context, aggregate, index);
2060 if (JSValueIsUndefined(context, rhs)) {
2061 if (element->name != NULL)
2062 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
2065 if (JSValueIsUndefined(context, rhs)) undefined:
2066 _throw(NSInvalidArgumentException, "unable to extract structure value");
2070 CYPoolFFI(pool, context, element->type, field, base, rhs);
2072 base += field->size;
2080 fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
2085 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
2088 switch (type->primitive) {
2089 case sig::boolean_P:
2090 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
2093 #define CYFromFFI_(primitive, native) \
2094 case sig::primitive ## _P: \
2095 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
2098 CYFromFFI_(uchar, unsigned char)
2099 CYFromFFI_(char, char)
2100 CYFromFFI_(ushort, unsigned short)
2101 CYFromFFI_(short, short)
2102 CYFromFFI_(ulong, unsigned long)
2103 CYFromFFI_(long, long)
2104 CYFromFFI_(uint, unsigned int)
2105 CYFromFFI_(int, int)
2106 CYFromFFI_(ulonglong, unsigned long long)
2107 CYFromFFI_(longlong, long long)
2108 CYFromFFI_(float, float)
2109 CYFromFFI_(double, double)
2112 case sig::object_P: {
2113 if (id object = *reinterpret_cast<id *>(data)) {
2114 value = CYCastJSValue(context, object);
2120 case sig::typename_P:
2121 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
2124 case sig::selector_P:
2125 if (SEL sel = *reinterpret_cast<SEL *>(data))
2126 value = CYMakeSelector(context, sel);
2131 case sig::pointer_P:
2132 if (void *pointer = *reinterpret_cast<void **>(data))
2133 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
2138 if (char *utf8 = *reinterpret_cast<char **>(data))
2139 value = CYCastJSValue(context, utf8);
2144 value = CYMakeStruct(context, data, type, ffi, owner);
2148 value = CYJSUndefined(context);
2152 value = CYJSNull(context);
2156 fprintf(stderr, "CYFromFFI(%c)\n", type->primitive);
2163 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
2164 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
2168 method_getReturnType(method, type, sizeof(type));
2173 // XXX: possibly use a more "awesome" check?
2177 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, objc_method *method) {
2179 return method_getTypeEncoding(method);
2180 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2181 return CYPoolCString(pool, type);
2186 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2187 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2189 JSContextRef context(internal->context_);
2191 size_t count(internal->cif_.nargs);
2192 JSValueRef values[count];
2194 for (size_t index(0); index != count; ++index)
2195 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2197 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2198 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2201 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2202 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2204 JSContextRef context(internal->context_);
2206 size_t count(internal->cif_.nargs);
2207 JSValueRef values[count];
2209 for (size_t index(0); index != count; ++index)
2210 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2212 JSObjectRef _this(CYCastJSObject(context, values[0]));
2214 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2215 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2218 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2219 // XXX: in case of exceptions this will leak
2220 // XXX: in point of fact, this may /need/ to leak :(
2221 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2223 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2224 NULL, sizeof(ffi_closure),
2225 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2229 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2230 _assert(status == FFI_OK);
2232 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2234 internal->value_ = closure;
2239 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2240 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2241 return JSObjectMake(context, Functor_, internal);
2244 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2245 JSValueRef exception(NULL);
2246 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2247 CYThrow(context, exception);
2250 JSObjectRef function(CYCastJSObject(context, value));
2251 return CYMakeFunctor(context, function, type);
2253 void (*function)()(CYCastPointer<void (*)()>(context, value));
2254 return CYMakeFunctor(context, function, type);
2259 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2260 Message_privateData *internal(new Message_privateData(sel, type, imp));
2261 return JSObjectMake(context, Message_, internal);
2264 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2265 JSObjectRef function(CYCastJSObject(context, value));
2266 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2267 return reinterpret_cast<IMP>(internal->GetValue());
2270 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2271 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2272 Class _class(internal->GetValue());
2275 const char *name(CYPoolCString(pool, property));
2277 if (SEL sel = sel_getUid(name))
2278 if (class_getInstanceMethod(_class, sel) != NULL)
2284 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2285 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2286 Class _class(internal->GetValue());
2289 const char *name(CYPoolCString(pool, property));
2291 if (SEL sel = sel_getUid(name))
2292 if (objc_method *method = class_getInstanceMethod(_class, sel))
2293 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2298 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2299 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2300 Class _class(internal->GetValue());
2303 const char *name(CYPoolCString(pool, property));
2305 SEL sel(sel_registerName(name));
2307 objc_method *method(class_getInstanceMethod(_class, sel));
2312 if (JSValueIsObjectOfClass(context, value, Message_)) {
2313 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2314 type = sig::Unparse(pool, &message->signature_);
2315 imp = reinterpret_cast<IMP>(message->GetValue());
2317 type = CYPoolTypeEncoding(pool, _class, sel, method);
2318 imp = CYMakeMessage(context, value, type);
2322 method_setImplementation(method, imp);
2324 class_replaceMethod(_class, sel, imp, type);
2330 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2331 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2332 Class _class(internal->GetValue());
2335 const char *name(CYPoolCString(pool, property));
2337 if (SEL sel = sel_getUid(name))
2338 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
2339 objc_method_list list = {NULL, 1, {method}};
2340 class_removeMethods(_class, &list);
2348 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2349 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2350 Class _class(internal->GetValue());
2353 objc_method **data(class_copyMethodList(_class, &size));
2354 for (size_t i(0); i != size; ++i)
2355 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2359 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2360 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2361 id self(internal->GetValue());
2363 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2367 NSString *name(CYCastNSString(pool, property));
2369 if (CYInternal *internal = CYInternal::Get(self))
2370 if (internal->HasProperty(context, property))
2373 Class _class(object_getClass(self));
2376 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2377 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2378 if ([self cy$hasProperty:name])
2380 } CYPoolCatch(false)
2382 const char *string(CYPoolCString(pool, name));
2384 if (class_getProperty(_class, string) != NULL)
2387 if (SEL sel = sel_getUid(string))
2388 if (CYImplements(self, _class, sel, true))
2394 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2395 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2396 id self(internal->GetValue());
2398 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2399 return Internal::Make(context, self, object);
2403 NSString *name(CYCastNSString(pool, property));
2405 if (CYInternal *internal = CYInternal::Get(self))
2406 if (JSValueRef value = internal->GetProperty(context, property))
2410 if (NSObject *data = [self cy$getProperty:name])
2411 return CYCastJSValue(context, data);
2414 const char *string(CYPoolCString(pool, name));
2415 Class _class(object_getClass(self));
2418 if (objc_property_t property = class_getProperty(_class, string)) {
2419 PropertyAttributes attributes(property);
2420 SEL sel(sel_registerName(attributes.Getter()));
2421 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2425 if (SEL sel = sel_getUid(string))
2426 if (CYImplements(self, _class, sel, true))
2427 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2433 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2434 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2435 id self(internal->GetValue());
2440 NSString *name(CYCastNSString(pool, property));
2441 NSObject *data(CYCastNSObject(pool, context, value));
2444 if ([self cy$setProperty:name to:data])
2448 const char *string(CYPoolCString(pool, name));
2449 Class _class(object_getClass(self));
2452 if (objc_property_t property = class_getProperty(_class, string)) {
2453 PropertyAttributes attributes(property);
2454 if (const char *setter = attributes.Setter()) {
2455 SEL sel(sel_registerName(setter));
2456 JSValueRef arguments[1] = {value};
2457 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2463 size_t length(strlen(string));
2465 char set[length + 5];
2471 if (string[0] != '\0') {
2472 set[3] = toupper(string[0]);
2473 memcpy(set + 4, string + 1, length - 1);
2476 set[length + 3] = ':';
2477 set[length + 4] = '\0';
2479 if (SEL sel = sel_getUid(set))
2480 if (CYImplements(self, _class, sel, false)) {
2481 JSValueRef arguments[1] = {value};
2482 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2485 if (CYInternal *internal = CYInternal::Set(self)) {
2486 internal->SetProperty(context, property, value);
2494 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2495 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2496 id self(internal->GetValue());
2500 NSString *name(CYCastNSString(NULL, property));
2501 return [self cy$deleteProperty:name];
2506 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2507 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2508 id self(internal->GetValue());
2511 Class _class(object_getClass(self));
2515 objc_property_t *data(class_copyPropertyList(_class, &size));
2516 for (size_t i(0); i != size; ++i)
2517 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2522 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2524 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2525 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2530 static bool CYIsClass(id self) {
2531 // XXX: this is a lame object_isClass
2532 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2535 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2536 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2537 Class _class(internal->GetValue());
2538 if (!CYIsClass(_class))
2541 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2542 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2543 // XXX: this isn't always safe
2545 return [linternal->GetValue() isKindOfClass:_class];
2552 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2553 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2556 id self(internal->GetValue());
2557 const char *name(CYPoolCString(pool, property));
2559 if (object_getInstanceVariable(self, name, NULL) != NULL)
2565 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2566 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2570 id self(internal->GetValue());
2571 const char *name(CYPoolCString(pool, property));
2573 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2574 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2575 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2582 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2583 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2587 id self(internal->GetValue());
2588 const char *name(CYPoolCString(pool, property));
2590 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2591 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2592 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2600 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2601 if (Class super = class_getSuperclass(_class))
2602 Internal_getPropertyNames_(super, names);
2605 Ivar *data(class_copyIvarList(_class, &size));
2606 for (size_t i(0); i != size; ++i)
2607 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2611 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2612 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2615 id self(internal->GetValue());
2616 Class _class(object_getClass(self));
2618 Internal_getPropertyNames_(_class, names);
2621 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2622 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2623 return internal->GetOwner();
2627 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2628 Type_privateData *typical(internal->type_);
2629 sig::Type *type(typical->type_);
2633 const char *name(CYPoolCString(pool, property));
2634 size_t length(strlen(name));
2635 double number(CYCastDouble(name, length));
2637 size_t count(type->data.signature.count);
2639 if (std::isnan(number)) {
2640 if (property == NULL)
2643 sig::Element *elements(type->data.signature.elements);
2645 for (size_t local(0); local != count; ++local) {
2646 sig::Element *element(&elements[local]);
2647 if (element->name != NULL && strcmp(name, element->name) == 0) {
2655 index = static_cast<ssize_t>(number);
2656 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2661 ffi_type **elements(typical->GetFFI()->elements);
2663 base = reinterpret_cast<uint8_t *>(internal->value_);
2664 for (ssize_t local(0); local != index; ++local)
2665 base += elements[local]->size;
2670 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2671 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2672 Type_privateData *typical(internal->type_);
2674 ffi_type *ffi(typical->GetFFI());
2676 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2677 base += ffi->size * index;
2679 JSObjectRef owner(internal->GetOwner() ?: object);
2682 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2686 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2688 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2689 Type_privateData *typical(internal->type_);
2691 if (typical->type_ == NULL)
2695 if (!CYGetOffset(pool, property, offset))
2698 return Pointer_getIndex(context, object, offset, exception);
2701 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2702 return Pointer_getIndex(context, object, 0, exception);
2705 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2706 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2707 Type_privateData *typical(internal->type_);
2709 ffi_type *ffi(typical->GetFFI());
2711 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2712 base += ffi->size * index;
2715 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2720 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2722 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2723 Type_privateData *typical(internal->type_);
2725 if (typical->type_ == NULL)
2729 if (!CYGetOffset(pool, property, offset))
2732 return Pointer_setIndex(context, object, offset, value, exception);
2735 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2736 return Pointer_setIndex(context, object, 0, value, exception);
2739 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2740 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2741 Type_privateData *typical(internal->type_);
2742 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2745 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2747 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2748 Type_privateData *typical(internal->type_);
2753 if (!Index_(pool, internal, property, index, base))
2756 JSObjectRef owner(internal->GetOwner() ?: object);
2759 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2763 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2765 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2766 Type_privateData *typical(internal->type_);
2771 if (!Index_(pool, internal, property, index, base))
2775 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2780 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2781 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2782 Type_privateData *typical(internal->type_);
2783 sig::Type *type(typical->type_);
2788 size_t count(type->data.signature.count);
2789 sig::Element *elements(type->data.signature.elements);
2793 for (size_t index(0); index != count; ++index) {
2795 name = elements[index].name;
2798 sprintf(number, "%lu", index);
2802 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2806 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)()) {
2808 if (setups + count != signature->count - 1)
2809 _throw(NSInvalidArgumentException, "incorrect number of arguments to ffi function");
2811 size_t size(setups + count);
2813 memcpy(values, setup, sizeof(void *) * setups);
2815 for (size_t index(setups); index != size; ++index) {
2816 sig::Element *element(&signature->elements[index + 1]);
2817 ffi_type *ffi(cif->arg_types[index]);
2819 values[index] = new(pool) uint8_t[ffi->size];
2820 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2823 uint8_t value[cif->rtype->size];
2824 ffi_call(cif, function, value, values);
2826 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2830 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2833 NSString *name(CYCastNSString(pool, property));
2834 if (Class _class = NSClassFromString(name))
2835 return CYMakeInstance(context, _class, true);
2840 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2841 size_t size(objc_getClassList(NULL, 0));
2842 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2845 size_t writ(objc_getClassList(data, size));
2848 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2854 for (size_t i(0); i != writ; ++i)
2855 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2861 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2862 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2866 const char *name(CYPoolCString(pool, property));
2868 const char **data(objc_copyClassNamesForImage(internal, &size));
2870 for (size_t i(0); i != size; ++i)
2871 if (strcmp(name, data[i]) == 0) {
2872 if (Class _class = objc_getClass(name)) {
2873 value = CYMakeInstance(context, _class, true);
2885 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2886 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2888 const char **data(objc_copyClassNamesForImage(internal, &size));
2889 for (size_t i(0); i != size; ++i)
2890 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2894 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2897 const char *name(CYPoolCString(pool, property));
2899 const char **data(objc_copyImageNames(&size));
2900 for (size_t i(0); i != size; ++i)
2901 if (strcmp(name, data[i]) == 0) {
2910 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2911 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2916 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2918 const char **data(objc_copyImageNames(&size));
2919 for (size_t i(0); i != size; ++i)
2920 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2924 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2927 NSString *name(CYCastNSString(pool, property));
2928 if (Protocol *protocol = NSProtocolFromString(name))
2929 return CYMakeInstance(context, protocol, true);
2934 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2936 Protocol **data(objc_copyProtocolList(&size));
2937 for (size_t i(0); i != size; ++i)
2938 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2942 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
2943 Type_privateData *internal(new Type_privateData(NULL, type));
2944 return JSObjectMake(context, Type_privateData::Class_, internal);
2947 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
2948 Type_privateData *internal(new Type_privateData(type));
2949 return JSObjectMake(context, Type_privateData::Class_, internal);
2952 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2953 if (JSStringIsEqualToUTF8CString(property, "nil"))
2954 return Instance::Make(context, nil);
2958 NSString *name(CYCastNSString(pool, property));
2959 if (Class _class = NSClassFromString(name))
2960 return CYMakeInstance(context, _class, true);
2961 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2962 switch ([[entry objectAtIndex:0] intValue]) {
2964 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2966 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2968 // XXX: this is horrendously inefficient
2969 sig::Signature signature;
2970 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2972 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2973 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2975 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
2976 switch ([[entry objectAtIndex:0] intValue]) {
2977 // XXX: implement case 0
2979 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
2985 static bool stret(ffi_type *ffi_type) {
2986 return ffi_type->type == FFI_TYPE_STRUCT && (
2987 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2988 struct_forward_array[ffi_type->size] != 0
2993 int *_NSGetArgc(void);
2994 char ***_NSGetArgv(void);
2997 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3002 printf("%s\n", CYCastCString(context, arguments[0]));
3003 return CYJSUndefined(context);
3007 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
3010 Class _class(object_getClass(self));
3011 if (objc_method *method = class_getInstanceMethod(_class, _cmd))
3012 type = method_getTypeEncoding(method);
3016 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
3018 _throw(NSInvalidArgumentException, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3019 type = CYPoolCString(pool, [method _typeString]);
3028 sig::Signature signature;
3029 sig::Parse(pool, &signature, type, &Structor_);
3032 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3034 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
3035 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3038 static size_t Nonce_(0);
3040 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3042 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
3043 return CYCastJSValue(context, name);
3046 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3056 _throw(NSInvalidArgumentException, "too few arguments to objc_msgSend");
3058 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
3059 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3060 self = internal->GetValue();
3061 uninitialized = internal->IsUninitialized();
3063 internal->value_ = nil;
3065 self = CYCastNSObject(pool, context, arguments[0]);
3066 uninitialized = false;
3070 return CYJSNull(context);
3072 _cmd = CYCastSEL(context, arguments[1]);
3075 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
3079 /* Hook: objc_registerClassPair {{{ */
3080 // XXX: replace this with associated objects
3082 MSHook(void, CYDealloc, id self, SEL sel) {
3083 CYInternal *internal;
3084 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
3085 if (internal != NULL)
3087 _CYDealloc(self, sel);
3090 MSHook(void, objc_registerClassPair, Class _class) {
3091 Class super(class_getSuperclass(_class));
3092 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
3093 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
3094 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
3097 _objc_registerClassPair(_class);
3100 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3103 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3105 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3106 if (value == NULL || !CYIsClass(value))
3107 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3108 Class _class((Class) value);
3109 $objc_registerClassPair(_class);
3110 return CYJSUndefined(context);
3116 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3117 JSGarbageCollect(context);
3118 return CYJSUndefined(context);
3122 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3123 JSValueRef setup[count + 2];
3126 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
3127 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
3130 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3132 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
3134 // XXX: handle Instance::Uninitialized?
3135 id self(CYCastNSObject(pool, context, _this));
3139 setup[1] = &internal->sel_;
3141 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3145 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3147 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
3148 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3151 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3154 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector constructor");
3155 const char *name(CYCastCString(context, arguments[0]));
3156 return CYMakeSelector(context, sel_registerName(name));
3160 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3163 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3165 void *value(CYCastPointer<void *>(context, arguments[0]));
3166 const char *type(CYCastCString(context, arguments[1]));
3170 sig::Signature signature;
3171 sig::Parse(pool, &signature, type, &Structor_);
3173 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
3177 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3180 _throw(NSInvalidArgumentException, "incorrect number of arguments to Type constructor");
3181 const char *type(CYCastCString(context, arguments[0]));
3182 return CYMakeType(context, type);
3186 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3187 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3192 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3193 type.primitive = sig::pointer_P;
3194 type.data.data.size = 0;
3196 size_t index(CYGetIndex(NULL, property));
3197 if (index == _not(size_t))
3199 type.primitive = sig::array_P;
3200 type.data.data.size = index;
3206 type.data.data.type = internal->type_;
3208 return CYMakeType(context, &type);
3212 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3213 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3217 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3218 sig::Type *type(internal->type_);
3219 ffi_type *ffi(internal->GetFFI());
3221 uint8_t value[ffi->size];
3223 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3224 return CYFromFFI(context, type, ffi, value);
3228 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3231 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3232 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3234 sig::Type *type(internal->type_);
3237 if (type->primitive != sig::array_P)
3240 size = type->data.data.size;
3241 type = type->data.data.type;
3244 void *value(malloc(internal->GetFFI()->size));
3245 return CYMakePointer(context, value, type, NULL, NULL);
3250 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3253 _throw(NSInvalidArgumentException, "incorrect number of arguments to Instance constructor");
3254 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3255 return Instance::Make(context, self);
3260 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3263 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3264 const char *type(CYCastCString(context, arguments[1]));
3265 return CYMakeFunctor(context, arguments[0], type);
3269 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3270 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3271 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3274 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3275 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3276 Type_privateData *typical(internal->GetType());
3281 if (typical == NULL) {
3285 type = typical->type_;
3286 ffi = typical->ffi_;
3289 return CYMakePointer(context, &internal->value_, type, ffi, object);
3292 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3293 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3296 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3300 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3301 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3304 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3305 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3307 sprintf(string, "%p", internal->value_);
3310 return CYCastJSValue(context, string);
3315 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3316 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3317 return Instance::Make(context, object_getClass(internal->GetValue()));
3320 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3321 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3322 id self(internal->GetValue());
3323 if (!CYIsClass(self))
3324 return CYJSUndefined(context);
3326 return CYGetClassPrototype(context, self);
3330 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3331 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3332 id self(internal->GetValue());
3333 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3334 return CYJSUndefined(context);
3335 return Messages::Make(context, self);
3338 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3339 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3342 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3346 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
3351 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3352 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3355 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3359 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3360 // XXX: check for support of cy$toJSON?
3361 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3366 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3367 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3370 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3374 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3379 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3380 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3383 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3387 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3388 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3391 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3392 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3393 const char *name(sel_getName(internal->GetValue()));
3397 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3402 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3405 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector.type");
3407 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3408 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3409 if (value == NULL) lookup:
3410 // XXX: do a lookup of some kind
3411 return CYJSNull(context);
3412 else if (!CYIsClass(value))
3413 _throw(NSInvalidArgumentException, "Selector.type takes a Class");
3415 Class _class((Class) value);
3416 SEL sel(internal->GetValue());
3417 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
3418 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3419 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3426 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3428 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3430 const char *type(sig::Unparse(pool, internal->type_));
3431 return CYCastJSValue(context, CYJSString(type));
3435 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3437 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3439 const char *type(sig::Unparse(pool, internal->type_));
3440 size_t size(strlen(type));
3441 char *cyon(new(pool) char[12 + size + 1]);
3442 memcpy(cyon, "new Type(\"", 10);
3443 cyon[12 + size] = '\0';
3444 cyon[12 + size - 2] = '"';
3445 cyon[12 + size - 1] = ')';
3446 memcpy(cyon + 10, type, size);
3447 return CYCastJSValue(context, CYJSString(cyon));
3451 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3452 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3455 static JSStaticValue CYValue_staticValues[2] = {
3456 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3457 {NULL, NULL, NULL, 0}
3460 static JSStaticValue Pointer_staticValues[2] = {
3461 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3462 {NULL, NULL, NULL, 0}
3465 static JSStaticFunction Pointer_staticFunctions[4] = {
3466 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3467 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3468 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3472 static JSStaticFunction Struct_staticFunctions[2] = {
3473 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3477 static JSStaticFunction Functor_staticFunctions[4] = {
3478 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3479 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3480 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3485 static JSStaticValue Instance_staticValues[5] = {
3486 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3487 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3488 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3489 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3490 {NULL, NULL, NULL, 0}
3493 static JSStaticFunction Instance_staticFunctions[5] = {
3494 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3495 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3496 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3497 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3501 static JSStaticFunction Internal_staticFunctions[2] = {
3502 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3506 static JSStaticFunction Selector_staticFunctions[5] = {
3507 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3508 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3509 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3510 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3515 static JSStaticFunction Type_staticFunctions[4] = {
3516 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3517 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3518 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3522 void CYSetArgs(int argc, const char *argv[]) {
3523 JSContextRef context(CYGetJSContext());
3524 JSValueRef args[argc];
3525 for (int i(0); i != argc; ++i)
3526 args[i] = CYCastJSValue(context, argv[i]);
3527 JSValueRef exception(NULL);
3528 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3529 CYThrow(context, exception);
3530 CYSetProperty(context, System_, CYJSString("args"), array);
3533 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3534 return JSContextGetGlobalObject(context);
3537 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3538 JSContextRef context(CYGetJSContext());
3539 JSValueRef exception(NULL), result;
3542 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3543 } catch (const char *error) {
3547 if (exception != NULL) { error:
3552 if (JSValueIsUndefined(context, result))
3558 json = CYPoolCCYON(pool, context, result, &exception);
3559 } catch (const char *error) {
3563 if (exception != NULL)
3566 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3570 static apr_pool_t *Pool_;
3572 apr_pool_t *CYGetGlobalPool() {
3576 MSInitialize { _pooled
3577 _aprcall(apr_initialize());
3578 _aprcall(apr_pool_create(&Pool_, NULL));
3580 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3583 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3584 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3587 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3588 NSCFType_ = objc_getClass("NSCFType");
3591 NSArray_ = objc_getClass("NSArray");
3592 NSDictionary_ = objc_getClass("NSDictonary");
3593 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3594 NSZombie_ = objc_getClass("_NSZombie_");
3595 Object_ = objc_getClass("Object");
3599 JSGlobalContextRef CYGetJSContext() {
3600 if (Context_ == NULL) {
3601 JSClassDefinition definition;
3603 definition = kJSClassDefinitionEmpty;
3604 definition.className = "Functor";
3605 definition.staticFunctions = Functor_staticFunctions;
3606 definition.callAsFunction = &Functor_callAsFunction;
3607 definition.finalize = &Finalize;
3608 Functor_ = JSClassCreate(&definition);
3610 definition = kJSClassDefinitionEmpty;
3611 definition.className = "Pointer";
3612 definition.staticValues = Pointer_staticValues;
3613 definition.staticFunctions = Pointer_staticFunctions;
3614 definition.getProperty = &Pointer_getProperty;
3615 definition.setProperty = &Pointer_setProperty;
3616 definition.finalize = &Finalize;
3617 Pointer_ = JSClassCreate(&definition);
3619 definition = kJSClassDefinitionEmpty;
3620 definition.className = "Selector";
3621 definition.staticValues = CYValue_staticValues;
3622 definition.staticFunctions = Selector_staticFunctions;
3623 definition.callAsFunction = &Selector_callAsFunction;
3624 definition.finalize = &Finalize;
3625 Selector_ = JSClassCreate(&definition);
3627 definition = kJSClassDefinitionEmpty;
3628 definition.className = "Struct";
3629 definition.staticFunctions = Struct_staticFunctions;
3630 definition.getProperty = &Struct_getProperty;
3631 definition.setProperty = &Struct_setProperty;
3632 definition.getPropertyNames = &Struct_getPropertyNames;
3633 definition.finalize = &Finalize;
3634 Struct_ = JSClassCreate(&definition);
3636 definition = kJSClassDefinitionEmpty;
3637 definition.className = "Type";
3638 definition.staticFunctions = Type_staticFunctions;
3639 definition.getProperty = &Type_getProperty;
3640 definition.callAsFunction = &Type_callAsFunction;
3641 definition.callAsConstructor = &Type_callAsConstructor;
3642 definition.finalize = &Finalize;
3643 Type_privateData::Class_ = JSClassCreate(&definition);
3645 definition = kJSClassDefinitionEmpty;
3646 definition.className = "Runtime";
3647 definition.getProperty = &Runtime_getProperty;
3648 Runtime_ = JSClassCreate(&definition);
3650 definition = kJSClassDefinitionEmpty;
3651 //definition.getProperty = &Global_getProperty;
3652 JSClassRef Global(JSClassCreate(&definition));
3654 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3656 JSObjectRef global(CYGetGlobalObject(context));
3658 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3660 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3661 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3662 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3664 length_ = JSStringCreateWithUTF8CString("length");
3665 message_ = JSStringCreateWithUTF8CString("message");
3666 name_ = JSStringCreateWithUTF8CString("name");
3667 prototype_ = JSStringCreateWithUTF8CString("prototype");
3668 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3669 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3671 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3672 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3674 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3675 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3676 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3677 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3679 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3681 /* Objective-C Classes {{{ */
3683 definition = kJSClassDefinitionEmpty;
3684 definition.className = "Instance";
3685 definition.staticValues = Instance_staticValues;
3686 definition.staticFunctions = Instance_staticFunctions;
3687 definition.hasProperty = &Instance_hasProperty;
3688 definition.getProperty = &Instance_getProperty;
3689 definition.setProperty = &Instance_setProperty;
3690 definition.deleteProperty = &Instance_deleteProperty;
3691 definition.getPropertyNames = &Instance_getPropertyNames;
3692 definition.callAsConstructor = &Instance_callAsConstructor;
3693 definition.hasInstance = &Instance_hasInstance;
3694 definition.finalize = &Finalize;
3695 Instance_ = JSClassCreate(&definition);
3697 definition = kJSClassDefinitionEmpty;
3698 definition.className = "Internal";
3699 definition.staticFunctions = Internal_staticFunctions;
3700 definition.hasProperty = &Internal_hasProperty;
3701 definition.getProperty = &Internal_getProperty;
3702 definition.setProperty = &Internal_setProperty;
3703 definition.getPropertyNames = &Internal_getPropertyNames;
3704 definition.finalize = &Finalize;
3705 Internal_ = JSClassCreate(&definition);
3707 definition = kJSClassDefinitionEmpty;
3708 definition.className = "Message";
3709 definition.staticFunctions = Functor_staticFunctions;
3710 definition.callAsFunction = &Message_callAsFunction;
3711 definition.finalize = &Finalize;
3712 Message_ = JSClassCreate(&definition);
3714 definition = kJSClassDefinitionEmpty;
3715 definition.className = "Messages";
3716 definition.hasProperty = &Messages_hasProperty;
3717 definition.getProperty = &Messages_getProperty;
3718 definition.setProperty = &Messages_setProperty;
3720 definition.deleteProperty = &Messages_deleteProperty;
3722 definition.getPropertyNames = &Messages_getPropertyNames;
3723 definition.finalize = &Finalize;
3724 Messages_ = JSClassCreate(&definition);
3725 definition = kJSClassDefinitionEmpty;
3727 definition.className = "ObjectiveC::Classes";
3728 definition.getProperty = &ObjectiveC_Classes_getProperty;
3729 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3730 ObjectiveC_Classes_ = JSClassCreate(&definition);
3732 definition = kJSClassDefinitionEmpty;
3733 definition.className = "ObjectiveC::Images";
3734 definition.getProperty = &ObjectiveC_Images_getProperty;
3735 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3736 ObjectiveC_Images_ = JSClassCreate(&definition);
3738 definition = kJSClassDefinitionEmpty;
3739 definition.className = "ObjectiveC::Image::Classes";
3740 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3741 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3742 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3744 definition = kJSClassDefinitionEmpty;
3745 definition.className = "ObjectiveC::Protocols";
3746 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3747 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3748 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3750 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3751 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3753 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3754 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3755 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3757 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3758 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3759 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3761 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3762 JSValueProtect(context, Instance_prototype_);
3764 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3765 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3767 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3768 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3772 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3773 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3774 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3775 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3777 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3778 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3779 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
3781 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3785 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3789 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
3790 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
3791 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
3793 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3795 System_ = JSObjectMake(context, NULL, NULL);
3796 CYSetProperty(context, global, CYJSString("system"), System_);
3797 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3798 //CYSetProperty(context, System_, CYJSString("global"), global);
3800 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3802 Result_ = JSStringCreateWithUTF8CString("_");
3804 JSValueProtect(context, Array_);
3805 JSValueProtect(context, Function_);
3806 JSValueProtect(context, String_);
3808 JSValueProtect(context, Object_prototype_);
3810 JSValueProtect(context, Array_prototype_);
3811 JSValueProtect(context, Array_pop_);
3812 JSValueProtect(context, Array_push_);
3813 JSValueProtect(context, Array_splice_);