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>
45 #include "cycript.hpp"
47 #include "sig/parse.hpp"
48 #include "sig/ffi_type.hpp"
50 #include "Pooling.hpp"
54 #include <CoreFoundation/CoreFoundation.h>
55 #include <CoreFoundation/CFLogUtilities.h>
56 #include <JavaScriptCore/JSStringRefCF.h>
61 #include <WebKit/WebScriptObject.h>
63 #include <Foundation/Foundation.h>
69 #include <ext/stdio_filebuf.h>
77 #include "Cycript.tab.hh"
83 #define _throw(name, args...) \
84 @throw [NSException exceptionWithName:name reason:[NSString stringWithFormat:@args] userInfo:nil]
86 #define _throw(name, args...) \
90 #define _assert(test) do { \
92 _throw(NSInternalInconsistencyException, "*** _assert(%s):%s(%u):%s [errno=%d]", #test, __FILE__, __LINE__, __FUNCTION__, errno); \
95 #define _trace() do { \
96 fprintf(stderr, "_trace():%u\n", __LINE__); \
102 @catch (NSException *error) { \
103 CYThrow(context, error, exception); \
111 catch (NSException *error) { \
112 CYThrow(context, error, exception); \
115 *exception = CYCastJSValue(context, "catch(...)"); \
121 #define CYPoolTry { \
123 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
125 #define CYPoolCatch(value) \
126 @catch (NSException *error) { \
127 _saved = [error retain]; \
133 [_saved autorelease]; \
138 #define CYPoolCatch }
142 #define class_getSuperclass GSObjCSuper
143 #define object_getClass GSObjCClass
146 void CYThrow(JSContextRef context, JSValueRef value);
148 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception);
149 JSStringRef CYCopyJSString(const char *value);
151 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value);
153 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)());
154 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
156 struct CYUTF8String {
160 CYUTF8String(const char *data, size_t size) :
167 struct CYUTF16String {
168 const uint16_t *data;
171 CYUTF16String(const uint16_t *data, size_t size) :
178 /* JavaScript Properties {{{ */
179 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
180 JSValueRef exception(NULL);
181 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
182 CYThrow(context, exception);
186 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
187 JSValueRef exception(NULL);
188 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
189 CYThrow(context, exception);
193 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
194 JSValueRef exception(NULL);
195 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
196 CYThrow(context, exception);
199 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
200 JSValueRef exception(NULL);
201 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
202 CYThrow(context, exception);
205 /* JavaScript Strings {{{ */
206 JSStringRef CYCopyJSString(const char *value) {
207 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
210 JSStringRef CYCopyJSString(JSStringRef value) {
211 return value == NULL ? NULL : JSStringRetain(value);
214 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
215 if (JSValueIsNull(context, value))
217 JSValueRef exception(NULL);
218 JSStringRef string(JSValueToStringCopy(context, value, &exception));
219 CYThrow(context, exception);
229 JSStringRelease(string_);
233 CYJSString(const CYJSString &rhs) :
234 string_(CYCopyJSString(rhs.string_))
238 template <typename Arg0_>
239 CYJSString(Arg0_ arg0) :
240 string_(CYCopyJSString(arg0))
244 template <typename Arg0_, typename Arg1_>
245 CYJSString(Arg0_ arg0, Arg1_ arg1) :
246 string_(CYCopyJSString(arg0, arg1))
250 CYJSString &operator =(const CYJSString &rhs) {
252 string_ = CYCopyJSString(rhs.string_);
265 operator JSStringRef() const {
271 // XXX: this macro is unhygenic
272 #define CYCastCString_(string) ({ \
274 if (string == NULL) \
277 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
278 utf8 = reinterpret_cast<char *>(alloca(size)); \
279 JSStringGetUTF8CString(string, utf8, size); \
284 // XXX: this macro is unhygenic
285 #define CYCastCString(context, value) ({ \
289 else if (JSStringRef string = CYCopyJSString(context, value)) { \
290 utf8 = CYCastCString_(string); \
291 JSStringRelease(string); \
300 /* Objective-C Pool Release {{{ */
301 apr_status_t CYPoolRelease_(void *data) {
302 id object(reinterpret_cast<id>(data));
307 id CYPoolRelease_(apr_pool_t *pool, id object) {
310 else if (pool == NULL)
311 return [object autorelease];
313 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
318 template <typename Type_>
319 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
320 return (Type_) CYPoolRelease_(pool, (id) object);
323 /* Objective-C Strings {{{ */
324 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
326 return [value UTF8String];
328 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
329 char *string(new(pool) char[size]);
330 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
331 _throw(NSInternalInconsistencyException, "[NSString getCString:maxLength:encoding:] == NO");
336 JSStringRef CYCopyJSString_(NSString *value) {
338 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
341 return CYCopyJSString(CYPoolCString(pool, value));
345 JSStringRef CYCopyJSString(id value) {
348 // XXX: this definition scares me; is anyone using this?!
349 NSString *string([value description]);
350 return CYCopyJSString_(string);
353 NSString *CYCopyNSString(const CYUTF8String &value) {
355 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
357 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
361 NSString *CYCopyNSString(JSStringRef value) {
363 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
365 return CYCopyNSString(CYCastCString_(value));
369 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
370 return CYCopyNSString(CYJSString(context, value));
373 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
374 return CYPoolRelease(pool, CYCopyNSString(value));
377 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
378 const char *name(sel_getName(sel));
379 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
382 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
383 return CYPoolRelease(pool, CYCopyNSString(value));
388 CYUTF8String CYCastUTF8String(NSString *value) {
389 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
390 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
393 /* JavaScript Stringify {{{ */
394 void CYStringify(std::ostringstream &str, const char *data, size_t size) {
395 unsigned quot(0), apos(0);
396 for (const char *value(data), *end(data + size); value != end; ++value)
399 else if (*value == '\'')
402 bool single(quot > apos);
404 str << (single ? '\'' : '"');
406 for (const char *value(data), *end(data + size); value != end; ++value)
408 case '\\': str << "\\\\"; break;
409 case '\b': str << "\\b"; break;
410 case '\f': str << "\\f"; break;
411 case '\n': str << "\\n"; break;
412 case '\r': str << "\\r"; break;
413 case '\t': str << "\\t"; break;
414 case '\v': str << "\\v"; break;
429 if (*value < 0x20 || *value >= 0x7f)
430 str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(*value);
435 str << (single ? '\'' : '"');
439 static JSGlobalContextRef Context_;
440 static JSObjectRef System_;
441 static JSObjectRef ObjectiveC_;
443 static JSClassRef Functor_;
444 static JSClassRef Instance_;
445 static JSClassRef Internal_;
446 static JSClassRef Message_;
447 static JSClassRef Messages_;
448 static JSClassRef Pointer_;
449 static JSClassRef Runtime_;
450 static JSClassRef Selector_;
451 static JSClassRef Struct_;
453 static JSClassRef ObjectiveC_Classes_;
454 static JSClassRef ObjectiveC_Image_Classes_;
455 static JSClassRef ObjectiveC_Images_;
456 static JSClassRef ObjectiveC_Protocols_;
458 static JSObjectRef Array_;
459 static JSObjectRef Function_;
460 static JSObjectRef String_;
462 static JSStringRef Result_;
464 static JSStringRef length_;
465 static JSStringRef message_;
466 static JSStringRef name_;
467 static JSStringRef prototype_;
468 static JSStringRef toCYON_;
469 static JSStringRef toJSON_;
471 static JSObjectRef Instance_prototype_;
472 static JSObjectRef Object_prototype_;
474 static JSObjectRef Array_prototype_;
475 static JSObjectRef Array_pop_;
476 static JSObjectRef Array_push_;
477 static JSObjectRef Array_splice_;
481 static Class NSCFBoolean_;
482 static Class NSCFType_;
485 static Class NSArray_;
486 static Class NSDictionary_;
487 static Class NSMessageBuilder_;
488 static Class NSZombie_;
489 static Class Object_;
492 static NSArray *Bridge_;
494 static void Finalize(JSObjectRef object) {
495 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
498 class Type_privateData;
508 CYValue(const void *value) :
509 value_(const_cast<void *>(value))
513 CYValue(const CYValue &rhs) :
518 virtual Type_privateData *GetType() const {
527 JSContextRef context_;
531 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
536 JSValueProtect(context_, owner_);
540 JSValueUnprotect(context_, owner_);
543 JSObjectRef GetOwner() const {
549 struct Selector_privateData :
552 Selector_privateData(SEL value) :
557 SEL GetValue() const {
558 return reinterpret_cast<SEL>(value_);
561 virtual Type_privateData *GetType() const;
564 // XXX: trick this out with associated objects!
565 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
567 return Instance_prototype_;
569 // XXX: I need to think through multi-context
570 typedef std::map<id, JSValueRef> CacheMap;
571 static CacheMap cache_;
573 JSValueRef &value(cache_[self]);
577 JSClassRef _class(NULL);
578 JSValueRef prototype;
580 if (self == NSArray_)
581 prototype = Array_prototype_;
582 else if (self == NSDictionary_)
583 prototype = Object_prototype_;
585 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
587 JSObjectRef object(JSObjectMake(context, _class, NULL));
588 JSObjectSetPrototype(context, object, prototype);
590 JSValueProtect(context, object);
600 Transient = (1 << 0),
601 Uninitialized = (1 << 1),
606 Instance(id value, Flags flags) :
612 virtual ~Instance() {
613 if ((flags_ & Transient) == 0)
614 // XXX: does this handle background threads correctly?
615 // XXX: this simply does not work on the console because I'm stupid
616 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
619 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
620 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
621 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
625 id GetValue() const {
626 return reinterpret_cast<id>(value_);
629 bool IsUninitialized() const {
630 return (flags_ & Uninitialized) != 0;
633 virtual Type_privateData *GetType() const;
639 Messages(Class value) :
644 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
645 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
646 if (_class == NSArray_)
648 if (Class super = class_getSuperclass(_class))
649 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
651 JSObjectSetPrototype(context, value, Array_prototype_);*/
655 Class GetValue() const {
656 return reinterpret_cast<Class>(value_);
663 Internal(id value, JSContextRef context, JSObjectRef owner) :
664 CYOwned(value, context, owner)
668 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
669 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
672 id GetValue() const {
673 return reinterpret_cast<id>(value_);
680 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
682 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
683 lhs.name = apr_pstrdup(pool, rhs.name);
684 if (rhs.type == NULL)
687 lhs.type = new(pool) Type;
688 Copy(pool, *lhs.type, *rhs.type);
690 lhs.offset = rhs.offset;
693 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
694 size_t count(rhs.count);
696 lhs.elements = new(pool) Element[count];
697 for (size_t index(0); index != count; ++index)
698 Copy(pool, lhs.elements[index], rhs.elements[index]);
701 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
702 lhs.primitive = rhs.primitive;
703 lhs.name = apr_pstrdup(pool, rhs.name);
704 lhs.flags = rhs.flags;
706 if (sig::IsAggregate(rhs.primitive))
707 Copy(pool, lhs.data.signature, rhs.data.signature);
709 sig::Type *&lht(lhs.data.data.type);
710 sig::Type *&rht(rhs.data.data.type);
715 lht = new(pool) Type;
716 Copy(pool, *lht, *rht);
719 lhs.data.data.size = rhs.data.data.size;
723 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
725 lhs.alignment = rhs.alignment;
727 if (rhs.elements == NULL)
731 while (rhs.elements[count] != NULL)
734 lhs.elements = new(pool) ffi_type *[count + 1];
735 lhs.elements[count] = NULL;
737 for (size_t index(0); index != count; ++index) {
738 // XXX: if these are libffi native then you can just take them
739 ffi_type *ffi(new(pool) ffi_type);
740 lhs.elements[index] = ffi;
741 sig::Copy(pool, *ffi, *rhs.elements[index]);
748 struct CStringMapLess :
749 std::binary_function<const char *, const char *, bool>
751 _finline bool operator ()(const char *lhs, const char *rhs) const {
752 return strcmp(lhs, rhs) < 0;
756 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
761 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
762 switch ([[entry objectAtIndex:0] intValue]) {
764 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
768 sig::Signature signature;
769 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
770 type = signature.elements[0].type;
776 struct Type_privateData :
780 static Type_privateData *Object;
781 static Type_privateData *Selector;
784 static JSClassRef Class_;
789 void Set(sig::Type *type) {
790 type_ = new(pool_) sig::Type;
791 sig::Copy(pool_, *type_, *type);
794 Type_privateData(apr_pool_t *pool, const char *type) :
800 sig::Signature signature;
801 sig::Parse(pool_, &signature, type, &Structor_);
802 type_ = signature.elements[0].type;
805 Type_privateData(sig::Type *type) :
812 Type_privateData(sig::Type *type, ffi_type *ffi) {
813 ffi_ = new(pool_) ffi_type;
814 sig::Copy(pool_, *ffi_, *ffi);
820 ffi_ = new(pool_) ffi_type;
822 sig::Element element;
824 element.type = type_;
827 sig::Signature signature;
828 signature.elements = &element;
832 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
840 JSClassRef Type_privateData::Class_;
843 Type_privateData *Type_privateData::Object;
844 Type_privateData *Type_privateData::Selector;
846 Type_privateData *Instance::GetType() const {
847 return Type_privateData::Object;
850 Type_privateData *Selector_privateData::GetType() const {
851 return Type_privateData::Selector;
858 Type_privateData *type_;
860 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
861 CYOwned(value, context, owner),
862 type_(new(pool_) Type_privateData(type))
867 struct Struct_privateData :
870 Type_privateData *type_;
872 Struct_privateData(JSContextRef context, JSObjectRef owner) :
873 CYOwned(NULL, context, owner)
878 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
879 static TypeMap Types_;
881 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
882 Struct_privateData *internal(new Struct_privateData(context, owner));
883 apr_pool_t *pool(internal->pool_);
884 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
885 internal->type_ = typical;
888 internal->value_ = data;
890 size_t size(typical->GetFFI()->size);
891 void *copy(apr_palloc(internal->pool_, size));
892 memcpy(copy, data, size);
893 internal->value_ = copy;
896 return JSObjectMake(context, Struct_, internal);
899 struct Functor_privateData :
902 sig::Signature signature_;
906 Functor_privateData(const char *type, void (*value)()) :
907 CYValue(reinterpret_cast<void *>(value))
909 sig::Parse(pool_, &signature_, type, &Structor_);
910 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
913 void (*GetValue())() const {
914 return reinterpret_cast<void (*)()>(value_);
918 struct Closure_privateData :
921 JSContextRef context_;
922 JSObjectRef function_;
924 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
925 Functor_privateData(type, NULL),
929 JSValueProtect(context_, function_);
932 virtual ~Closure_privateData() {
933 JSValueUnprotect(context_, function_);
938 struct Message_privateData :
943 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
944 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
950 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
951 Instance::Flags flags;
954 flags = Instance::Transient;
956 flags = Instance::None;
957 object = [object retain];
960 return Instance::Make(context, object, flags);
964 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
965 return JSValueMakeBoolean(context, value);
968 JSValueRef CYCastJSValue(JSContextRef context, double value) {
969 return JSValueMakeNumber(context, value);
972 #define CYCastJSValue_(Type_) \
973 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
974 return JSValueMakeNumber(context, static_cast<double>(value)); \
978 CYCastJSValue_(unsigned int)
979 CYCastJSValue_(long int)
980 CYCastJSValue_(long unsigned int)
981 CYCastJSValue_(long long int)
982 CYCastJSValue_(long long unsigned int)
984 JSValueRef CYJSUndefined(JSContextRef context) {
985 return JSValueMakeUndefined(context);
988 size_t CYGetIndex(const CYUTF8String &value) {
989 if (value.data[0] != '0') {
991 size_t index(strtoul(value.data, &end, 10));
992 if (value.data + value.size == end)
994 } else if (value.data[1] == '\0')
1000 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value);
1002 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
1003 return CYGetIndex(CYPoolUTF8String(pool, value));
1006 bool CYGetOffset(const char *value, ssize_t &index) {
1007 if (value[0] != '0') {
1009 index = strtol(value, &end, 10);
1010 if (value + strlen(value) == end)
1012 } else if (value[1] == '\0') {
1021 size_t CYGetIndex(NSString *value) {
1022 return CYGetIndex(CYCastUTF8String(value));
1025 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
1026 return CYGetOffset(CYPoolCString(pool, value), index);
1031 @interface NSMethodSignature (Cycript)
1032 - (NSString *) _typeString;
1035 @interface NSObject (Cycript)
1037 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1038 - (JSType) cy$JSType;
1040 - (NSObject *) cy$toJSON:(NSString *)key;
1041 - (NSString *) cy$toCYON;
1042 - (NSString *) cy$toKey;
1044 - (bool) cy$hasProperty:(NSString *)name;
1045 - (NSObject *) cy$getProperty:(NSString *)name;
1046 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
1047 - (bool) cy$deleteProperty:(NSString *)name;
1052 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1055 @interface NSString (Cycript)
1056 - (void *) cy$symbol;
1061 NSString *CYCastNSCYON(id value) {
1067 Class _class(object_getClass(value));
1068 SEL sel(@selector(cy$toCYON));
1070 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
1071 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1072 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1073 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1074 string = [value cy$toCYON];
1077 if (value == NSZombie_)
1078 string = @"_NSZombie_";
1079 else if (_class == NSZombie_)
1080 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1081 // XXX: frowny /in/ the pants
1082 else if (value == NSMessageBuilder_ || value == Object_)
1085 string = [NSString stringWithFormat:@"%@", value];
1088 // XXX: frowny pants
1090 string = @"undefined";
1099 struct PropertyAttributes {
1104 const char *variable;
1106 const char *getter_;
1107 const char *setter_;
1117 PropertyAttributes(objc_property_t property) :
1129 name = property_getName(property);
1130 const char *attributes(property_getAttributes(property));
1132 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
1134 case 'R': readonly = true; break;
1135 case 'C': copy = true; break;
1136 case '&': retain = true; break;
1137 case 'N': nonatomic = true; break;
1138 case 'G': getter_ = token + 1; break;
1139 case 'S': setter_ = token + 1; break;
1140 case 'V': variable = token + 1; break;
1144 /*if (variable == NULL) {
1145 variable = property_getName(property);
1146 size_t size(strlen(variable));
1147 char *name(new(pool_) char[size + 2]);
1149 memcpy(name + 1, variable, size);
1150 name[size + 1] = '\0';
1155 const char *Getter() {
1156 if (getter_ == NULL)
1157 getter_ = apr_pstrdup(pool_, name);
1161 const char *Setter() {
1162 if (setter_ == NULL && !readonly) {
1163 size_t length(strlen(name));
1165 char *temp(new(pool_) char[length + 5]);
1171 temp[3] = toupper(name[0]);
1172 memcpy(temp + 4, name + 1, length - 1);
1175 temp[length + 3] = ':';
1176 temp[length + 4] = '\0';
1189 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
1190 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
1197 @interface CYWebUndefined : NSObject {
1200 + (CYWebUndefined *) undefined;
1204 @implementation CYWebUndefined
1206 + (CYWebUndefined *) undefined {
1207 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
1213 #define WebUndefined CYWebUndefined
1218 /* Bridge: NSArray {{{ */
1219 @implementation NSArray (Cycript)
1221 - (NSString *) cy$toCYON {
1222 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1223 [json appendString:@"["];
1227 for (id object in self) {
1230 for (size_t index(0), count([self count]); index != count; ++index) {
1231 object = [self objectAtIndex:index];
1234 [json appendString:@","];
1237 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
1238 [json appendString:CYCastNSCYON(object)];
1240 [json appendString:@","];
1245 [json appendString:@"]"];
1249 - (bool) cy$hasProperty:(NSString *)name {
1250 if ([name isEqualToString:@"length"])
1253 size_t index(CYGetIndex(name));
1254 if (index == _not(size_t) || index >= [self count])
1255 return [super cy$hasProperty:name];
1260 - (NSObject *) cy$getProperty:(NSString *)name {
1261 if ([name isEqualToString:@"length"]) {
1262 NSUInteger count([self count]);
1264 return [NSNumber numberWithUnsignedInteger:count];
1266 return [NSNumber numberWithUnsignedInt:count];
1270 size_t index(CYGetIndex(name));
1271 if (index == _not(size_t) || index >= [self count])
1272 return [super cy$getProperty:name];
1274 return [self objectAtIndex:index];
1279 /* Bridge: NSDictionary {{{ */
1280 @implementation NSDictionary (Cycript)
1282 - (NSString *) cy$toCYON {
1283 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1284 [json appendString:@"{"];
1288 for (id key in self) {
1290 NSEnumerator *keys([self keyEnumerator]);
1291 while (id key = [keys nextObject]) {
1294 [json appendString:@","];
1297 [json appendString:[key cy$toKey]];
1298 [json appendString:@":"];
1299 NSObject *object([self objectForKey:key]);
1300 [json appendString:CYCastNSCYON(object)];
1303 [json appendString:@"}"];
1307 - (bool) cy$hasProperty:(NSString *)name {
1308 return [self objectForKey:name] != nil;
1311 - (NSObject *) cy$getProperty:(NSString *)name {
1312 return [self objectForKey:name];
1317 /* Bridge: NSMutableArray {{{ */
1318 @implementation NSMutableArray (Cycript)
1320 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1321 if ([name isEqualToString:@"length"]) {
1322 // XXX: is this not intelligent?
1323 NSNumber *number(reinterpret_cast<NSNumber *>(value));
1325 NSUInteger size([number unsignedIntegerValue]);
1327 NSUInteger size([number unsignedIntValue]);
1329 NSUInteger count([self count]);
1331 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1332 else if (size != count) {
1333 WebUndefined *undefined([WebUndefined undefined]);
1334 for (size_t i(count); i != size; ++i)
1335 [self addObject:undefined];
1340 size_t index(CYGetIndex(name));
1341 if (index == _not(size_t))
1342 return [super cy$setProperty:name to:value];
1344 id object(value ?: [NSNull null]);
1346 size_t count([self count]);
1348 [self replaceObjectAtIndex:index withObject:object];
1350 if (index != count) {
1351 WebUndefined *undefined([WebUndefined undefined]);
1352 for (size_t i(count); i != index; ++i)
1353 [self addObject:undefined];
1356 [self addObject:object];
1362 - (bool) cy$deleteProperty:(NSString *)name {
1363 size_t index(CYGetIndex(name));
1364 if (index == _not(size_t) || index >= [self count])
1365 return [super cy$deleteProperty:name];
1366 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1372 /* Bridge: NSMutableDictionary {{{ */
1373 @implementation NSMutableDictionary (Cycript)
1375 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1376 [self setObject:(value ?: [NSNull null]) forKey:name];
1380 - (bool) cy$deleteProperty:(NSString *)name {
1381 if ([self objectForKey:name] == nil)
1384 [self removeObjectForKey:name];
1391 /* Bridge: NSNumber {{{ */
1392 @implementation NSNumber (Cycript)
1394 - (JSType) cy$JSType {
1396 // XXX: this just seems stupid
1397 if ([self class] == NSCFBoolean_)
1398 return kJSTypeBoolean;
1400 return kJSTypeNumber;
1403 - (NSObject *) cy$toJSON:(NSString *)key {
1407 - (NSString *) cy$toCYON {
1408 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1411 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1412 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1417 /* Bridge: NSNull {{{ */
1418 @implementation NSNull (Cycript)
1420 - (JSType) cy$JSType {
1424 - (NSObject *) cy$toJSON:(NSString *)key {
1428 - (NSString *) cy$toCYON {
1434 /* Bridge: NSObject {{{ */
1435 @implementation NSObject (Cycript)
1437 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1438 return CYMakeInstance(context, self, false);
1441 - (JSType) cy$JSType {
1442 return kJSTypeObject;
1445 - (NSObject *) cy$toJSON:(NSString *)key {
1446 return [self description];
1449 - (NSString *) cy$toCYON {
1450 return [[self cy$toJSON:@""] cy$toCYON];
1453 - (NSString *) cy$toKey {
1454 return [self cy$toCYON];
1457 - (bool) cy$hasProperty:(NSString *)name {
1461 - (NSObject *) cy$getProperty:(NSString *)name {
1465 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1469 - (bool) cy$deleteProperty:(NSString *)name {
1475 /* Bridge: NSProxy {{{ */
1476 @implementation NSProxy (Cycript)
1478 - (NSObject *) cy$toJSON:(NSString *)key {
1479 return [self description];
1482 - (NSString *) cy$toCYON {
1483 return [[self cy$toJSON:@""] cy$toCYON];
1488 /* Bridge: NSString {{{ */
1489 @implementation NSString (Cycript)
1491 - (JSType) cy$JSType {
1492 return kJSTypeString;
1495 - (NSObject *) cy$toJSON:(NSString *)key {
1499 - (NSString *) cy$toCYON {
1500 std::ostringstream str;
1501 CYUTF8String string(CYCastUTF8String(self));
1502 CYStringify(str, string.data, string.size);
1503 std::string value(str.str());
1504 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1507 - (NSString *) cy$toKey {
1508 const char *value([self UTF8String]);
1509 size_t size(strlen(value));
1514 if (DigitRange_[value[0]]) {
1515 size_t index(CYGetIndex(self));
1516 if (index == _not(size_t))
1519 if (!WordStartRange_[value[0]])
1521 for (size_t i(1); i != size; ++i)
1522 if (!WordEndRange_[value[i]])
1529 return [self cy$toCYON];
1532 - (void *) cy$symbol {
1534 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1539 /* Bridge: WebUndefined {{{ */
1540 @implementation WebUndefined (Cycript)
1542 - (JSType) cy$JSType {
1543 return kJSTypeUndefined;
1546 - (NSObject *) cy$toJSON:(NSString *)key {
1550 - (NSString *) cy$toCYON {
1551 return @"undefined";
1554 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1555 return CYJSUndefined(context);
1561 /* Bridge: CYJSObject {{{ */
1562 @interface CYJSObject : NSMutableDictionary {
1563 JSObjectRef object_;
1564 JSContextRef context_;
1567 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1569 - (NSObject *) cy$toJSON:(NSString *)key;
1571 - (NSUInteger) count;
1572 - (id) objectForKey:(id)key;
1573 - (NSEnumerator *) keyEnumerator;
1574 - (void) setObject:(id)object forKey:(id)key;
1575 - (void) removeObjectForKey:(id)key;
1579 /* Bridge: CYJSArray {{{ */
1580 @interface CYJSArray : NSMutableArray {
1581 JSObjectRef object_;
1582 JSContextRef context_;
1585 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1587 - (NSUInteger) count;
1588 - (id) objectAtIndex:(NSUInteger)index;
1590 - (void) addObject:(id)anObject;
1591 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1592 - (void) removeLastObject;
1593 - (void) removeObjectAtIndex:(NSUInteger)index;
1594 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1601 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1602 JSValueRef exception(NULL);
1603 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1604 CYThrow(context, exception);
1605 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1606 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1609 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1610 if (!JSValueIsObjectOfClass(context, object, Instance_))
1611 return CYCastNSObject_(pool, context, object);
1613 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1614 return internal->GetValue();
1619 double CYCastDouble(const char *value, size_t size) {
1621 double number(strtod(value, &end));
1622 if (end != value + size)
1627 double CYCastDouble(const char *value) {
1628 return CYCastDouble(value, strlen(value));
1631 double CYCastDouble(JSContextRef context, JSValueRef value) {
1632 JSValueRef exception(NULL);
1633 double number(JSValueToNumber(context, value, &exception));
1634 CYThrow(context, exception);
1639 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
1640 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
1644 bool CYCastBool(JSContextRef context, JSValueRef value) {
1645 return JSValueToBoolean(context, value);
1649 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1653 switch (JSType type = JSValueGetType(context, value)) {
1654 case kJSTypeUndefined:
1655 object = [WebUndefined undefined];
1663 case kJSTypeBoolean:
1665 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
1668 object = [[NSNumber alloc] initWithBool:CYCastBool(context, value)];
1674 object = CYCopyNSNumber(context, value);
1679 object = CYCopyNSString(context, value);
1684 // XXX: this might could be more efficient
1685 object = CYCastNSObject(pool, context, (JSObjectRef) value);
1690 _throw(NSInternalInconsistencyException, "JSValueGetType() == 0x%x", type);
1697 return CYPoolRelease(pool, object);
1699 return [object retain];
1702 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1703 return CYNSObject(pool, context, value, true);
1706 id CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1707 return CYNSObject(pool, context, value, false);
1710 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1712 size_t size(JSPropertyNameArrayGetCount(names));
1713 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1714 for (size_t index(0); index != size; ++index)
1715 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1720 void CYThrow(JSContextRef context, JSValueRef value) {
1724 @throw CYCastNSObject(NULL, context, value);
1731 JSValueRef CYJSNull(JSContextRef context) {
1732 return JSValueMakeNull(context);
1735 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1736 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1739 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1740 return CYCastJSValue(context, CYJSString(value));
1744 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1746 return CYJSNull(context);
1747 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1748 return [value cy$JSValueInContext:context];
1750 return CYMakeInstance(context, value, false);
1754 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1755 JSValueRef exception(NULL);
1756 JSObjectRef object(JSValueToObject(context, value, &exception));
1757 CYThrow(context, exception);
1761 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1762 if (exception == NULL)
1764 *exception = CYCastJSValue(context, error);
1767 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1768 JSValueRef exception(NULL);
1769 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1770 CYThrow(context, exception);
1774 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1775 // XXX: this isn't actually correct
1776 return value != NULL && JSValueIsObject(context, value);
1780 @implementation CYJSObject
1782 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1783 if ((self = [super init]) != nil) {
1786 JSValueProtect(context_, object_);
1791 JSValueUnprotect(context_, object_);
1795 - (NSObject *) cy$toJSON:(NSString *)key {
1796 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1797 if (!CYIsCallable(context_, toJSON))
1798 return [super cy$toJSON:key];
1800 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1801 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1802 // XXX: do I really want an NSNull here?!
1803 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1807 - (NSString *) cy$toCYON {
1808 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1809 if (!CYIsCallable(context_, toCYON)) super:
1810 return [super cy$toCYON];
1811 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1812 return CYCastNSString(NULL, CYJSString(context_, value));
1816 - (NSUInteger) count {
1817 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1818 size_t size(JSPropertyNameArrayGetCount(names));
1819 JSPropertyNameArrayRelease(names);
1823 - (id) objectForKey:(id)key {
1824 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1825 if (JSValueIsUndefined(context_, value))
1827 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1830 - (NSEnumerator *) keyEnumerator {
1831 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1832 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1833 JSPropertyNameArrayRelease(names);
1837 - (void) setObject:(id)object forKey:(id)key {
1838 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1841 - (void) removeObjectForKey:(id)key {
1842 JSValueRef exception(NULL);
1843 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1844 CYThrow(context_, exception);
1849 @implementation CYJSArray
1851 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1852 if ((self = [super init]) != nil) {
1855 JSValueProtect(context_, object_);
1860 JSValueUnprotect(context_, object_);
1864 - (NSUInteger) count {
1865 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1868 - (id) objectAtIndex:(NSUInteger)index {
1869 size_t bounds([self count]);
1870 if (index >= bounds)
1871 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1872 JSValueRef exception(NULL);
1873 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1874 CYThrow(context_, exception);
1875 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1878 - (void) addObject:(id)object {
1879 JSValueRef exception(NULL);
1880 JSValueRef arguments[1];
1881 arguments[0] = CYCastJSValue(context_, object);
1882 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1883 CYThrow(context_, exception);
1886 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1887 size_t bounds([self count] + 1);
1888 if (index >= bounds)
1889 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1890 JSValueRef exception(NULL);
1891 JSValueRef arguments[3];
1892 arguments[0] = CYCastJSValue(context_, index);
1893 arguments[1] = CYCastJSValue(context_, 0);
1894 arguments[2] = CYCastJSValue(context_, object);
1895 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1896 CYThrow(context_, exception);
1899 - (void) removeLastObject {
1900 JSValueRef exception(NULL);
1901 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1902 CYThrow(context_, exception);
1905 - (void) removeObjectAtIndex:(NSUInteger)index {
1906 size_t bounds([self count]);
1907 if (index >= bounds)
1908 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1909 JSValueRef exception(NULL);
1910 JSValueRef arguments[2];
1911 arguments[0] = CYCastJSValue(context_, index);
1912 arguments[1] = CYCastJSValue(context_, 1);
1913 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1914 CYThrow(context_, exception);
1917 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1918 size_t bounds([self count]);
1919 if (index >= bounds)
1920 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1921 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1927 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1928 if (JSValueIsNull(context, value))
1929 return [@"null" retain];
1933 return [CYCastNSCYON(CYCastNSObject(NULL, context, value)) retain];
1938 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1939 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1940 const char *string(CYPoolCString(pool, json));
1947 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1951 JSObjectRef object_;
1959 // XXX: delete object_? ;(
1962 static CYInternal *Get(id self) {
1963 CYInternal *internal(NULL);
1964 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1965 // XXX: do something epic? ;P
1971 static CYInternal *Set(id self) {
1972 CYInternal *internal(NULL);
1973 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1974 if (internal == NULL) {
1975 internal = new CYInternal();
1976 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1979 // XXX: do something epic? ;P
1985 bool HasProperty(JSContextRef context, JSStringRef name) {
1986 if (object_ == NULL)
1988 return JSObjectHasProperty(context, object_, name);
1991 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1992 if (object_ == NULL)
1994 return CYGetProperty(context, object_, name);
1997 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1998 if (object_ == NULL)
1999 object_ = JSObjectMake(context, NULL, NULL);
2000 CYSetProperty(context, object_, name, value);
2006 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
2007 Selector_privateData *internal(new Selector_privateData(sel));
2008 return JSObjectMake(context, Selector_, internal);
2012 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
2013 Pointer *internal(new Pointer(pointer, context, owner, type));
2014 return JSObjectMake(context, Pointer_, internal);
2017 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
2018 Functor_privateData *internal(new Functor_privateData(type, function));
2019 return JSObjectMake(context, Functor_, internal);
2022 static CYUTF16String CYCastUTF16String(JSStringRef value) {
2023 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
2026 // XXX: sometimes pool is null
2027 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value) {
2028 CYUTF16String utf16(CYCastUTF16String(value));
2029 const char *in(reinterpret_cast<const char *>(utf16.data));
2031 iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL")));
2033 size_t size(JSStringGetMaximumUTF8CStringSize(value));
2034 char *out(new(pool) char[size]);
2035 CYUTF8String utf8(out, size);
2037 size = utf16.size * 2;
2038 _syscall(iconv(conversion, const_cast<char **>(&in), &size, &out, &utf8.size));
2041 utf8.size = out - utf8.data;
2043 _syscall(iconv_close(conversion));
2048 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
2049 CYUTF8String utf8(CYPoolUTF8String(pool, value));
2050 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
2054 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
2055 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
2058 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
2059 return CYGetOffset(CYPoolCString(pool, value), index);
2062 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
2063 switch (JSValueGetType(context, value)) {
2066 /*case kJSTypeString:
2067 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
2069 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
2070 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
2071 return internal->value_;
2074 double number(CYCastDouble(context, value));
2075 if (std::isnan(number))
2076 _throw(NSInvalidArgumentException, "cannot convert value to pointer");
2077 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
2081 template <typename Type_>
2082 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
2083 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
2087 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
2088 if (JSValueIsObjectOfClass(context, value, Selector_)) {
2089 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2090 return reinterpret_cast<SEL>(internal->value_);
2092 return CYCastPointer<SEL>(context, value);
2096 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
2097 switch (type->primitive) {
2098 case sig::boolean_P:
2099 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
2102 #define CYPoolFFI_(primitive, native) \
2103 case sig::primitive ## _P: \
2104 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
2107 CYPoolFFI_(uchar, unsigned char)
2108 CYPoolFFI_(char, char)
2109 CYPoolFFI_(ushort, unsigned short)
2110 CYPoolFFI_(short, short)
2111 CYPoolFFI_(ulong, unsigned long)
2112 CYPoolFFI_(long, long)
2113 CYPoolFFI_(uint, unsigned int)
2114 CYPoolFFI_(int, int)
2115 CYPoolFFI_(ulonglong, unsigned long long)
2116 CYPoolFFI_(longlong, long long)
2117 CYPoolFFI_(float, float)
2118 CYPoolFFI_(double, double)
2122 case sig::typename_P:
2123 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
2126 case sig::selector_P:
2127 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
2131 case sig::pointer_P:
2132 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
2136 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
2139 case sig::struct_P: {
2140 uint8_t *base(reinterpret_cast<uint8_t *>(data));
2141 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
2142 for (size_t index(0); index != type->data.signature.count; ++index) {
2143 sig::Element *element(&type->data.signature.elements[index]);
2144 ffi_type *field(ffi->elements[index]);
2147 if (aggregate == NULL)
2150 rhs = CYGetProperty(context, aggregate, index);
2151 if (JSValueIsUndefined(context, rhs)) {
2152 if (element->name != NULL)
2153 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
2156 if (JSValueIsUndefined(context, rhs)) undefined:
2157 _throw(NSInvalidArgumentException, "unable to extract structure value");
2161 CYPoolFFI(pool, context, element->type, field, base, rhs);
2163 base += field->size;
2171 fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
2176 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
2179 switch (type->primitive) {
2180 case sig::boolean_P:
2181 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
2184 #define CYFromFFI_(primitive, native) \
2185 case sig::primitive ## _P: \
2186 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
2189 CYFromFFI_(uchar, unsigned char)
2190 CYFromFFI_(char, char)
2191 CYFromFFI_(ushort, unsigned short)
2192 CYFromFFI_(short, short)
2193 CYFromFFI_(ulong, unsigned long)
2194 CYFromFFI_(long, long)
2195 CYFromFFI_(uint, unsigned int)
2196 CYFromFFI_(int, int)
2197 CYFromFFI_(ulonglong, unsigned long long)
2198 CYFromFFI_(longlong, long long)
2199 CYFromFFI_(float, float)
2200 CYFromFFI_(double, double)
2203 case sig::object_P: {
2204 if (id object = *reinterpret_cast<id *>(data)) {
2205 value = CYCastJSValue(context, object);
2211 case sig::typename_P:
2212 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
2215 case sig::selector_P:
2216 if (SEL sel = *reinterpret_cast<SEL *>(data))
2217 value = CYMakeSelector(context, sel);
2222 case sig::pointer_P:
2223 if (void *pointer = *reinterpret_cast<void **>(data))
2224 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
2229 if (char *utf8 = *reinterpret_cast<char **>(data))
2230 value = CYCastJSValue(context, utf8);
2235 value = CYMakeStruct(context, data, type, ffi, owner);
2239 value = CYJSUndefined(context);
2243 value = CYJSNull(context);
2247 fprintf(stderr, "CYFromFFI(%c)\n", type->primitive);
2254 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
2255 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
2259 method_getReturnType(method, type, sizeof(type));
2264 // XXX: possibly use a more "awesome" check?
2268 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, objc_method *method) {
2270 return method_getTypeEncoding(method);
2271 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel)])
2272 return CYPoolCString(pool, type);
2277 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2278 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2280 JSContextRef context(internal->context_);
2282 size_t count(internal->cif_.nargs);
2283 JSValueRef values[count];
2285 for (size_t index(0); index != count; ++index)
2286 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2288 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2289 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2292 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2293 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2295 JSContextRef context(internal->context_);
2297 size_t count(internal->cif_.nargs);
2298 JSValueRef values[count];
2300 for (size_t index(0); index != count; ++index)
2301 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2303 JSObjectRef _this(CYCastJSObject(context, values[0]));
2305 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2306 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2309 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2310 // XXX: in case of exceptions this will leak
2311 // XXX: in point of fact, this may /need/ to leak :(
2312 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2314 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2315 NULL, sizeof(ffi_closure),
2316 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2320 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2321 _assert(status == FFI_OK);
2323 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2325 internal->value_ = closure;
2330 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2331 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2332 return JSObjectMake(context, Functor_, internal);
2335 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2336 JSValueRef exception(NULL);
2337 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2338 CYThrow(context, exception);
2341 JSObjectRef function(CYCastJSObject(context, value));
2342 return CYMakeFunctor(context, function, type);
2344 void (*function)()(CYCastPointer<void (*)()>(context, value));
2345 return CYMakeFunctor(context, function, type);
2350 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2351 Message_privateData *internal(new Message_privateData(sel, type, imp));
2352 return JSObjectMake(context, Message_, internal);
2355 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2356 JSObjectRef function(CYCastJSObject(context, value));
2357 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2358 return reinterpret_cast<IMP>(internal->GetValue());
2361 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2362 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2363 Class _class(internal->GetValue());
2366 const char *name(CYPoolCString(pool, property));
2368 if (SEL sel = sel_getUid(name))
2369 if (class_getInstanceMethod(_class, sel) != NULL)
2375 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2376 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2377 Class _class(internal->GetValue());
2380 const char *name(CYPoolCString(pool, property));
2382 if (SEL sel = sel_getUid(name))
2383 if (objc_method *method = class_getInstanceMethod(_class, sel))
2384 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2389 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2390 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2391 Class _class(internal->GetValue());
2394 const char *name(CYPoolCString(pool, property));
2396 SEL sel(sel_registerName(name));
2398 objc_method *method(class_getInstanceMethod(_class, sel));
2403 if (JSValueIsObjectOfClass(context, value, Message_)) {
2404 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2405 type = sig::Unparse(pool, &message->signature_);
2406 imp = reinterpret_cast<IMP>(message->GetValue());
2408 type = CYPoolTypeEncoding(pool, _class, sel, method);
2409 imp = CYMakeMessage(context, value, type);
2413 method_setImplementation(method, imp);
2415 class_replaceMethod(_class, sel, imp, type);
2421 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2422 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2423 Class _class(internal->GetValue());
2426 const char *name(CYPoolCString(pool, property));
2428 if (SEL sel = sel_getUid(name))
2429 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
2430 objc_method_list list = {NULL, 1, {method}};
2431 class_removeMethods(_class, &list);
2439 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2440 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2441 Class _class(internal->GetValue());
2444 objc_method **data(class_copyMethodList(_class, &size));
2445 for (size_t i(0); i != size; ++i)
2446 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2450 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2451 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2452 id self(internal->GetValue());
2454 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2458 NSString *name(CYCastNSString(pool, property));
2460 if (CYInternal *internal = CYInternal::Get(self))
2461 if (internal->HasProperty(context, property))
2464 Class _class(object_getClass(self));
2467 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2468 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2469 if ([self cy$hasProperty:name])
2471 } CYPoolCatch(false)
2473 const char *string(CYPoolCString(pool, name));
2475 if (class_getProperty(_class, string) != NULL)
2478 if (SEL sel = sel_getUid(string))
2479 if (CYImplements(self, _class, sel, true))
2485 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2486 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2487 id self(internal->GetValue());
2489 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2490 return Internal::Make(context, self, object);
2494 NSString *name(CYCastNSString(pool, property));
2496 if (CYInternal *internal = CYInternal::Get(self))
2497 if (JSValueRef value = internal->GetProperty(context, property))
2501 if (NSObject *data = [self cy$getProperty:name])
2502 return CYCastJSValue(context, data);
2505 const char *string(CYPoolCString(pool, name));
2506 Class _class(object_getClass(self));
2509 if (objc_property_t property = class_getProperty(_class, string)) {
2510 PropertyAttributes attributes(property);
2511 SEL sel(sel_registerName(attributes.Getter()));
2512 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2516 if (SEL sel = sel_getUid(string))
2517 if (CYImplements(self, _class, sel, true))
2518 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2524 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2525 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2526 id self(internal->GetValue());
2531 NSString *name(CYCastNSString(pool, property));
2532 NSObject *data(CYCastNSObject(pool, context, value));
2535 if ([self cy$setProperty:name to:data])
2539 const char *string(CYPoolCString(pool, name));
2540 Class _class(object_getClass(self));
2543 if (objc_property_t property = class_getProperty(_class, string)) {
2544 PropertyAttributes attributes(property);
2545 if (const char *setter = attributes.Setter()) {
2546 SEL sel(sel_registerName(setter));
2547 JSValueRef arguments[1] = {value};
2548 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2554 size_t length(strlen(string));
2556 char set[length + 5];
2562 if (string[0] != '\0') {
2563 set[3] = toupper(string[0]);
2564 memcpy(set + 4, string + 1, length - 1);
2567 set[length + 3] = ':';
2568 set[length + 4] = '\0';
2570 if (SEL sel = sel_getUid(set))
2571 if (CYImplements(self, _class, sel, false)) {
2572 JSValueRef arguments[1] = {value};
2573 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2576 if (CYInternal *internal = CYInternal::Set(self)) {
2577 internal->SetProperty(context, property, value);
2585 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2586 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2587 id self(internal->GetValue());
2591 NSString *name(CYCastNSString(NULL, property));
2592 return [self cy$deleteProperty:name];
2597 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2598 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2599 id self(internal->GetValue());
2602 Class _class(object_getClass(self));
2606 objc_property_t *data(class_copyPropertyList(_class, &size));
2607 for (size_t i(0); i != size; ++i)
2608 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2613 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2615 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2616 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2621 static bool CYIsClass(id self) {
2622 // XXX: this is a lame object_isClass
2623 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2626 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2627 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2628 Class _class(internal->GetValue());
2629 if (!CYIsClass(_class))
2632 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2633 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2634 // XXX: this isn't always safe
2636 return [linternal->GetValue() isKindOfClass:_class];
2643 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2644 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2647 id self(internal->GetValue());
2648 const char *name(CYPoolCString(pool, property));
2650 if (object_getInstanceVariable(self, name, NULL) != NULL)
2656 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2657 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2661 id self(internal->GetValue());
2662 const char *name(CYPoolCString(pool, property));
2664 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2665 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2666 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2673 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2674 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2678 id self(internal->GetValue());
2679 const char *name(CYPoolCString(pool, property));
2681 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2682 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2683 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2691 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2692 if (Class super = class_getSuperclass(_class))
2693 Internal_getPropertyNames_(super, names);
2696 Ivar *data(class_copyIvarList(_class, &size));
2697 for (size_t i(0); i != size; ++i)
2698 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2702 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2703 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2706 id self(internal->GetValue());
2707 Class _class(object_getClass(self));
2709 Internal_getPropertyNames_(_class, names);
2712 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2713 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2714 return internal->GetOwner();
2718 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2719 Type_privateData *typical(internal->type_);
2720 sig::Type *type(typical->type_);
2724 const char *name(CYPoolCString(pool, property));
2725 size_t length(strlen(name));
2726 double number(CYCastDouble(name, length));
2728 size_t count(type->data.signature.count);
2730 if (std::isnan(number)) {
2731 if (property == NULL)
2734 sig::Element *elements(type->data.signature.elements);
2736 for (size_t local(0); local != count; ++local) {
2737 sig::Element *element(&elements[local]);
2738 if (element->name != NULL && strcmp(name, element->name) == 0) {
2746 index = static_cast<ssize_t>(number);
2747 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2752 ffi_type **elements(typical->GetFFI()->elements);
2754 base = reinterpret_cast<uint8_t *>(internal->value_);
2755 for (ssize_t local(0); local != index; ++local)
2756 base += elements[local]->size;
2761 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2762 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2763 Type_privateData *typical(internal->type_);
2765 ffi_type *ffi(typical->GetFFI());
2767 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2768 base += ffi->size * index;
2770 JSObjectRef owner(internal->GetOwner() ?: object);
2773 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2777 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2779 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2780 Type_privateData *typical(internal->type_);
2782 if (typical->type_ == NULL)
2786 if (!CYGetOffset(pool, property, offset))
2789 return Pointer_getIndex(context, object, offset, exception);
2792 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2793 return Pointer_getIndex(context, object, 0, exception);
2796 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2797 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2798 Type_privateData *typical(internal->type_);
2800 ffi_type *ffi(typical->GetFFI());
2802 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2803 base += ffi->size * index;
2806 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2811 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2813 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2814 Type_privateData *typical(internal->type_);
2816 if (typical->type_ == NULL)
2820 if (!CYGetOffset(pool, property, offset))
2823 return Pointer_setIndex(context, object, offset, value, exception);
2826 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2827 return Pointer_setIndex(context, object, 0, value, exception);
2830 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2831 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2832 Type_privateData *typical(internal->type_);
2833 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2836 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2838 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2839 Type_privateData *typical(internal->type_);
2845 if (!Index_(pool, internal, property, index, base))
2848 JSObjectRef owner(internal->GetOwner() ?: object);
2850 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2854 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2856 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2857 Type_privateData *typical(internal->type_);
2863 if (!Index_(pool, internal, property, index, base))
2866 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2871 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2872 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2873 Type_privateData *typical(internal->type_);
2874 sig::Type *type(typical->type_);
2879 size_t count(type->data.signature.count);
2880 sig::Element *elements(type->data.signature.elements);
2884 for (size_t index(0); index != count; ++index) {
2886 name = elements[index].name;
2889 sprintf(number, "%lu", index);
2893 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2897 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)()) {
2899 if (setups + count != signature->count - 1)
2900 _throw(NSInvalidArgumentException, "incorrect number of arguments to ffi function");
2902 size_t size(setups + count);
2904 memcpy(values, setup, sizeof(void *) * setups);
2906 for (size_t index(setups); index != size; ++index) {
2907 sig::Element *element(&signature->elements[index + 1]);
2908 ffi_type *ffi(cif->arg_types[index]);
2910 values[index] = new(pool) uint8_t[ffi->size];
2911 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2914 uint8_t value[cif->rtype->size];
2915 ffi_call(cif, function, value, values);
2917 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2921 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2924 NSString *name(CYCastNSString(pool, property));
2925 if (Class _class = NSClassFromString(name))
2926 return CYMakeInstance(context, _class, true);
2931 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2932 size_t size(objc_getClassList(NULL, 0));
2933 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2936 size_t writ(objc_getClassList(data, size));
2939 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2945 for (size_t i(0); i != writ; ++i)
2946 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2952 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2953 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2957 const char *name(CYPoolCString(pool, property));
2959 const char **data(objc_copyClassNamesForImage(internal, &size));
2961 for (size_t i(0); i != size; ++i)
2962 if (strcmp(name, data[i]) == 0) {
2963 if (Class _class = objc_getClass(name)) {
2964 value = CYMakeInstance(context, _class, true);
2976 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2977 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2979 const char **data(objc_copyClassNamesForImage(internal, &size));
2980 for (size_t i(0); i != size; ++i)
2981 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2985 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2988 const char *name(CYPoolCString(pool, property));
2990 const char **data(objc_copyImageNames(&size));
2991 for (size_t i(0); i != size; ++i)
2992 if (strcmp(name, data[i]) == 0) {
3001 JSObjectRef value(JSObjectMake(context, NULL, NULL));
3002 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
3007 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3009 const char **data(objc_copyImageNames(&size));
3010 for (size_t i(0); i != size; ++i)
3011 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3015 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3018 NSString *name(CYCastNSString(pool, property));
3019 if (Protocol *protocol = NSProtocolFromString(name))
3020 return CYMakeInstance(context, protocol, true);
3025 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3027 Protocol **data(objc_copyProtocolList(&size));
3028 for (size_t i(0); i != size; ++i)
3029 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
3033 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
3034 Type_privateData *internal(new Type_privateData(NULL, type));
3035 return JSObjectMake(context, Type_privateData::Class_, internal);
3038 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
3039 Type_privateData *internal(new Type_privateData(type));
3040 return JSObjectMake(context, Type_privateData::Class_, internal);
3043 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3044 if (JSStringIsEqualToUTF8CString(property, "nil"))
3045 return Instance::Make(context, nil);
3049 NSString *name(CYCastNSString(pool, property));
3050 if (Class _class = NSClassFromString(name))
3051 return CYMakeInstance(context, _class, true);
3052 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
3053 switch ([[entry objectAtIndex:0] intValue]) {
3055 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
3057 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
3059 // XXX: this is horrendously inefficient
3060 sig::Signature signature;
3061 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
3063 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3064 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
3066 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
3067 switch ([[entry objectAtIndex:0] intValue]) {
3068 // XXX: implement case 0
3070 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
3076 static bool stret(ffi_type *ffi_type) {
3077 return ffi_type->type == FFI_TYPE_STRUCT && (
3078 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
3079 struct_forward_array[ffi_type->size] != 0
3084 int *_NSGetArgc(void);
3085 char ***_NSGetArgv(void);
3088 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3093 printf("%s\n", CYCastCString(context, arguments[0]));
3094 return CYJSUndefined(context);
3098 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
3101 Class _class(object_getClass(self));
3102 if (objc_method *method = class_getInstanceMethod(_class, _cmd))
3103 type = method_getTypeEncoding(method);
3107 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
3109 _throw(NSInvalidArgumentException, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3110 type = CYPoolCString(pool, [method _typeString]);
3119 sig::Signature signature;
3120 sig::Parse(pool, &signature, type, &Structor_);
3123 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3125 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
3126 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3129 static size_t Nonce_(0);
3131 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3133 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
3134 return CYCastJSValue(context, name);
3137 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3147 _throw(NSInvalidArgumentException, "too few arguments to objc_msgSend");
3149 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
3150 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3151 self = internal->GetValue();
3152 uninitialized = internal->IsUninitialized();
3154 internal->value_ = nil;
3156 self = CYCastNSObject(pool, context, arguments[0]);
3157 uninitialized = false;
3161 return CYJSNull(context);
3163 _cmd = CYCastSEL(context, arguments[1]);
3166 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
3170 /* Hook: objc_registerClassPair {{{ */
3171 // XXX: replace this with associated objects
3173 MSHook(void, CYDealloc, id self, SEL sel) {
3174 CYInternal *internal;
3175 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
3176 if (internal != NULL)
3178 _CYDealloc(self, sel);
3181 MSHook(void, objc_registerClassPair, Class _class) {
3182 Class super(class_getSuperclass(_class));
3183 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
3184 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
3185 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
3188 _objc_registerClassPair(_class);
3191 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3194 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3196 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3197 if (value == NULL || !CYIsClass(value))
3198 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3199 Class _class((Class) value);
3200 $objc_registerClassPair(_class);
3201 return CYJSUndefined(context);
3207 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3208 JSGarbageCollect(context);
3209 return CYJSUndefined(context);
3213 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3214 JSValueRef setup[count + 2];
3217 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
3218 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
3221 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3223 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
3225 // XXX: handle Instance::Uninitialized?
3226 id self(CYCastNSObject(pool, context, _this));
3230 setup[1] = &internal->sel_;
3232 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3236 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3238 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
3239 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3242 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3245 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector constructor");
3246 const char *name(CYCastCString(context, arguments[0]));
3247 return CYMakeSelector(context, sel_registerName(name));
3251 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3254 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3256 void *value(CYCastPointer<void *>(context, arguments[0]));
3257 const char *type(CYCastCString(context, arguments[1]));
3261 sig::Signature signature;
3262 sig::Parse(pool, &signature, type, &Structor_);
3264 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
3268 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3271 _throw(NSInvalidArgumentException, "incorrect number of arguments to Type constructor");
3272 const char *type(CYCastCString(context, arguments[0]));
3273 return CYMakeType(context, type);
3277 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3278 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3283 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3284 type.primitive = sig::pointer_P;
3285 type.data.data.size = 0;
3287 size_t index(CYGetIndex(NULL, property));
3288 if (index == _not(size_t))
3290 type.primitive = sig::array_P;
3291 type.data.data.size = index;
3297 type.data.data.type = internal->type_;
3299 return CYMakeType(context, &type);
3303 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3304 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3308 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3309 sig::Type *type(internal->type_);
3310 ffi_type *ffi(internal->GetFFI());
3312 uint8_t value[ffi->size];
3314 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3315 return CYFromFFI(context, type, ffi, value);
3319 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3322 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3323 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3325 sig::Type *type(internal->type_);
3328 if (type->primitive != sig::array_P)
3331 size = type->data.data.size;
3332 type = type->data.data.type;
3335 void *value(malloc(internal->GetFFI()->size));
3336 return CYMakePointer(context, value, type, NULL, NULL);
3341 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3344 _throw(NSInvalidArgumentException, "incorrect number of arguments to Instance constructor");
3345 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3346 return Instance::Make(context, self);
3351 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3354 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3355 const char *type(CYCastCString(context, arguments[1]));
3356 return CYMakeFunctor(context, arguments[0], type);
3360 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3361 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3362 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3365 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3366 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3367 Type_privateData *typical(internal->GetType());
3372 if (typical == NULL) {
3376 type = typical->type_;
3377 ffi = typical->ffi_;
3380 return CYMakePointer(context, &internal->value_, type, ffi, object);
3383 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3384 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3387 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3391 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3392 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3395 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3396 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3398 sprintf(string, "%p", internal->value_);
3401 return CYCastJSValue(context, string);
3406 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3407 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3408 return Instance::Make(context, object_getClass(internal->GetValue()));
3411 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3412 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3413 id self(internal->GetValue());
3414 if (!CYIsClass(self))
3415 return CYJSUndefined(context);
3417 return CYGetClassPrototype(context, self);
3421 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3422 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3423 id self(internal->GetValue());
3424 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3425 return CYJSUndefined(context);
3426 return Messages::Make(context, self);
3429 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3430 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3433 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3437 return CYCastJSValue(context, CYJSString(CYCastNSCYON(internal->GetValue())));
3442 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3443 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3446 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3450 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3451 // XXX: check for support of cy$toJSON?
3452 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3457 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3458 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3461 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3465 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3470 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3471 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3474 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3478 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3479 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3482 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3483 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3484 const char *name(sel_getName(internal->GetValue()));
3488 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3493 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3496 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector.type");
3498 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3499 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3500 if (value == NULL) lookup:
3501 // XXX: do a lookup of some kind
3502 return CYJSNull(context);
3503 else if (!CYIsClass(value))
3504 _throw(NSInvalidArgumentException, "Selector.type takes a Class");
3506 Class _class((Class) value);
3507 SEL sel(internal->GetValue());
3508 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
3509 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3510 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3517 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3519 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3521 const char *type(sig::Unparse(pool, internal->type_));
3522 return CYCastJSValue(context, CYJSString(type));
3526 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3528 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3530 const char *type(sig::Unparse(pool, internal->type_));
3531 size_t size(strlen(type));
3532 char *cyon(new(pool) char[12 + size + 1]);
3533 memcpy(cyon, "new Type(\"", 10);
3534 cyon[12 + size] = '\0';
3535 cyon[12 + size - 2] = '"';
3536 cyon[12 + size - 1] = ')';
3537 memcpy(cyon + 10, type, size);
3538 return CYCastJSValue(context, CYJSString(cyon));
3542 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3543 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3546 static JSStaticValue CYValue_staticValues[2] = {
3547 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3548 {NULL, NULL, NULL, 0}
3551 static JSStaticValue Pointer_staticValues[2] = {
3552 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3553 {NULL, NULL, NULL, 0}
3556 static JSStaticFunction Pointer_staticFunctions[4] = {
3557 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3558 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3559 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3563 static JSStaticFunction Struct_staticFunctions[2] = {
3564 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3568 static JSStaticFunction Functor_staticFunctions[4] = {
3569 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3570 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3571 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3576 static JSStaticValue Instance_staticValues[5] = {
3577 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3578 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3579 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3580 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3581 {NULL, NULL, NULL, 0}
3584 static JSStaticFunction Instance_staticFunctions[5] = {
3585 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3586 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3587 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3588 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3592 static JSStaticFunction Internal_staticFunctions[2] = {
3593 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3597 static JSStaticFunction Selector_staticFunctions[5] = {
3598 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3599 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3600 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3601 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3606 static JSStaticFunction Type_staticFunctions[4] = {
3607 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3608 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3609 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3613 void CYSetArgs(int argc, const char *argv[]) {
3614 JSContextRef context(CYGetJSContext());
3615 JSValueRef args[argc];
3616 for (int i(0); i != argc; ++i)
3617 args[i] = CYCastJSValue(context, argv[i]);
3618 JSValueRef exception(NULL);
3619 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3620 CYThrow(context, exception);
3621 CYSetProperty(context, System_, CYJSString("args"), array);
3624 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3625 return JSContextGetGlobalObject(context);
3628 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3629 JSContextRef context(CYGetJSContext());
3630 JSValueRef exception(NULL), result;
3633 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3634 } catch (const char *error) {
3638 if (exception != NULL) { error:
3643 if (JSValueIsUndefined(context, result))
3649 json = CYPoolCCYON(pool, context, result, &exception);
3650 } catch (const char *error) {
3654 if (exception != NULL)
3657 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3661 static apr_pool_t *Pool_;
3663 apr_pool_t *CYGetGlobalPool() {
3667 MSInitialize { _pooled
3668 _aprcall(apr_initialize());
3669 _aprcall(apr_pool_create(&Pool_, NULL));
3671 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3674 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3675 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3678 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3679 NSCFType_ = objc_getClass("NSCFType");
3682 NSArray_ = objc_getClass("NSArray");
3683 NSDictionary_ = objc_getClass("NSDictonary");
3684 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3685 NSZombie_ = objc_getClass("_NSZombie_");
3686 Object_ = objc_getClass("Object");
3690 JSGlobalContextRef CYGetJSContext() {
3691 if (Context_ == NULL) {
3692 JSClassDefinition definition;
3694 definition = kJSClassDefinitionEmpty;
3695 definition.className = "Functor";
3696 definition.staticFunctions = Functor_staticFunctions;
3697 definition.callAsFunction = &Functor_callAsFunction;
3698 definition.finalize = &Finalize;
3699 Functor_ = JSClassCreate(&definition);
3701 definition = kJSClassDefinitionEmpty;
3702 definition.className = "Pointer";
3703 definition.staticValues = Pointer_staticValues;
3704 definition.staticFunctions = Pointer_staticFunctions;
3705 definition.getProperty = &Pointer_getProperty;
3706 definition.setProperty = &Pointer_setProperty;
3707 definition.finalize = &Finalize;
3708 Pointer_ = JSClassCreate(&definition);
3710 definition = kJSClassDefinitionEmpty;
3711 definition.className = "Selector";
3712 definition.staticValues = CYValue_staticValues;
3713 definition.staticFunctions = Selector_staticFunctions;
3714 definition.callAsFunction = &Selector_callAsFunction;
3715 definition.finalize = &Finalize;
3716 Selector_ = JSClassCreate(&definition);
3718 definition = kJSClassDefinitionEmpty;
3719 definition.className = "Struct";
3720 definition.staticFunctions = Struct_staticFunctions;
3721 definition.getProperty = &Struct_getProperty;
3722 definition.setProperty = &Struct_setProperty;
3723 definition.getPropertyNames = &Struct_getPropertyNames;
3724 definition.finalize = &Finalize;
3725 Struct_ = JSClassCreate(&definition);
3727 definition = kJSClassDefinitionEmpty;
3728 definition.className = "Type";
3729 definition.staticFunctions = Type_staticFunctions;
3730 definition.getProperty = &Type_getProperty;
3731 definition.callAsFunction = &Type_callAsFunction;
3732 definition.callAsConstructor = &Type_callAsConstructor;
3733 definition.finalize = &Finalize;
3734 Type_privateData::Class_ = JSClassCreate(&definition);
3736 definition = kJSClassDefinitionEmpty;
3737 definition.className = "Runtime";
3738 definition.getProperty = &Runtime_getProperty;
3739 Runtime_ = JSClassCreate(&definition);
3741 definition = kJSClassDefinitionEmpty;
3742 //definition.getProperty = &Global_getProperty;
3743 JSClassRef Global(JSClassCreate(&definition));
3745 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3747 JSObjectRef global(CYGetGlobalObject(context));
3749 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3751 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3752 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3753 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3755 length_ = JSStringCreateWithUTF8CString("length");
3756 message_ = JSStringCreateWithUTF8CString("message");
3757 name_ = JSStringCreateWithUTF8CString("name");
3758 prototype_ = JSStringCreateWithUTF8CString("prototype");
3759 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3760 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3762 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3763 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3765 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3766 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3767 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3768 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3770 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3772 /* Objective-C Classes {{{ */
3774 definition = kJSClassDefinitionEmpty;
3775 definition.className = "Instance";
3776 definition.staticValues = Instance_staticValues;
3777 definition.staticFunctions = Instance_staticFunctions;
3778 definition.hasProperty = &Instance_hasProperty;
3779 definition.getProperty = &Instance_getProperty;
3780 definition.setProperty = &Instance_setProperty;
3781 definition.deleteProperty = &Instance_deleteProperty;
3782 definition.getPropertyNames = &Instance_getPropertyNames;
3783 definition.callAsConstructor = &Instance_callAsConstructor;
3784 definition.hasInstance = &Instance_hasInstance;
3785 definition.finalize = &Finalize;
3786 Instance_ = JSClassCreate(&definition);
3788 definition = kJSClassDefinitionEmpty;
3789 definition.className = "Internal";
3790 definition.staticFunctions = Internal_staticFunctions;
3791 definition.hasProperty = &Internal_hasProperty;
3792 definition.getProperty = &Internal_getProperty;
3793 definition.setProperty = &Internal_setProperty;
3794 definition.getPropertyNames = &Internal_getPropertyNames;
3795 definition.finalize = &Finalize;
3796 Internal_ = JSClassCreate(&definition);
3798 definition = kJSClassDefinitionEmpty;
3799 definition.className = "Message";
3800 definition.staticFunctions = Functor_staticFunctions;
3801 definition.callAsFunction = &Message_callAsFunction;
3802 definition.finalize = &Finalize;
3803 Message_ = JSClassCreate(&definition);
3805 definition = kJSClassDefinitionEmpty;
3806 definition.className = "Messages";
3807 definition.hasProperty = &Messages_hasProperty;
3808 definition.getProperty = &Messages_getProperty;
3809 definition.setProperty = &Messages_setProperty;
3811 definition.deleteProperty = &Messages_deleteProperty;
3813 definition.getPropertyNames = &Messages_getPropertyNames;
3814 definition.finalize = &Finalize;
3815 Messages_ = JSClassCreate(&definition);
3816 definition = kJSClassDefinitionEmpty;
3818 definition.className = "ObjectiveC::Classes";
3819 definition.getProperty = &ObjectiveC_Classes_getProperty;
3820 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3821 ObjectiveC_Classes_ = JSClassCreate(&definition);
3823 definition = kJSClassDefinitionEmpty;
3824 definition.className = "ObjectiveC::Images";
3825 definition.getProperty = &ObjectiveC_Images_getProperty;
3826 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3827 ObjectiveC_Images_ = JSClassCreate(&definition);
3829 definition = kJSClassDefinitionEmpty;
3830 definition.className = "ObjectiveC::Image::Classes";
3831 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3832 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3833 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3835 definition = kJSClassDefinitionEmpty;
3836 definition.className = "ObjectiveC::Protocols";
3837 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3838 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3839 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3841 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3842 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3844 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3845 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3846 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3848 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3849 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3850 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3852 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3853 JSValueProtect(context, Instance_prototype_);
3855 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3856 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3858 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3859 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3863 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3864 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3865 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3866 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3868 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3869 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3870 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
3872 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3876 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3880 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
3881 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
3882 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
3884 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3886 System_ = JSObjectMake(context, NULL, NULL);
3887 CYSetProperty(context, global, CYJSString("system"), System_);
3888 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3889 //CYSetProperty(context, System_, CYJSString("global"), global);
3891 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3893 Result_ = JSStringCreateWithUTF8CString("_");
3895 JSValueProtect(context, Array_);
3896 JSValueProtect(context, Function_);
3897 JSValueProtect(context, String_);
3899 JSValueProtect(context, Object_prototype_);
3901 JSValueProtect(context, Array_prototype_);
3902 JSValueProtect(context, Array_pop_);
3903 JSValueProtect(context, Array_push_);
3904 JSValueProtect(context, Array_splice_);