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>
41 #include <minimal/sqlite3.h>
46 #include "cycript.hpp"
48 #include "sig/parse.hpp"
49 #include "sig/ffi_type.hpp"
51 #include "Pooling.hpp"
58 #include <CoreFoundation/CoreFoundation.h>
59 #include <CoreFoundation/CFLogUtilities.h>
60 #include <JavaScriptCore/JSStringRefCF.h>
65 #include <WebKit/WebScriptObject.h>
67 #include <Foundation/Foundation.h>
73 #include <ext/stdio_filebuf.h>
81 #include "Cycript.tab.hh"
87 #define _throw(name, args...) \
88 @throw [NSException exceptionWithName:name reason:[NSString stringWithFormat:@args] userInfo:nil]
90 #define _throw(name, args...) ({ \
92 throw std::string(apr_psprintf(pool, args)); \
96 #define _assert(test, args...) do { \
98 _throw(NSInternalInconsistencyException, "*** _assert(%s):%s(%u):%s [errno=%d]", #test, __FILE__, __LINE__, __FUNCTION__, errno); \
101 #define _trace() do { \
102 fprintf(stderr, "_trace():%u\n", __LINE__); \
107 catch (NSException *error) { \
108 CYThrow(context, error, exception); \
120 *exception = CYCastJSValue(context, "catch(...)"); \
125 #define CYPoolTry { \
127 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
129 #define CYPoolCatch(value) \
130 @catch (NSException *error) { \
131 _saved = [error retain]; \
137 [_saved autorelease]; \
142 #define CYPoolCatch }
146 #define class_getSuperclass GSObjCSuper
147 #define object_getClass GSObjCClass
150 char *sqlite3_column_pooled(apr_pool_t *pool, sqlite3_stmt *stmt, int n) {
151 if (const unsigned char *value = sqlite3_column_text(stmt, n))
152 return apr_pstrdup(pool, (const char *) value);
156 void CYThrow(JSContextRef context, JSValueRef value);
158 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
160 struct CYUTF8String {
164 CYUTF8String(const char *data, size_t size) :
171 struct CYUTF16String {
172 const uint16_t *data;
175 CYUTF16String(const uint16_t *data, size_t size) :
182 /* JavaScript Properties {{{ */
183 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
184 JSValueRef exception(NULL);
185 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
186 CYThrow(context, exception);
190 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
191 JSValueRef exception(NULL);
192 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
193 CYThrow(context, exception);
197 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
198 JSValueRef exception(NULL);
199 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
200 CYThrow(context, exception);
203 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
204 JSValueRef exception(NULL);
205 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
206 CYThrow(context, exception);
209 /* JavaScript Strings {{{ */
210 JSStringRef CYCopyJSString(const char *value) {
211 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
214 JSStringRef CYCopyJSString(JSStringRef value) {
215 return value == NULL ? NULL : JSStringRetain(value);
218 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
219 if (JSValueIsNull(context, value))
221 JSValueRef exception(NULL);
222 JSStringRef string(JSValueToStringCopy(context, value, &exception));
223 CYThrow(context, exception);
233 JSStringRelease(string_);
237 CYJSString(const CYJSString &rhs) :
238 string_(CYCopyJSString(rhs.string_))
242 template <typename Arg0_>
243 CYJSString(Arg0_ arg0) :
244 string_(CYCopyJSString(arg0))
248 template <typename Arg0_, typename Arg1_>
249 CYJSString(Arg0_ arg0, Arg1_ arg1) :
250 string_(CYCopyJSString(arg0, arg1))
254 CYJSString &operator =(const CYJSString &rhs) {
256 string_ = CYCopyJSString(rhs.string_);
269 operator JSStringRef() const {
274 static CYUTF16String CYCastUTF16String(JSStringRef value) {
275 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
278 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value) {
279 _assert(pool != NULL);
281 CYUTF16String utf16(CYCastUTF16String(value));
282 const char *in(reinterpret_cast<const char *>(utf16.data));
284 iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL")));
286 size_t size(JSStringGetMaximumUTF8CStringSize(value));
287 char *out(new(pool) char[size]);
288 CYUTF8String utf8(out, size);
290 size = utf16.size * 2;
291 _syscall(iconv(conversion, const_cast<char **>(&in), &size, &out, &utf8.size));
294 utf8.size = out - utf8.data;
296 _syscall(iconv_close(conversion));
301 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
302 CYUTF8String utf8(CYPoolUTF8String(pool, value));
303 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
307 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
308 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
312 // XXX: this macro is unhygenic
313 #define CYCastCString_(string) ({ \
315 if (string == NULL) \
318 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
319 utf8 = reinterpret_cast<char *>(alloca(size)); \
320 JSStringGetUTF8CString(string, utf8, size); \
325 // XXX: this macro is unhygenic
326 #define CYCastCString(context, value) ({ \
330 else if (JSStringRef string = CYCopyJSString(context, value)) { \
331 utf8 = CYCastCString_(string); \
332 JSStringRelease(string); \
341 /* Objective-C Pool Release {{{ */
342 apr_status_t CYPoolRelease_(void *data) {
343 id object(reinterpret_cast<id>(data));
348 id CYPoolRelease_(apr_pool_t *pool, id object) {
351 else if (pool == NULL)
352 return [object autorelease];
354 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
359 template <typename Type_>
360 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
361 return (Type_) CYPoolRelease_(pool, (id) object);
364 /* Objective-C Strings {{{ */
365 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
367 return [value UTF8String];
369 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
370 char *string(new(pool) char[size]);
371 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
372 _throw(NSInternalInconsistencyException, "[NSString getCString:maxLength:encoding:] == NO");
377 JSStringRef CYCopyJSString_(NSString *value) {
379 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
382 return CYCopyJSString(CYPoolCString(pool, value));
386 JSStringRef CYCopyJSString(id value) {
389 // XXX: this definition scares me; is anyone using this?!
390 NSString *string([value description]);
391 return CYCopyJSString_(string);
394 NSString *CYCopyNSString(const CYUTF8String &value) {
396 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
398 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
402 NSString *CYCopyNSString(JSStringRef value) {
404 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
406 return CYCopyNSString(CYCastCString_(value));
410 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
411 return CYCopyNSString(CYJSString(context, value));
414 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
415 return CYPoolRelease(pool, CYCopyNSString(value));
418 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
419 const char *name(sel_getName(sel));
420 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
423 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
424 return CYPoolRelease(pool, CYCopyNSString(value));
427 CYUTF8String CYCastUTF8String(NSString *value) {
428 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
429 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
434 /* JavaScript *ify {{{ */
435 void CYStringify(std::ostringstream &str, const char *data, size_t size) {
436 unsigned quot(0), apos(0);
437 for (const char *value(data), *end(data + size); value != end; ++value)
440 else if (*value == '\'')
443 bool single(quot > apos);
445 str << (single ? '\'' : '"');
447 for (const char *value(data), *end(data + size); value != end; ++value)
449 case '\\': str << "\\\\"; break;
450 case '\b': str << "\\b"; break;
451 case '\f': str << "\\f"; break;
452 case '\n': str << "\\n"; break;
453 case '\r': str << "\\r"; break;
454 case '\t': str << "\\t"; break;
455 case '\v': str << "\\v"; break;
470 if (*value < 0x20 || *value >= 0x7f)
471 str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(*value);
476 str << (single ? '\'' : '"');
479 void CYNumerify(std::ostringstream &str, double value) {
481 // XXX: I want this to print 1e3 rather than 1000
482 sprintf(string, "%.17g", value);
487 static JSGlobalContextRef Context_;
488 static JSObjectRef System_;
490 static JSClassRef Functor_;
491 static JSClassRef Pointer_;
492 static JSClassRef Runtime_;
493 static JSClassRef Struct_;
496 static JSClassRef Instance_;
497 static JSClassRef Internal_;
498 static JSClassRef Message_;
499 static JSClassRef Messages_;
500 static JSClassRef Selector_;
501 static JSClassRef Super_;
503 static JSClassRef ObjectiveC_Classes_;
504 static JSClassRef ObjectiveC_Image_Classes_;
505 static JSClassRef ObjectiveC_Images_;
506 static JSClassRef ObjectiveC_Protocols_;
508 static JSObjectRef Instance_prototype_;
511 static JSObjectRef Array_;
512 static JSObjectRef Function_;
513 static JSObjectRef String_;
515 static JSStringRef Result_;
517 static JSStringRef length_;
518 static JSStringRef message_;
519 static JSStringRef name_;
520 static JSStringRef prototype_;
521 static JSStringRef toCYON_;
522 static JSStringRef toJSON_;
524 static JSObjectRef Object_prototype_;
526 static JSObjectRef Array_prototype_;
527 static JSObjectRef Array_pop_;
528 static JSObjectRef Array_push_;
529 static JSObjectRef Array_splice_;
533 static Class NSCFBoolean_;
534 static Class NSCFType_;
537 static Class NSArray_;
538 static Class NSDictionary_;
539 static Class NSMessageBuilder_;
540 static Class NSZombie_;
541 static Class Object_;
546 static void Finalize(JSObjectRef object) {
547 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
550 class Type_privateData;
560 CYValue(const void *value) :
561 value_(const_cast<void *>(value))
565 CYValue(const CYValue &rhs) :
570 virtual Type_privateData *GetType() const {
579 JSContextRef context_;
583 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
589 JSValueProtect(context_, owner_);
594 JSValueUnprotect(context_, owner_);
597 JSObjectRef GetOwner() const {
603 struct Selector_privateData :
606 Selector_privateData(SEL value) :
611 SEL GetValue() const {
612 return reinterpret_cast<SEL>(value_);
615 virtual Type_privateData *GetType() const;
618 // XXX: trick this out with associated objects!
619 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
621 return Instance_prototype_;
623 // XXX: I need to think through multi-context
624 typedef std::map<id, JSValueRef> CacheMap;
625 static CacheMap cache_;
627 JSValueRef &value(cache_[self]);
631 JSClassRef _class(NULL);
632 JSValueRef prototype;
634 if (self == NSArray_)
635 prototype = Array_prototype_;
636 else if (self == NSDictionary_)
637 prototype = Object_prototype_;
639 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
641 JSObjectRef object(JSObjectMake(context, _class, NULL));
642 JSObjectSetPrototype(context, object, prototype);
644 JSValueProtect(context, object);
654 Transient = (1 << 0),
655 Uninitialized = (1 << 1),
660 Instance(id value, Flags flags) :
666 virtual ~Instance() {
667 if ((flags_ & Transient) == 0)
668 // XXX: does this handle background threads correctly?
669 // XXX: this simply does not work on the console because I'm stupid
670 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
673 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
674 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
675 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
679 id GetValue() const {
680 return reinterpret_cast<id>(value_);
683 bool IsUninitialized() const {
684 return (flags_ & Uninitialized) != 0;
687 virtual Type_privateData *GetType() const;
695 Super(id value, Class _class) :
696 Instance(value, Instance::Transient),
701 static JSObjectRef Make(JSContextRef context, id object, Class _class) {
702 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
710 Messages(Class value) :
715 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
716 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
717 if (_class == NSArray_)
719 if (Class super = class_getSuperclass(_class))
720 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
722 JSObjectSetPrototype(context, value, Array_prototype_);*/
726 Class GetValue() const {
727 return reinterpret_cast<Class>(value_);
734 Internal(id value, JSContextRef context, JSObjectRef owner) :
735 CYOwned(value, context, owner)
739 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
740 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
743 id GetValue() const {
744 return reinterpret_cast<id>(value_);
751 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
753 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
754 lhs.name = apr_pstrdup(pool, rhs.name);
755 if (rhs.type == NULL)
758 lhs.type = new(pool) Type;
759 Copy(pool, *lhs.type, *rhs.type);
761 lhs.offset = rhs.offset;
764 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
765 size_t count(rhs.count);
767 lhs.elements = new(pool) Element[count];
768 for (size_t index(0); index != count; ++index)
769 Copy(pool, lhs.elements[index], rhs.elements[index]);
772 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
773 lhs.primitive = rhs.primitive;
774 lhs.name = apr_pstrdup(pool, rhs.name);
775 lhs.flags = rhs.flags;
777 if (sig::IsAggregate(rhs.primitive))
778 Copy(pool, lhs.data.signature, rhs.data.signature);
780 sig::Type *&lht(lhs.data.data.type);
781 sig::Type *&rht(rhs.data.data.type);
786 lht = new(pool) Type;
787 Copy(pool, *lht, *rht);
790 lhs.data.data.size = rhs.data.data.size;
794 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
796 lhs.alignment = rhs.alignment;
798 if (rhs.elements == NULL)
802 while (rhs.elements[count] != NULL)
805 lhs.elements = new(pool) ffi_type *[count + 1];
806 lhs.elements[count] = NULL;
808 for (size_t index(0); index != count; ++index) {
809 // XXX: if these are libffi native then you can just take them
810 ffi_type *ffi(new(pool) ffi_type);
811 lhs.elements[index] = ffi;
812 sig::Copy(pool, *ffi, *rhs.elements[index]);
819 struct CStringMapLess :
820 std::binary_function<const char *, const char *, bool>
822 _finline bool operator ()(const char *lhs, const char *rhs) const {
823 return strcmp(lhs, rhs) < 0;
827 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
831 sqlite3_stmt *statement;
833 _sqlcall(sqlite3_prepare(Bridge_,
835 "\"bridge\".\"mode\", "
836 "\"bridge\".\"value\" "
839 " \"bridge\".\"mode\" in (3, 4) and"
840 " \"bridge\".\"name\" = ?"
842 , -1, &statement, NULL));
844 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
849 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
853 mode = sqlite3_column_int(statement, 0);
854 value = sqlite3_column_pooled(pool, statement, 1);
857 _sqlcall(sqlite3_finalize(statement));
866 sig::Parse(pool, &type->data.signature, value, &Structor_);
870 sig::Signature signature;
871 sig::Parse(pool, &signature, value, &Structor_);
872 type = signature.elements[0].type;
877 struct Type_privateData :
881 static Type_privateData *Object;
882 static Type_privateData *Selector;
885 static JSClassRef Class_;
890 void Set(sig::Type *type) {
891 type_ = new(pool_) sig::Type;
892 sig::Copy(pool_, *type_, *type);
895 Type_privateData(apr_pool_t *pool, const char *type) :
901 sig::Signature signature;
902 sig::Parse(pool_, &signature, type, &Structor_);
903 type_ = signature.elements[0].type;
906 Type_privateData(sig::Type *type) :
913 Type_privateData(sig::Type *type, ffi_type *ffi) {
914 ffi_ = new(pool_) ffi_type;
915 sig::Copy(pool_, *ffi_, *ffi);
921 ffi_ = new(pool_) ffi_type;
923 sig::Element element;
925 element.type = type_;
928 sig::Signature signature;
929 signature.elements = &element;
933 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
941 JSClassRef Type_privateData::Class_;
944 Type_privateData *Type_privateData::Object;
945 Type_privateData *Type_privateData::Selector;
947 Type_privateData *Instance::GetType() const {
948 return Type_privateData::Object;
951 Type_privateData *Selector_privateData::GetType() const {
952 return Type_privateData::Selector;
959 Type_privateData *type_;
961 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
962 CYOwned(value, context, owner),
963 type_(new(pool_) Type_privateData(type))
968 struct Struct_privateData :
971 Type_privateData *type_;
973 Struct_privateData(JSContextRef context, JSObjectRef owner) :
974 CYOwned(NULL, context, owner)
979 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
980 static TypeMap Types_;
982 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
983 Struct_privateData *internal(new Struct_privateData(context, owner));
984 apr_pool_t *pool(internal->pool_);
985 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
986 internal->type_ = typical;
989 internal->value_ = data;
991 size_t size(typical->GetFFI()->size);
992 void *copy(apr_palloc(internal->pool_, size));
993 memcpy(copy, data, size);
994 internal->value_ = copy;
997 return JSObjectMake(context, Struct_, internal);
1000 struct Functor_privateData :
1003 sig::Signature signature_;
1006 Functor_privateData(const char *type, void (*value)()) :
1007 CYValue(reinterpret_cast<void *>(value))
1009 sig::Parse(pool_, &signature_, type, &Structor_);
1010 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
1013 void (*GetValue())() const {
1014 return reinterpret_cast<void (*)()>(value_);
1018 struct Closure_privateData :
1021 JSContextRef context_;
1022 JSObjectRef function_;
1024 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
1025 Functor_privateData(type, NULL),
1029 JSValueProtect(context_, function_);
1032 virtual ~Closure_privateData() {
1033 JSValueUnprotect(context_, function_);
1038 struct Message_privateData :
1043 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
1044 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
1050 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
1051 Instance::Flags flags;
1054 flags = Instance::Transient;
1056 flags = Instance::None;
1057 object = [object retain];
1060 return Instance::Make(context, object, flags);
1064 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
1065 return JSValueMakeBoolean(context, value);
1068 JSValueRef CYCastJSValue(JSContextRef context, double value) {
1069 return JSValueMakeNumber(context, value);
1072 #define CYCastJSValue_(Type_) \
1073 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
1074 return JSValueMakeNumber(context, static_cast<double>(value)); \
1078 CYCastJSValue_(unsigned int)
1079 CYCastJSValue_(long int)
1080 CYCastJSValue_(long unsigned int)
1081 CYCastJSValue_(long long int)
1082 CYCastJSValue_(long long unsigned int)
1084 JSValueRef CYJSUndefined(JSContextRef context) {
1085 return JSValueMakeUndefined(context);
1088 size_t CYGetIndex(const CYUTF8String &value) {
1089 if (value.data[0] != '0') {
1091 size_t index(strtoul(value.data, &end, 10));
1092 if (value.data + value.size == end)
1094 } else if (value.data[1] == '\0')
1096 return _not(size_t);
1099 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
1100 return CYGetIndex(CYPoolUTF8String(pool, value));
1103 bool CYGetOffset(const char *value, ssize_t &index) {
1104 if (value[0] != '0') {
1106 index = strtol(value, &end, 10);
1107 if (value + strlen(value) == end)
1109 } else if (value[1] == '\0') {
1118 size_t CYGetIndex(NSString *value) {
1119 return CYGetIndex(CYCastUTF8String(value));
1122 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
1123 return CYGetOffset(CYPoolCString(pool, value), index);
1128 @interface NSMethodSignature (Cycript)
1129 - (NSString *) _typeString;
1132 @interface NSObject (Cycript)
1134 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1135 - (JSType) cy$JSType;
1137 - (NSObject *) cy$toJSON:(NSString *)key;
1138 - (NSString *) cy$toCYON;
1139 - (NSString *) cy$toKey;
1141 - (bool) cy$hasProperty:(NSString *)name;
1142 - (NSObject *) cy$getProperty:(NSString *)name;
1143 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
1144 - (bool) cy$deleteProperty:(NSString *)name;
1149 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1154 NSString *CYCastNSCYON(id value) {
1160 Class _class(object_getClass(value));
1161 SEL sel(@selector(cy$toCYON));
1163 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
1164 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1165 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1166 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1167 string = [value cy$toCYON];
1170 if (value == NSZombie_)
1171 string = @"_NSZombie_";
1172 else if (_class == NSZombie_)
1173 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1174 // XXX: frowny /in/ the pants
1175 else if (value == NSMessageBuilder_ || value == Object_)
1178 string = [NSString stringWithFormat:@"%@", value];
1181 // XXX: frowny pants
1183 string = @"undefined";
1192 struct PropertyAttributes {
1197 const char *variable;
1199 const char *getter_;
1200 const char *setter_;
1210 PropertyAttributes(objc_property_t property) :
1222 name = property_getName(property);
1223 const char *attributes(property_getAttributes(property));
1225 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
1227 case 'R': readonly = true; break;
1228 case 'C': copy = true; break;
1229 case '&': retain = true; break;
1230 case 'N': nonatomic = true; break;
1231 case 'G': getter_ = token + 1; break;
1232 case 'S': setter_ = token + 1; break;
1233 case 'V': variable = token + 1; break;
1237 /*if (variable == NULL) {
1238 variable = property_getName(property);
1239 size_t size(strlen(variable));
1240 char *name(new(pool_) char[size + 2]);
1242 memcpy(name + 1, variable, size);
1243 name[size + 1] = '\0';
1248 const char *Getter() {
1249 if (getter_ == NULL)
1250 getter_ = apr_pstrdup(pool_, name);
1254 const char *Setter() {
1255 if (setter_ == NULL && !readonly) {
1256 size_t length(strlen(name));
1258 char *temp(new(pool_) char[length + 5]);
1264 temp[3] = toupper(name[0]);
1265 memcpy(temp + 4, name + 1, length - 1);
1268 temp[length + 3] = ':';
1269 temp[length + 4] = '\0';
1282 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
1283 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
1290 @interface CYWebUndefined : NSObject {
1293 + (CYWebUndefined *) undefined;
1297 @implementation CYWebUndefined
1299 + (CYWebUndefined *) undefined {
1300 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
1306 #define WebUndefined CYWebUndefined
1311 /* Bridge: NSArray {{{ */
1312 @implementation NSArray (Cycript)
1314 - (NSString *) cy$toCYON {
1315 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1316 [json appendString:@"["];
1320 for (id object in self) {
1323 for (size_t index(0), count([self count]); index != count; ++index) {
1324 object = [self objectAtIndex:index];
1327 [json appendString:@","];
1330 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
1331 [json appendString:CYCastNSCYON(object)];
1333 [json appendString:@","];
1338 [json appendString:@"]"];
1342 - (bool) cy$hasProperty:(NSString *)name {
1343 if ([name isEqualToString:@"length"])
1346 size_t index(CYGetIndex(name));
1347 if (index == _not(size_t) || index >= [self count])
1348 return [super cy$hasProperty:name];
1353 - (NSObject *) cy$getProperty:(NSString *)name {
1354 if ([name isEqualToString:@"length"]) {
1355 NSUInteger count([self count]);
1357 return [NSNumber numberWithUnsignedInteger:count];
1359 return [NSNumber numberWithUnsignedInt:count];
1363 size_t index(CYGetIndex(name));
1364 if (index == _not(size_t) || index >= [self count])
1365 return [super cy$getProperty:name];
1367 return [self objectAtIndex:index];
1372 /* Bridge: NSDictionary {{{ */
1373 @implementation NSDictionary (Cycript)
1375 - (NSString *) cy$toCYON {
1376 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1377 [json appendString:@"{"];
1381 for (id key in self) {
1383 NSEnumerator *keys([self keyEnumerator]);
1384 while (id key = [keys nextObject]) {
1387 [json appendString:@","];
1390 [json appendString:[key cy$toKey]];
1391 [json appendString:@":"];
1392 NSObject *object([self objectForKey:key]);
1393 [json appendString:CYCastNSCYON(object)];
1396 [json appendString:@"}"];
1400 - (bool) cy$hasProperty:(NSString *)name {
1401 return [self objectForKey:name] != nil;
1404 - (NSObject *) cy$getProperty:(NSString *)name {
1405 return [self objectForKey:name];
1410 /* Bridge: NSMutableArray {{{ */
1411 @implementation NSMutableArray (Cycript)
1413 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1414 if ([name isEqualToString:@"length"]) {
1415 // XXX: is this not intelligent?
1416 NSNumber *number(reinterpret_cast<NSNumber *>(value));
1418 NSUInteger size([number unsignedIntegerValue]);
1420 NSUInteger size([number unsignedIntValue]);
1422 NSUInteger count([self count]);
1424 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1425 else if (size != count) {
1426 WebUndefined *undefined([WebUndefined undefined]);
1427 for (size_t i(count); i != size; ++i)
1428 [self addObject:undefined];
1433 size_t index(CYGetIndex(name));
1434 if (index == _not(size_t))
1435 return [super cy$setProperty:name to:value];
1437 id object(value ?: [NSNull null]);
1439 size_t count([self count]);
1441 [self replaceObjectAtIndex:index withObject:object];
1443 if (index != count) {
1444 WebUndefined *undefined([WebUndefined undefined]);
1445 for (size_t i(count); i != index; ++i)
1446 [self addObject:undefined];
1449 [self addObject:object];
1455 - (bool) cy$deleteProperty:(NSString *)name {
1456 size_t index(CYGetIndex(name));
1457 if (index == _not(size_t) || index >= [self count])
1458 return [super cy$deleteProperty:name];
1459 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1465 /* Bridge: NSMutableDictionary {{{ */
1466 @implementation NSMutableDictionary (Cycript)
1468 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1469 [self setObject:(value ?: [NSNull null]) forKey:name];
1473 - (bool) cy$deleteProperty:(NSString *)name {
1474 if ([self objectForKey:name] == nil)
1477 [self removeObjectForKey:name];
1484 /* Bridge: NSNumber {{{ */
1485 @implementation NSNumber (Cycript)
1487 - (JSType) cy$JSType {
1489 // XXX: this just seems stupid
1490 if ([self class] == NSCFBoolean_)
1491 return kJSTypeBoolean;
1493 return kJSTypeNumber;
1496 - (NSObject *) cy$toJSON:(NSString *)key {
1500 - (NSString *) cy$toCYON {
1501 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1504 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1505 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1510 /* Bridge: NSNull {{{ */
1511 @implementation NSNull (Cycript)
1513 - (JSType) cy$JSType {
1517 - (NSObject *) cy$toJSON:(NSString *)key {
1521 - (NSString *) cy$toCYON {
1527 /* Bridge: NSObject {{{ */
1528 @implementation NSObject (Cycript)
1530 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1531 return CYMakeInstance(context, self, false);
1534 - (JSType) cy$JSType {
1535 return kJSTypeObject;
1538 - (NSObject *) cy$toJSON:(NSString *)key {
1539 return [self description];
1542 - (NSString *) cy$toCYON {
1543 return [[self cy$toJSON:@""] cy$toCYON];
1546 - (NSString *) cy$toKey {
1547 return [self cy$toCYON];
1550 - (bool) cy$hasProperty:(NSString *)name {
1554 - (NSObject *) cy$getProperty:(NSString *)name {
1558 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1562 - (bool) cy$deleteProperty:(NSString *)name {
1568 /* Bridge: NSProxy {{{ */
1569 @implementation NSProxy (Cycript)
1571 - (NSObject *) cy$toJSON:(NSString *)key {
1572 return [self description];
1575 - (NSString *) cy$toCYON {
1576 return [[self cy$toJSON:@""] cy$toCYON];
1581 /* Bridge: NSString {{{ */
1582 @implementation NSString (Cycript)
1584 - (JSType) cy$JSType {
1585 return kJSTypeString;
1588 - (NSObject *) cy$toJSON:(NSString *)key {
1592 - (NSString *) cy$toCYON {
1593 std::ostringstream str;
1594 CYUTF8String string(CYCastUTF8String(self));
1595 CYStringify(str, string.data, string.size);
1596 std::string value(str.str());
1597 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1600 - (NSString *) cy$toKey {
1601 const char *value([self UTF8String]);
1602 size_t size(strlen(value));
1607 if (DigitRange_[value[0]]) {
1608 size_t index(CYGetIndex(self));
1609 if (index == _not(size_t))
1612 if (!WordStartRange_[value[0]])
1614 for (size_t i(1); i != size; ++i)
1615 if (!WordEndRange_[value[i]])
1622 return [self cy$toCYON];
1627 /* Bridge: WebUndefined {{{ */
1628 @implementation WebUndefined (Cycript)
1630 - (JSType) cy$JSType {
1631 return kJSTypeUndefined;
1634 - (NSObject *) cy$toJSON:(NSString *)key {
1638 - (NSString *) cy$toCYON {
1639 return @"undefined";
1642 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1643 return CYJSUndefined(context);
1649 /* Bridge: CYJSObject {{{ */
1650 @interface CYJSObject : NSMutableDictionary {
1651 JSObjectRef object_;
1652 JSContextRef context_;
1655 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1657 - (NSObject *) cy$toJSON:(NSString *)key;
1659 - (NSUInteger) count;
1660 - (id) objectForKey:(id)key;
1661 - (NSEnumerator *) keyEnumerator;
1662 - (void) setObject:(id)object forKey:(id)key;
1663 - (void) removeObjectForKey:(id)key;
1667 /* Bridge: CYJSArray {{{ */
1668 @interface CYJSArray : NSMutableArray {
1669 JSObjectRef object_;
1670 JSContextRef context_;
1673 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1675 - (NSUInteger) count;
1676 - (id) objectAtIndex:(NSUInteger)index;
1678 - (void) addObject:(id)anObject;
1679 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1680 - (void) removeLastObject;
1681 - (void) removeObjectAtIndex:(NSUInteger)index;
1682 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1689 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1690 JSValueRef exception(NULL);
1691 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1692 CYThrow(context, exception);
1693 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1694 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1697 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1698 if (!JSValueIsObjectOfClass(context, object, Instance_))
1699 return CYCastNSObject_(pool, context, object);
1701 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1702 return internal->GetValue();
1707 double CYCastDouble(const char *value, size_t size) {
1709 double number(strtod(value, &end));
1710 if (end != value + size)
1715 double CYCastDouble(const char *value) {
1716 return CYCastDouble(value, strlen(value));
1719 double CYCastDouble(JSContextRef context, JSValueRef value) {
1720 JSValueRef exception(NULL);
1721 double number(JSValueToNumber(context, value, &exception));
1722 CYThrow(context, exception);
1727 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
1728 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
1732 bool CYCastBool(JSContextRef context, JSValueRef value) {
1733 return JSValueToBoolean(context, value);
1737 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1741 switch (JSType type = JSValueGetType(context, value)) {
1742 case kJSTypeUndefined:
1743 object = [WebUndefined undefined];
1751 case kJSTypeBoolean:
1753 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
1756 object = [[NSNumber alloc] initWithBool:CYCastBool(context, value)];
1762 object = CYCopyNSNumber(context, value);
1767 object = CYCopyNSString(context, value);
1772 // XXX: this might could be more efficient
1773 object = CYCastNSObject(pool, context, (JSObjectRef) value);
1778 _throw(NSInternalInconsistencyException, "JSValueGetType() == 0x%x", type);
1785 return CYPoolRelease(pool, object);
1787 return [object retain];
1790 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1791 return CYNSObject(pool, context, value, true);
1793 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1794 return CYNSObject(pool, context, value, false);
1797 static bool CYIsClass(id self) {
1798 // XXX: this is a lame object_isClass
1799 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1802 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1803 id self(CYCastNSObject(pool, context, value));
1804 if (CYIsClass(self))
1805 return (Class) self;
1806 _throw(NSInvalidArgumentException, "got something that is not a Class");
1810 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1812 size_t size(JSPropertyNameArrayGetCount(names));
1813 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1814 for (size_t index(0); index != size; ++index)
1815 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1820 void CYThrow(JSContextRef context, JSValueRef value) {
1824 @throw CYCastNSObject(NULL, context, value);
1827 throw "throwing something";
1831 JSValueRef CYJSNull(JSContextRef context) {
1832 return JSValueMakeNull(context);
1835 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1836 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1839 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1840 return CYCastJSValue(context, CYJSString(value));
1844 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1846 return CYJSNull(context);
1847 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1848 return [value cy$JSValueInContext:context];
1850 return CYMakeInstance(context, value, false);
1854 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1855 JSValueRef exception(NULL);
1856 JSObjectRef object(JSValueToObject(context, value, &exception));
1857 CYThrow(context, exception);
1861 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1862 if (exception == NULL)
1864 *exception = CYCastJSValue(context, error);
1867 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1868 JSValueRef exception(NULL);
1869 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1870 CYThrow(context, exception);
1874 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1875 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
1879 @implementation CYJSObject
1881 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1882 if ((self = [super init]) != nil) {
1885 JSValueProtect(context_, object_);
1890 JSValueUnprotect(context_, object_);
1894 - (NSObject *) cy$toJSON:(NSString *)key {
1895 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1896 if (!CYIsCallable(context_, toJSON))
1897 return [super cy$toJSON:key];
1899 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1900 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1901 // XXX: do I really want an NSNull here?!
1902 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1906 - (NSString *) cy$toCYON {
1907 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1908 if (!CYIsCallable(context_, toCYON)) super:
1909 return [super cy$toCYON];
1910 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1911 return CYCastNSString(NULL, CYJSString(context_, value));
1915 - (NSUInteger) count {
1916 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1917 size_t size(JSPropertyNameArrayGetCount(names));
1918 JSPropertyNameArrayRelease(names);
1922 - (id) objectForKey:(id)key {
1923 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1924 if (JSValueIsUndefined(context_, value))
1926 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1929 - (NSEnumerator *) keyEnumerator {
1930 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1931 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1932 JSPropertyNameArrayRelease(names);
1936 - (void) setObject:(id)object forKey:(id)key {
1937 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1940 - (void) removeObjectForKey:(id)key {
1941 JSValueRef exception(NULL);
1942 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1943 CYThrow(context_, exception);
1948 @implementation CYJSArray
1950 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1951 if ((self = [super init]) != nil) {
1954 JSValueProtect(context_, object_);
1959 JSValueUnprotect(context_, object_);
1963 - (NSUInteger) count {
1964 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1967 - (id) objectAtIndex:(NSUInteger)index {
1968 size_t bounds([self count]);
1969 if (index >= bounds)
1970 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1971 JSValueRef exception(NULL);
1972 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1973 CYThrow(context_, exception);
1974 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1977 - (void) addObject:(id)object {
1978 JSValueRef exception(NULL);
1979 JSValueRef arguments[1];
1980 arguments[0] = CYCastJSValue(context_, object);
1981 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1982 CYThrow(context_, exception);
1985 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1986 size_t bounds([self count] + 1);
1987 if (index >= bounds)
1988 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1989 JSValueRef exception(NULL);
1990 JSValueRef arguments[3];
1991 arguments[0] = CYCastJSValue(context_, index);
1992 arguments[1] = CYCastJSValue(context_, 0);
1993 arguments[2] = CYCastJSValue(context_, object);
1994 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1995 CYThrow(context_, exception);
1998 - (void) removeLastObject {
1999 JSValueRef exception(NULL);
2000 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
2001 CYThrow(context_, exception);
2004 - (void) removeObjectAtIndex:(NSUInteger)index {
2005 size_t bounds([self count]);
2006 if (index >= bounds)
2007 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
2008 JSValueRef exception(NULL);
2009 JSValueRef arguments[2];
2010 arguments[0] = CYCastJSValue(context_, index);
2011 arguments[1] = CYCastJSValue(context_, 1);
2012 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
2013 CYThrow(context_, exception);
2016 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
2017 size_t bounds([self count]);
2018 if (index >= bounds)
2019 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
2020 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
2026 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
2027 switch (JSType type = JSValueGetType(context, value)) {
2028 case kJSTypeUndefined:
2032 case kJSTypeBoolean:
2033 return CYCastBool(context, value) ? "true" : "false";
2035 case kJSTypeNumber: {
2036 std::ostringstream str;
2037 CYNumerify(str, CYCastDouble(context, value));
2038 std::string value(str.str());
2039 return apr_pstrmemdup(pool, value.c_str(), value.size());
2042 case kJSTypeString: {
2043 std::ostringstream str;
2044 CYUTF8String string(CYPoolUTF8String(pool, CYJSString(context, value)));
2045 CYStringify(str, string.data, string.size);
2046 std::string value(str.str());
2047 return apr_pstrmemdup(pool, value.c_str(), value.size());
2050 case kJSTypeObject: {
2051 JSObjectRef object((JSObjectRef) value);
2052 JSValueRef toCYON(CYGetProperty(context, object, toCYON_));
2054 if (CYIsCallable(context, toCYON)) {
2055 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
2056 return CYPoolCString(pool, context, value);
2059 return "\"[object /* XXX: implement something awesome */]\"";
2063 _throw(NSInternalInconsistencyException, "JSValueGetType() == 0x%x", type);
2070 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
2074 JSObjectRef object_;
2082 // XXX: delete object_? ;(
2085 static CYInternal *Get(id self) {
2086 CYInternal *internal(NULL);
2087 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
2088 // XXX: do something epic? ;P
2094 static CYInternal *Set(id self) {
2095 CYInternal *internal(NULL);
2096 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
2097 if (internal == NULL) {
2098 internal = new CYInternal();
2099 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
2102 // XXX: do something epic? ;P
2108 bool HasProperty(JSContextRef context, JSStringRef name) {
2109 if (object_ == NULL)
2111 return JSObjectHasProperty(context, object_, name);
2114 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
2115 if (object_ == NULL)
2117 return CYGetProperty(context, object_, name);
2120 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
2121 if (object_ == NULL)
2122 object_ = JSObjectMake(context, NULL, NULL);
2123 CYSetProperty(context, object_, name, value);
2129 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
2130 Selector_privateData *internal(new Selector_privateData(sel));
2131 return JSObjectMake(context, Selector_, internal);
2135 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
2136 Pointer *internal(new Pointer(pointer, context, owner, type));
2137 return JSObjectMake(context, Pointer_, internal);
2140 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
2141 Functor_privateData *internal(new Functor_privateData(type, function));
2142 return JSObjectMake(context, Functor_, internal);
2145 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
2146 return CYGetOffset(CYPoolCString(pool, value), index);
2149 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
2150 switch (JSValueGetType(context, value)) {
2153 /*case kJSTypeString:
2154 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
2156 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
2157 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
2158 return internal->value_;
2161 double number(CYCastDouble(context, value));
2162 if (std::isnan(number))
2163 _throw(NSInvalidArgumentException, "cannot convert value to pointer");
2164 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
2168 template <typename Type_>
2169 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
2170 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
2174 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
2175 if (JSValueIsObjectOfClass(context, value, Selector_)) {
2176 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2177 return reinterpret_cast<SEL>(internal->value_);
2179 return CYCastPointer<SEL>(context, value);
2183 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
2184 switch (type->primitive) {
2185 case sig::boolean_P:
2186 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
2189 #define CYPoolFFI_(primitive, native) \
2190 case sig::primitive ## _P: \
2191 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
2194 CYPoolFFI_(uchar, unsigned char)
2195 CYPoolFFI_(char, char)
2196 CYPoolFFI_(ushort, unsigned short)
2197 CYPoolFFI_(short, short)
2198 CYPoolFFI_(ulong, unsigned long)
2199 CYPoolFFI_(long, long)
2200 CYPoolFFI_(uint, unsigned int)
2201 CYPoolFFI_(int, int)
2202 CYPoolFFI_(ulonglong, unsigned long long)
2203 CYPoolFFI_(longlong, long long)
2204 CYPoolFFI_(float, float)
2205 CYPoolFFI_(double, double)
2209 case sig::typename_P:
2210 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
2213 case sig::selector_P:
2214 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
2218 case sig::pointer_P:
2219 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
2223 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
2226 case sig::struct_P: {
2227 uint8_t *base(reinterpret_cast<uint8_t *>(data));
2228 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
2229 for (size_t index(0); index != type->data.signature.count; ++index) {
2230 sig::Element *element(&type->data.signature.elements[index]);
2231 ffi_type *field(ffi->elements[index]);
2234 if (aggregate == NULL)
2237 rhs = CYGetProperty(context, aggregate, index);
2238 if (JSValueIsUndefined(context, rhs)) {
2239 if (element->name != NULL)
2240 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
2243 if (JSValueIsUndefined(context, rhs)) undefined:
2244 _throw(NSInvalidArgumentException, "unable to extract structure value");
2248 CYPoolFFI(pool, context, element->type, field, base, rhs);
2250 base += field->size;
2258 fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
2263 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
2266 switch (type->primitive) {
2267 case sig::boolean_P:
2268 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
2271 #define CYFromFFI_(primitive, native) \
2272 case sig::primitive ## _P: \
2273 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
2276 CYFromFFI_(uchar, unsigned char)
2277 CYFromFFI_(char, char)
2278 CYFromFFI_(ushort, unsigned short)
2279 CYFromFFI_(short, short)
2280 CYFromFFI_(ulong, unsigned long)
2281 CYFromFFI_(long, long)
2282 CYFromFFI_(uint, unsigned int)
2283 CYFromFFI_(int, int)
2284 CYFromFFI_(ulonglong, unsigned long long)
2285 CYFromFFI_(longlong, long long)
2286 CYFromFFI_(float, float)
2287 CYFromFFI_(double, double)
2290 case sig::object_P: {
2291 if (id object = *reinterpret_cast<id *>(data)) {
2292 value = CYCastJSValue(context, object);
2298 case sig::typename_P:
2299 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
2302 case sig::selector_P:
2303 if (SEL sel = *reinterpret_cast<SEL *>(data))
2304 value = CYMakeSelector(context, sel);
2309 case sig::pointer_P:
2310 if (void *pointer = *reinterpret_cast<void **>(data))
2311 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
2316 if (char *utf8 = *reinterpret_cast<char **>(data))
2317 value = CYCastJSValue(context, utf8);
2322 value = CYMakeStruct(context, data, type, ffi, owner);
2326 value = CYJSUndefined(context);
2330 value = CYJSNull(context);
2334 fprintf(stderr, "CYFromFFI(%c)\n", type->primitive);
2342 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
2343 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
2347 method_getReturnType(method, type, sizeof(type));
2352 // XXX: possibly use a more "awesome" check?
2358 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, objc_method *method) {
2360 return method_getTypeEncoding(method);
2362 const char *name(sel_getName(sel));
2364 sqlite3_stmt *statement;
2366 _sqlcall(sqlite3_prepare(Bridge_,
2368 "\"bridge\".\"mode\", "
2369 "\"bridge\".\"value\" "
2372 " \"bridge\".\"mode\" in (3, 4) and"
2373 " \"bridge\".\"name\" = ?"
2375 , -1, &statement, NULL));
2377 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
2382 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
2386 mode = sqlite3_column_int(statement, 0);
2387 value = sqlite3_column_pooled(pool, statement, 1);
2390 _sqlcall(sqlite3_finalize(statement));
2399 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2400 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2402 JSContextRef context(internal->context_);
2404 size_t count(internal->cif_.nargs);
2405 JSValueRef values[count];
2407 for (size_t index(0); index != count; ++index)
2408 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2410 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2411 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2415 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2416 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2418 JSContextRef context(internal->context_);
2420 size_t count(internal->cif_.nargs);
2421 JSValueRef values[count];
2423 for (size_t index(0); index != count; ++index)
2424 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2426 JSObjectRef _this(CYCastJSObject(context, values[0]));
2428 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2429 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2433 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2434 // XXX: in case of exceptions this will leak
2435 // XXX: in point of fact, this may /need/ to leak :(
2436 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2438 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2439 NULL, sizeof(ffi_closure),
2440 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2444 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2445 _assert(status == FFI_OK);
2447 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2449 internal->value_ = closure;
2454 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2455 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2456 return JSObjectMake(context, Functor_, internal);
2459 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2460 JSValueRef exception(NULL);
2461 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2462 CYThrow(context, exception);
2465 JSObjectRef function(CYCastJSObject(context, value));
2466 return CYMakeFunctor(context, function, type);
2468 void (*function)()(CYCastPointer<void (*)()>(context, value));
2469 return CYMakeFunctor(context, function, type);
2474 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2475 Message_privateData *internal(new Message_privateData(sel, type, imp));
2476 return JSObjectMake(context, Message_, internal);
2479 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2480 JSObjectRef function(CYCastJSObject(context, value));
2481 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2482 return reinterpret_cast<IMP>(internal->GetValue());
2485 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2486 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2487 Class _class(internal->GetValue());
2490 const char *name(CYPoolCString(pool, property));
2492 if (SEL sel = sel_getUid(name))
2493 if (class_getInstanceMethod(_class, sel) != NULL)
2499 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2500 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2501 Class _class(internal->GetValue());
2504 const char *name(CYPoolCString(pool, property));
2506 if (SEL sel = sel_getUid(name))
2507 if (objc_method *method = class_getInstanceMethod(_class, sel))
2508 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2513 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2514 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2515 Class _class(internal->GetValue());
2518 const char *name(CYPoolCString(pool, property));
2520 SEL sel(sel_registerName(name));
2522 objc_method *method(class_getInstanceMethod(_class, sel));
2527 if (JSValueIsObjectOfClass(context, value, Message_)) {
2528 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2529 type = sig::Unparse(pool, &message->signature_);
2530 imp = reinterpret_cast<IMP>(message->GetValue());
2532 type = CYPoolTypeEncoding(pool, _class, sel, method);
2533 imp = CYMakeMessage(context, value, type);
2537 method_setImplementation(method, imp);
2539 class_replaceMethod(_class, sel, imp, type);
2545 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2546 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2547 Class _class(internal->GetValue());
2550 const char *name(CYPoolCString(pool, property));
2552 if (SEL sel = sel_getUid(name))
2553 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
2554 objc_method_list list = {NULL, 1, {method}};
2555 class_removeMethods(_class, &list);
2563 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2564 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2565 Class _class(internal->GetValue());
2568 objc_method **data(class_copyMethodList(_class, &size));
2569 for (size_t i(0); i != size; ++i)
2570 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2574 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2575 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2576 id self(internal->GetValue());
2578 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2582 NSString *name(CYCastNSString(pool, property));
2584 if (CYInternal *internal = CYInternal::Get(self))
2585 if (internal->HasProperty(context, property))
2588 Class _class(object_getClass(self));
2591 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2592 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2593 if ([self cy$hasProperty:name])
2595 } CYPoolCatch(false)
2597 const char *string(CYPoolCString(pool, name));
2599 if (class_getProperty(_class, string) != NULL)
2602 if (SEL sel = sel_getUid(string))
2603 if (CYImplements(self, _class, sel, true))
2609 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2610 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2611 id self(internal->GetValue());
2613 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2614 return Internal::Make(context, self, object);
2618 NSString *name(CYCastNSString(pool, property));
2620 if (CYInternal *internal = CYInternal::Get(self))
2621 if (JSValueRef value = internal->GetProperty(context, property))
2625 if (NSObject *data = [self cy$getProperty:name])
2626 return CYCastJSValue(context, data);
2629 const char *string(CYPoolCString(pool, name));
2630 Class _class(object_getClass(self));
2633 if (objc_property_t property = class_getProperty(_class, string)) {
2634 PropertyAttributes attributes(property);
2635 SEL sel(sel_registerName(attributes.Getter()));
2636 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
2640 if (SEL sel = sel_getUid(string))
2641 if (CYImplements(self, _class, sel, true))
2642 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
2648 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2649 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2650 id self(internal->GetValue());
2655 NSString *name(CYCastNSString(pool, property));
2656 NSObject *data(CYCastNSObject(pool, context, value));
2659 if ([self cy$setProperty:name to:data])
2663 const char *string(CYPoolCString(pool, name));
2664 Class _class(object_getClass(self));
2667 if (objc_property_t property = class_getProperty(_class, string)) {
2668 PropertyAttributes attributes(property);
2669 if (const char *setter = attributes.Setter()) {
2670 SEL sel(sel_registerName(setter));
2671 JSValueRef arguments[1] = {value};
2672 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
2678 size_t length(strlen(string));
2680 char set[length + 5];
2686 if (string[0] != '\0') {
2687 set[3] = toupper(string[0]);
2688 memcpy(set + 4, string + 1, length - 1);
2691 set[length + 3] = ':';
2692 set[length + 4] = '\0';
2694 if (SEL sel = sel_getUid(set))
2695 if (CYImplements(self, _class, sel, false)) {
2696 JSValueRef arguments[1] = {value};
2697 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
2700 if (CYInternal *internal = CYInternal::Set(self)) {
2701 internal->SetProperty(context, property, value);
2709 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2710 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2711 id self(internal->GetValue());
2715 NSString *name(CYCastNSString(NULL, property));
2716 return [self cy$deleteProperty:name];
2721 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2722 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2723 id self(internal->GetValue());
2726 Class _class(object_getClass(self));
2730 objc_property_t *data(class_copyPropertyList(_class, &size));
2731 for (size_t i(0); i != size; ++i)
2732 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2737 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2739 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2740 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2745 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2746 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2747 Class _class(internal->GetValue());
2748 if (!CYIsClass(_class))
2751 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2752 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2753 // XXX: this isn't always safe
2755 return [linternal->GetValue() isKindOfClass:_class];
2762 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2763 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2766 id self(internal->GetValue());
2767 const char *name(CYPoolCString(pool, property));
2769 if (object_getInstanceVariable(self, name, NULL) != NULL)
2775 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2776 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2780 id self(internal->GetValue());
2781 const char *name(CYPoolCString(pool, property));
2783 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2784 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2785 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2792 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2793 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2797 id self(internal->GetValue());
2798 const char *name(CYPoolCString(pool, property));
2800 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2801 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2802 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2810 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2811 if (Class super = class_getSuperclass(_class))
2812 Internal_getPropertyNames_(super, names);
2815 Ivar *data(class_copyIvarList(_class, &size));
2816 for (size_t i(0); i != size; ++i)
2817 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2821 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2822 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2825 id self(internal->GetValue());
2826 Class _class(object_getClass(self));
2828 Internal_getPropertyNames_(_class, names);
2831 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2832 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2833 return internal->GetOwner();
2837 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2838 Type_privateData *typical(internal->type_);
2839 sig::Type *type(typical->type_);
2843 const char *name(CYPoolCString(pool, property));
2844 size_t length(strlen(name));
2845 double number(CYCastDouble(name, length));
2847 size_t count(type->data.signature.count);
2849 if (std::isnan(number)) {
2850 if (property == NULL)
2853 sig::Element *elements(type->data.signature.elements);
2855 for (size_t local(0); local != count; ++local) {
2856 sig::Element *element(&elements[local]);
2857 if (element->name != NULL && strcmp(name, element->name) == 0) {
2865 index = static_cast<ssize_t>(number);
2866 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2871 ffi_type **elements(typical->GetFFI()->elements);
2873 base = reinterpret_cast<uint8_t *>(internal->value_);
2874 for (ssize_t local(0); local != index; ++local)
2875 base += elements[local]->size;
2880 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2881 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2882 Type_privateData *typical(internal->type_);
2884 ffi_type *ffi(typical->GetFFI());
2886 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2887 base += ffi->size * index;
2889 JSObjectRef owner(internal->GetOwner() ?: object);
2892 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2896 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2898 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2899 Type_privateData *typical(internal->type_);
2901 if (typical->type_ == NULL)
2905 if (!CYGetOffset(pool, property, offset))
2908 return Pointer_getIndex(context, object, offset, exception);
2911 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2912 return Pointer_getIndex(context, object, 0, exception);
2915 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2916 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2917 Type_privateData *typical(internal->type_);
2919 ffi_type *ffi(typical->GetFFI());
2921 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2922 base += ffi->size * index;
2925 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2930 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2932 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2933 Type_privateData *typical(internal->type_);
2935 if (typical->type_ == NULL)
2939 if (!CYGetOffset(pool, property, offset))
2942 return Pointer_setIndex(context, object, offset, value, exception);
2945 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2946 return Pointer_setIndex(context, object, 0, value, exception);
2949 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2950 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2951 Type_privateData *typical(internal->type_);
2952 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2955 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2957 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2958 Type_privateData *typical(internal->type_);
2964 if (!Index_(pool, internal, property, index, base))
2967 JSObjectRef owner(internal->GetOwner() ?: object);
2969 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2973 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2975 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2976 Type_privateData *typical(internal->type_);
2982 if (!Index_(pool, internal, property, index, base))
2985 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2990 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2991 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2992 Type_privateData *typical(internal->type_);
2993 sig::Type *type(typical->type_);
2998 size_t count(type->data.signature.count);
2999 sig::Element *elements(type->data.signature.elements);
3003 for (size_t index(0); index != count; ++index) {
3005 name = elements[index].name;
3008 sprintf(number, "%lu", index);
3012 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
3016 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)()) {
3018 if (setups + count != signature->count - 1)
3019 _throw(NSInvalidArgumentException, "incorrect number of arguments to ffi function");
3021 size_t size(setups + count);
3023 memcpy(values, setup, sizeof(void *) * setups);
3025 for (size_t index(setups); index != size; ++index) {
3026 sig::Element *element(&signature->elements[index + 1]);
3027 ffi_type *ffi(cif->arg_types[index]);
3029 values[index] = new(pool) uint8_t[ffi->size];
3030 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
3033 uint8_t value[cif->rtype->size];
3034 ffi_call(cif, function, value, values);
3036 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
3041 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3044 NSString *name(CYCastNSString(pool, property));
3045 if (Class _class = NSClassFromString(name))
3046 return CYMakeInstance(context, _class, true);
3051 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3052 size_t size(objc_getClassList(NULL, 0));
3053 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
3056 size_t writ(objc_getClassList(data, size));
3059 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
3065 for (size_t i(0); i != writ; ++i)
3066 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
3072 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3073 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
3077 const char *name(CYPoolCString(pool, property));
3079 const char **data(objc_copyClassNamesForImage(internal, &size));
3081 for (size_t i(0); i != size; ++i)
3082 if (strcmp(name, data[i]) == 0) {
3083 if (Class _class = objc_getClass(name)) {
3084 value = CYMakeInstance(context, _class, true);
3096 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3097 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
3099 const char **data(objc_copyClassNamesForImage(internal, &size));
3100 for (size_t i(0); i != size; ++i)
3101 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3105 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3108 const char *name(CYPoolCString(pool, property));
3110 const char **data(objc_copyImageNames(&size));
3111 for (size_t i(0); i != size; ++i)
3112 if (strcmp(name, data[i]) == 0) {
3121 JSObjectRef value(JSObjectMake(context, NULL, NULL));
3122 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
3127 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3129 const char **data(objc_copyImageNames(&size));
3130 for (size_t i(0); i != size; ++i)
3131 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3135 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3138 NSString *name(CYCastNSString(pool, property));
3139 if (Protocol *protocol = NSProtocolFromString(name))
3140 return CYMakeInstance(context, protocol, true);
3145 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3147 Protocol **data(objc_copyProtocolList(&size));
3148 for (size_t i(0); i != size; ++i)
3149 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
3154 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
3155 Type_privateData *internal(new Type_privateData(NULL, type));
3156 return JSObjectMake(context, Type_privateData::Class_, internal);
3159 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
3160 Type_privateData *internal(new Type_privateData(type));
3161 return JSObjectMake(context, Type_privateData::Class_, internal);
3164 static void *CYCastSymbol(const char *name) {
3165 return dlsym(RTLD_DEFAULT, name);
3168 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3170 if (JSStringIsEqualToUTF8CString(property, "nil"))
3171 return Instance::Make(context, nil);
3176 const char *name(CYPoolCString(pool, property));
3179 if (Class _class = objc_getClass(name))
3180 return CYMakeInstance(context, _class, true);
3183 sqlite3_stmt *statement;
3185 _sqlcall(sqlite3_prepare(Bridge_,
3187 "\"bridge\".\"mode\", "
3188 "\"bridge\".\"value\" "
3191 " \"bridge\".\"name\" = ?"
3193 , -1, &statement, NULL));
3195 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
3200 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
3204 mode = sqlite3_column_int(statement, 0);
3205 value = sqlite3_column_pooled(pool, statement, 1);
3208 _sqlcall(sqlite3_finalize(statement));
3217 return JSEvaluateScript(CYGetJSContext(), CYJSString(value), NULL, NULL, 0, NULL);
3219 return CYMakeFunctor(context, reinterpret_cast<void (*)()>(CYCastSymbol(name)), value);
3222 // XXX: this is horrendously inefficient
3223 sig::Signature signature;
3224 sig::Parse(pool, &signature, value, &Structor_);
3226 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3227 return CYFromFFI(context, signature.elements[0].type, cif.rtype, CYCastSymbol(name));
3230 // XXX: implement case 3
3232 return CYMakeType(context, value);
3238 static bool stret(ffi_type *ffi_type) {
3239 return ffi_type->type == FFI_TYPE_STRUCT && (
3240 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
3241 struct_forward_array[ffi_type->size] != 0
3246 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3251 printf("%s\n", CYCastCString(context, arguments[0]));
3252 return CYJSUndefined(context);
3257 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
3261 _class = object_getClass(self);
3263 if (objc_method *method = class_getInstanceMethod(_class, _cmd))
3264 type = method_getTypeEncoding(method);
3268 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
3270 _throw(NSInvalidArgumentException, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3271 type = CYPoolCString(pool, [method _typeString]);
3276 objc_super super = {self, _class};
3277 void *arg0 = &super;
3283 sig::Signature signature;
3284 sig::Parse(pool, &signature, type, &Structor_);
3287 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3289 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSendSuper_stret) : reinterpret_cast<void (*)()>(&objc_msgSendSuper);
3290 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3294 static size_t Nonce_(0);
3296 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3298 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
3299 return CYCastJSValue(context, name);
3303 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3314 _throw(NSInvalidArgumentException, "too few arguments to objc_msgSend");
3316 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
3317 Super *internal(reinterpret_cast<Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3318 self = internal->GetValue();
3319 _class = internal->class_;;
3320 uninitialized = false;
3321 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
3322 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3323 self = internal->GetValue();
3325 uninitialized = internal->IsUninitialized();
3327 internal->value_ = nil;
3329 self = CYCastNSObject(pool, context, arguments[0]);
3331 uninitialized = false;
3335 return CYJSNull(context);
3337 _cmd = CYCastSEL(context, arguments[1]);
3340 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
3345 /* Hook: objc_registerClassPair {{{ */
3346 // XXX: replace this with associated objects
3348 MSHook(void, CYDealloc, id self, SEL sel) {
3349 CYInternal *internal;
3350 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
3351 if (internal != NULL)
3353 _CYDealloc(self, sel);
3356 MSHook(void, objc_registerClassPair, Class _class) {
3357 Class super(class_getSuperclass(_class));
3358 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
3359 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
3360 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
3363 _objc_registerClassPair(_class);
3366 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3369 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3371 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3372 if (value == NULL || !CYIsClass(value))
3373 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3374 Class _class((Class) value);
3375 $objc_registerClassPair(_class);
3376 return CYJSUndefined(context);
3382 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3383 JSGarbageCollect(context);
3384 return CYJSUndefined(context);
3388 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3389 JSValueRef setup[count + 2];
3392 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
3393 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
3396 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3398 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
3400 // XXX: handle Instance::Uninitialized?
3401 id self(CYCastNSObject(pool, context, _this));
3405 setup[1] = &internal->sel_;
3407 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3411 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3413 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
3414 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3418 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3421 _throw(NSInvalidArgumentException, "incorrect number of arguments to Super constructor");
3423 NSObject *self(CYCastNSObject(pool, context, arguments[0]));
3424 Class _class(CYCastClass(pool, context, arguments[1]));
3425 return Super::Make(context, self, _class);
3429 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3432 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector constructor");
3433 const char *name(CYCastCString(context, arguments[0]));
3434 return CYMakeSelector(context, sel_registerName(name));
3439 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3442 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3444 void *value(CYCastPointer<void *>(context, arguments[0]));
3445 const char *type(CYCastCString(context, arguments[1]));
3449 sig::Signature signature;
3450 sig::Parse(pool, &signature, type, &Structor_);
3452 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
3456 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3459 _throw(NSInvalidArgumentException, "incorrect number of arguments to Type constructor");
3460 const char *type(CYCastCString(context, arguments[0]));
3461 return CYMakeType(context, type);
3465 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3466 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3471 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3472 type.primitive = sig::pointer_P;
3473 type.data.data.size = 0;
3476 size_t index(CYGetIndex(pool, property));
3477 if (index == _not(size_t))
3479 type.primitive = sig::array_P;
3480 type.data.data.size = index;
3486 type.data.data.type = internal->type_;
3488 return CYMakeType(context, &type);
3492 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3493 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3497 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3498 sig::Type *type(internal->type_);
3499 ffi_type *ffi(internal->GetFFI());
3501 uint8_t value[ffi->size];
3503 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3504 return CYFromFFI(context, type, ffi, value);
3508 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3511 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3512 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3514 sig::Type *type(internal->type_);
3517 if (type->primitive != sig::array_P)
3520 size = type->data.data.size;
3521 type = type->data.data.type;
3524 void *value(malloc(internal->GetFFI()->size));
3525 return CYMakePointer(context, value, type, NULL, NULL);
3530 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3533 _throw(NSInvalidArgumentException, "incorrect number of arguments to Instance constructor");
3534 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3535 return Instance::Make(context, self);
3540 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3543 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3544 const char *type(CYCastCString(context, arguments[1]));
3545 return CYMakeFunctor(context, arguments[0], type);
3550 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3551 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3552 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3555 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3556 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3557 Type_privateData *typical(internal->GetType());
3562 if (typical == NULL) {
3566 type = typical->type_;
3567 ffi = typical->ffi_;
3570 return CYMakePointer(context, &internal->value_, type, ffi, object);
3574 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3575 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3578 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3582 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3583 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3586 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3587 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3589 sprintf(string, "%p", internal->value_);
3592 return CYCastJSValue(context, string);
3597 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3598 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3599 return Instance::Make(context, object_getClass(internal->GetValue()));
3602 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3603 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3604 id self(internal->GetValue());
3605 if (!CYIsClass(self))
3606 return CYJSUndefined(context);
3608 return CYGetClassPrototype(context, self);
3612 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3613 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3614 id self(internal->GetValue());
3615 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3616 return CYJSUndefined(context);
3617 return Messages::Make(context, self);
3620 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3621 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3624 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3628 return CYCastJSValue(context, CYJSString(CYCastNSCYON(internal->GetValue())));
3633 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3634 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3637 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3641 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3642 // XXX: check for support of cy$toJSON?
3643 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3648 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3649 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3652 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3656 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3661 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3662 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3665 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3669 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3670 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3673 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3674 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3675 const char *name(sel_getName(internal->GetValue()));
3679 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3684 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3687 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector.type");
3689 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3690 if (Class _class = CYCastClass(pool, context, arguments[0])) {
3691 SEL sel(internal->GetValue());
3692 if (objc_method *method = class_getInstanceMethod(_class, sel))
3693 if (const char *type = CYPoolTypeEncoding(pool, _class, sel, method))
3694 return CYCastJSValue(context, CYJSString(type));
3697 // XXX: do a lookup of some kind
3698 return CYJSNull(context);
3703 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3705 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3707 const char *type(sig::Unparse(pool, internal->type_));
3708 return CYCastJSValue(context, CYJSString(type));
3712 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3714 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3716 const char *type(sig::Unparse(pool, internal->type_));
3717 size_t size(strlen(type));
3718 char *cyon(new(pool) char[12 + size + 1]);
3719 memcpy(cyon, "new Type(\"", 10);
3720 cyon[12 + size] = '\0';
3721 cyon[12 + size - 2] = '"';
3722 cyon[12 + size - 1] = ')';
3723 memcpy(cyon + 10, type, size);
3724 return CYCastJSValue(context, CYJSString(cyon));
3728 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3729 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3733 static JSStaticValue Selector_staticValues[2] = {
3734 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3735 {NULL, NULL, NULL, 0}
3739 static JSStaticValue Pointer_staticValues[2] = {
3740 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3741 {NULL, NULL, NULL, 0}
3744 static JSStaticFunction Pointer_staticFunctions[4] = {
3745 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3746 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3747 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3751 static JSStaticFunction Struct_staticFunctions[2] = {
3752 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3756 static JSStaticFunction Functor_staticFunctions[4] = {
3757 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3758 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3759 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3764 static JSStaticValue Instance_staticValues[5] = {
3765 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3766 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3767 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3768 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3769 {NULL, NULL, NULL, 0}
3772 static JSStaticFunction Instance_staticFunctions[5] = {
3773 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3774 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3775 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3776 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3780 static JSStaticFunction Internal_staticFunctions[2] = {
3781 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3785 static JSStaticFunction Selector_staticFunctions[5] = {
3786 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3787 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3788 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3789 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3794 static JSStaticFunction Type_staticFunctions[4] = {
3795 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3796 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3797 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3801 void CYSetArgs(int argc, const char *argv[]) {
3802 JSContextRef context(CYGetJSContext());
3803 JSValueRef args[argc];
3804 for (int i(0); i != argc; ++i)
3805 args[i] = CYCastJSValue(context, argv[i]);
3806 JSValueRef exception(NULL);
3807 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3808 CYThrow(context, exception);
3809 CYSetProperty(context, System_, CYJSString("args"), array);
3812 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3813 return JSContextGetGlobalObject(context);
3816 const char *CYExecute(apr_pool_t *pool, const char *code) {
3817 JSContextRef context(CYGetJSContext());
3818 JSValueRef exception(NULL), result;
3824 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3825 } catch (const char *error) {
3829 if (exception != NULL) { error:
3834 if (JSValueIsUndefined(context, result))
3838 json = CYPoolCCYON(pool, context, result, &exception);
3839 } catch (const char *error) {
3843 if (exception != NULL)
3847 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3851 static apr_pool_t *Pool_;
3853 apr_pool_t *CYGetGlobalPool() {
3858 _aprcall(apr_initialize());
3859 _aprcall(apr_pool_create(&Pool_, NULL));
3861 _sqlcall(sqlite3_open("/usr/lib/libcycript.db", &Bridge_));
3864 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3865 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3868 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3869 NSCFType_ = objc_getClass("NSCFType");
3872 NSArray_ = objc_getClass("NSArray");
3873 NSDictionary_ = objc_getClass("NSDictonary");
3874 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3875 NSZombie_ = objc_getClass("_NSZombie_");
3876 Object_ = objc_getClass("Object");
3880 JSGlobalContextRef CYGetJSContext() {
3881 if (Context_ == NULL) {
3882 JSClassDefinition definition;
3884 definition = kJSClassDefinitionEmpty;
3885 definition.className = "Functor";
3886 definition.staticFunctions = Functor_staticFunctions;
3887 definition.callAsFunction = &Functor_callAsFunction;
3888 definition.finalize = &Finalize;
3889 Functor_ = JSClassCreate(&definition);
3891 definition = kJSClassDefinitionEmpty;
3892 definition.className = "Pointer";
3893 definition.staticValues = Pointer_staticValues;
3894 definition.staticFunctions = Pointer_staticFunctions;
3895 definition.getProperty = &Pointer_getProperty;
3896 definition.setProperty = &Pointer_setProperty;
3897 definition.finalize = &Finalize;
3898 Pointer_ = JSClassCreate(&definition);
3900 definition = kJSClassDefinitionEmpty;
3901 definition.className = "Struct";
3902 definition.staticFunctions = Struct_staticFunctions;
3903 definition.getProperty = &Struct_getProperty;
3904 definition.setProperty = &Struct_setProperty;
3905 definition.getPropertyNames = &Struct_getPropertyNames;
3906 definition.finalize = &Finalize;
3907 Struct_ = JSClassCreate(&definition);
3909 definition = kJSClassDefinitionEmpty;
3910 definition.className = "Type";
3911 definition.staticFunctions = Type_staticFunctions;
3912 definition.getProperty = &Type_getProperty;
3913 definition.callAsFunction = &Type_callAsFunction;
3914 definition.callAsConstructor = &Type_callAsConstructor;
3915 definition.finalize = &Finalize;
3916 Type_privateData::Class_ = JSClassCreate(&definition);
3918 definition = kJSClassDefinitionEmpty;
3919 definition.className = "Runtime";
3920 definition.getProperty = &Runtime_getProperty;
3921 Runtime_ = JSClassCreate(&definition);
3923 definition = kJSClassDefinitionEmpty;
3924 //definition.getProperty = &Global_getProperty;
3925 JSClassRef Global(JSClassCreate(&definition));
3927 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3929 JSObjectRef global(CYGetGlobalObject(context));
3931 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3933 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3934 JSValueProtect(context, Array_);
3936 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3937 JSValueProtect(context, Function_);
3939 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3940 JSValueProtect(context, String_);
3942 length_ = JSStringCreateWithUTF8CString("length");
3943 message_ = JSStringCreateWithUTF8CString("message");
3944 name_ = JSStringCreateWithUTF8CString("name");
3945 prototype_ = JSStringCreateWithUTF8CString("prototype");
3946 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3947 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3949 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3950 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3951 JSValueProtect(context, Object_prototype_);
3953 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3954 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3955 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3956 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3958 JSValueProtect(context, Array_prototype_);
3959 JSValueProtect(context, Array_pop_);
3960 JSValueProtect(context, Array_push_);
3961 JSValueProtect(context, Array_splice_);
3963 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3965 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3967 /* Objective-C Classes {{{ */
3969 definition = kJSClassDefinitionEmpty;
3970 definition.className = "Instance";
3971 definition.staticValues = Instance_staticValues;
3972 definition.staticFunctions = Instance_staticFunctions;
3973 definition.hasProperty = &Instance_hasProperty;
3974 definition.getProperty = &Instance_getProperty;
3975 definition.setProperty = &Instance_setProperty;
3976 definition.deleteProperty = &Instance_deleteProperty;
3977 definition.getPropertyNames = &Instance_getPropertyNames;
3978 definition.callAsConstructor = &Instance_callAsConstructor;
3979 definition.hasInstance = &Instance_hasInstance;
3980 definition.finalize = &Finalize;
3981 Instance_ = JSClassCreate(&definition);
3983 definition = kJSClassDefinitionEmpty;
3984 definition.className = "Internal";
3985 definition.staticFunctions = Internal_staticFunctions;
3986 definition.hasProperty = &Internal_hasProperty;
3987 definition.getProperty = &Internal_getProperty;
3988 definition.setProperty = &Internal_setProperty;
3989 definition.getPropertyNames = &Internal_getPropertyNames;
3990 definition.finalize = &Finalize;
3991 Internal_ = JSClassCreate(&definition);
3993 definition = kJSClassDefinitionEmpty;
3994 definition.className = "Message";
3995 definition.staticFunctions = Functor_staticFunctions;
3996 definition.callAsFunction = &Message_callAsFunction;
3997 definition.finalize = &Finalize;
3998 Message_ = JSClassCreate(&definition);
4000 definition = kJSClassDefinitionEmpty;
4001 definition.className = "Messages";
4002 definition.hasProperty = &Messages_hasProperty;
4003 definition.getProperty = &Messages_getProperty;
4004 definition.setProperty = &Messages_setProperty;
4006 definition.deleteProperty = &Messages_deleteProperty;
4008 definition.getPropertyNames = &Messages_getPropertyNames;
4009 definition.finalize = &Finalize;
4010 Messages_ = JSClassCreate(&definition);
4012 definition = kJSClassDefinitionEmpty;
4013 definition.className = "Selector";
4014 definition.staticValues = Selector_staticValues;
4015 definition.staticFunctions = Selector_staticFunctions;
4016 definition.callAsFunction = &Selector_callAsFunction;
4017 definition.finalize = &Finalize;
4018 Selector_ = JSClassCreate(&definition);
4020 definition = kJSClassDefinitionEmpty;
4021 definition.className = "Super";
4022 definition.staticFunctions = Internal_staticFunctions;
4023 definition.finalize = &Finalize;
4024 Super_ = JSClassCreate(&definition);
4026 definition = kJSClassDefinitionEmpty;
4027 definition.className = "ObjectiveC::Classes";
4028 definition.getProperty = &ObjectiveC_Classes_getProperty;
4029 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
4030 ObjectiveC_Classes_ = JSClassCreate(&definition);
4032 definition = kJSClassDefinitionEmpty;
4033 definition.className = "ObjectiveC::Images";
4034 definition.getProperty = &ObjectiveC_Images_getProperty;
4035 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
4036 ObjectiveC_Images_ = JSClassCreate(&definition);
4038 definition = kJSClassDefinitionEmpty;
4039 definition.className = "ObjectiveC::Image::Classes";
4040 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
4041 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
4042 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
4044 definition = kJSClassDefinitionEmpty;
4045 definition.className = "ObjectiveC::Protocols";
4046 definition.getProperty = &ObjectiveC_Protocols_getProperty;
4047 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
4048 ObjectiveC_Protocols_ = JSClassCreate(&definition);
4050 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
4051 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC);
4053 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
4054 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
4055 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
4057 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
4058 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
4059 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
4060 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
4062 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
4063 JSValueProtect(context, Instance_prototype_);
4065 CYSetProperty(context, global, CYJSString("Instance"), Instance);
4066 CYSetProperty(context, global, CYJSString("Selector"), Selector);
4067 CYSetProperty(context, global, CYJSString("Super"), Super);
4069 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
4070 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
4072 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
4073 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
4077 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
4079 CYSetProperty(context, global, CYJSString("Functor"), Functor);
4080 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
4081 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
4084 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
4089 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
4093 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
4094 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
4095 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
4097 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
4099 System_ = JSObjectMake(context, NULL, NULL);
4100 JSValueProtect(context, System_);
4102 CYSetProperty(context, global, CYJSString("system"), System_);
4103 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
4104 //CYSetProperty(context, System_, CYJSString("global"), global);
4106 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
4108 Result_ = JSStringCreateWithUTF8CString("_");