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>
43 #include "Internal.hpp"
48 #include "cycript.hpp"
50 #include "sig/parse.hpp"
51 #include "sig/ffi_type.hpp"
53 #include "Pooling.hpp"
56 #include <CoreFoundation/CoreFoundation.h>
57 #include <CoreFoundation/CFLogUtilities.h>
58 #include <JavaScriptCore/JSStringRefCF.h>
64 #include <ext/stdio_filebuf.h>
72 #include "Cycript.tab.hh"
77 void CYThrow(const char *format, ...);
79 #define _assert(test, args...) do { \
81 throw CYError(context, "*** _assert(%s):%s(%u):%s [errno=%d]", #test, __FILE__, __LINE__, __FUNCTION__, errno); \
84 #define _trace() do { \
85 fprintf(stderr, "_trace():%u\n", __LINE__); \
90 catch (NSException *error) { \
91 CYThrow(context, error, exception); \
101 catch (const CYError &error) { \
102 *exception = error.value_; \
105 *exception = CYCastJSValue(context, "catch(...)"); \
110 #define class_getSuperclass GSObjCSuper
111 #define object_getClass GSObjCClass
114 char *sqlite3_column_pooled(apr_pool_t *pool, sqlite3_stmt *stmt, int n) {
115 if (const unsigned char *value = sqlite3_column_text(stmt, n))
116 return apr_pstrdup(pool, (const char *) value);
121 JSContextRef context_;
124 CYError(JSContextRef context, JSValueRef value) :
130 CYError(JSContextRef context, const char *format, ...);
133 void CYThrow(JSContextRef context, JSValueRef value);
135 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
137 struct CYUTF8String {
141 CYUTF8String(const char *data, size_t size) :
147 bool operator ==(const char *value) const {
148 size_t length(strlen(data));
149 return length == size && memcmp(value, data, length) == 0;
153 struct CYUTF16String {
154 const uint16_t *data;
157 CYUTF16String(const uint16_t *data, size_t size) :
165 void *(*ExecuteStart)();
166 void (*ExecuteEnd)(void *);
167 JSValueRef (*RuntimeProperty)(JSContextRef, CYUTF8String);
168 bool (*PoolFFI)(apr_pool_t *, JSContextRef, sig::Type *, ffi_type *, void *, JSValueRef);
169 JSValueRef (*FromFFI)(JSContextRef, sig::Type *, ffi_type *, void *, bool, JSObjectRef);
172 /* JavaScript Properties {{{ */
173 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
174 JSValueRef exception(NULL);
175 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
176 CYThrow(context, exception);
180 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
181 JSValueRef exception(NULL);
182 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
183 CYThrow(context, exception);
187 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
188 JSValueRef exception(NULL);
189 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
190 CYThrow(context, exception);
193 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes = kJSPropertyAttributeNone) {
194 JSValueRef exception(NULL);
195 JSObjectSetProperty(context, object, name, value, attributes, &exception);
196 CYThrow(context, exception);
199 /* JavaScript Strings {{{ */
200 JSStringRef CYCopyJSString(const char *value) {
201 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
204 JSStringRef CYCopyJSString(JSStringRef value) {
205 return value == NULL ? NULL : JSStringRetain(value);
208 JSStringRef CYCopyJSString(CYUTF8String value) {
209 // XXX: this is very wrong
210 return CYCopyJSString(value.data);
213 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
214 if (JSValueIsNull(context, value))
216 JSValueRef exception(NULL);
217 JSStringRef string(JSValueToStringCopy(context, value, &exception));
218 CYThrow(context, exception);
228 JSStringRelease(string_);
232 CYJSString(const CYJSString &rhs) :
233 string_(CYCopyJSString(rhs.string_))
237 template <typename Arg0_>
238 CYJSString(Arg0_ arg0) :
239 string_(CYCopyJSString(arg0))
243 template <typename Arg0_, typename Arg1_>
244 CYJSString(Arg0_ arg0, Arg1_ arg1) :
245 string_(CYCopyJSString(arg0, arg1))
249 CYJSString &operator =(const CYJSString &rhs) {
251 string_ = CYCopyJSString(rhs.string_);
264 operator JSStringRef() const {
269 static CYUTF16String CYCastUTF16String(JSStringRef value) {
270 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
273 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
274 _assert(pool != NULL);
276 CYUTF16String utf16(CYCastUTF16String(value));
277 const char *in(reinterpret_cast<const char *>(utf16.data));
279 iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL")));
281 size_t size(JSStringGetMaximumUTF8CStringSize(value));
282 char *out(new(pool) char[size]);
283 CYUTF8String utf8(out, size);
285 size = utf16.size * 2;
286 _syscall(iconv(conversion, const_cast<char **>(&in), &size, &out, &utf8.size));
289 utf8.size = out - utf8.data;
291 _syscall(iconv_close(conversion));
296 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
297 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
298 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
302 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
303 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, context, CYJSString(context, value));
307 // XXX: this macro is unhygenic
308 #define CYCastCString_(string) ({ \
310 if (string == NULL) \
313 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
314 utf8 = reinterpret_cast<char *>(alloca(size)); \
315 JSStringGetUTF8CString(string, utf8, size); \
320 // XXX: this macro is unhygenic
321 #define CYCastCString(context, value) ({ \
325 else if (JSStringRef string = CYCopyJSString(context, value)) { \
326 utf8 = CYCastCString_(string); \
327 JSStringRelease(string); \
335 /* Index Offsets {{{ */
336 size_t CYGetIndex(const CYUTF8String &value) {
337 if (value.data[0] != '0') {
339 size_t index(strtoul(value.data, &end, 10));
340 if (value.data + value.size == end)
342 } else if (value.data[1] == '\0')
347 size_t CYGetIndex(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
348 return CYGetIndex(CYPoolUTF8String(pool, context, value));
351 bool CYGetOffset(const char *value, ssize_t &index) {
352 if (value[0] != '0') {
354 index = strtol(value, &end, 10);
355 if (value + strlen(value) == end)
357 } else if (value[1] == '\0') {
366 /* JavaScript *ify {{{ */
367 void CYStringify(std::ostringstream &str, const char *data, size_t size) {
368 unsigned quot(0), apos(0);
369 for (const char *value(data), *end(data + size); value != end; ++value)
372 else if (*value == '\'')
375 bool single(quot > apos);
377 str << (single ? '\'' : '"');
379 for (const char *value(data), *end(data + size); value != end; ++value)
381 case '\\': str << "\\\\"; break;
382 case '\b': str << "\\b"; break;
383 case '\f': str << "\\f"; break;
384 case '\n': str << "\\n"; break;
385 case '\r': str << "\\r"; break;
386 case '\t': str << "\\t"; break;
387 case '\v': str << "\\v"; break;
402 if (*value < 0x20 || *value >= 0x7f)
403 str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(*value);
408 str << (single ? '\'' : '"');
411 void CYNumerify(std::ostringstream &str, double value) {
413 // XXX: I want this to print 1e3 rather than 1000
414 sprintf(string, "%.17g", value);
418 bool CYIsKey(CYUTF8String value) {
419 const char *data(value.data);
420 size_t size(value.size);
425 if (DigitRange_[data[0]]) {
426 size_t index(CYGetIndex(value));
427 if (index == _not(size_t))
430 if (!WordStartRange_[data[0]])
432 for (size_t i(1); i != size; ++i)
433 if (!WordEndRange_[data[i]])
441 static JSGlobalContextRef Context_;
442 static JSObjectRef System_;
444 static JSClassRef Functor_;
445 static JSClassRef Pointer_;
446 static JSClassRef Runtime_;
447 static JSClassRef Struct_;
449 static JSObjectRef Array_;
450 static JSObjectRef Error_;
451 static JSObjectRef Function_;
452 static JSObjectRef String_;
454 static JSStringRef Result_;
456 static JSStringRef length_;
457 static JSStringRef message_;
458 static JSStringRef name_;
459 static JSStringRef prototype_;
460 static JSStringRef toCYON_;
461 static JSStringRef toJSON_;
463 static JSObjectRef Object_prototype_;
464 static JSObjectRef Function_prototype_;
466 static JSObjectRef Array_prototype_;
467 static JSObjectRef Array_pop_;
468 static JSObjectRef Array_push_;
469 static JSObjectRef Array_splice_;
473 void Finalize(JSObjectRef object) {
474 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
477 struct CStringMapLess :
478 std::binary_function<const char *, const char *, bool>
480 _finline bool operator ()(const char *lhs, const char *rhs) const {
481 return strcmp(lhs, rhs) < 0;
485 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
489 JSContextRef context(NULL);
491 sqlite3_stmt *statement;
493 _sqlcall(sqlite3_prepare(Bridge_,
495 "\"bridge\".\"mode\", "
496 "\"bridge\".\"value\" "
499 " \"bridge\".\"mode\" in (3, 4) and"
500 " \"bridge\".\"name\" = ?"
502 , -1, &statement, NULL));
504 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
509 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
513 mode = sqlite3_column_int(statement, 0);
514 value = sqlite3_column_pooled(pool, statement, 1);
517 _sqlcall(sqlite3_finalize(statement));
526 sig::Parse(pool, &type->data.signature, value, &Structor_);
530 sig::Signature signature;
531 sig::Parse(pool, &signature, value, &Structor_);
532 type = signature.elements[0].type;
537 JSClassRef Type_privateData::Class_;
542 Type_privateData *type_;
544 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
545 CYOwned(value, context, owner),
546 type_(new(pool_) Type_privateData(type))
551 struct Struct_privateData :
554 Type_privateData *type_;
556 Struct_privateData(JSContextRef context, JSObjectRef owner) :
557 CYOwned(NULL, context, owner)
562 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
563 static TypeMap Types_;
565 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
566 Struct_privateData *internal(new Struct_privateData(context, owner));
567 apr_pool_t *pool(internal->pool_);
568 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
569 internal->type_ = typical;
572 internal->value_ = data;
574 size_t size(typical->GetFFI()->size);
575 void *copy(apr_palloc(internal->pool_, size));
576 memcpy(copy, data, size);
577 internal->value_ = copy;
580 return JSObjectMake(context, Struct_, internal);
583 struct Functor_privateData :
586 sig::Signature signature_;
589 Functor_privateData(const char *type, void (*value)()) :
590 CYValue(reinterpret_cast<void *>(value))
592 sig::Parse(pool_, &signature_, type, &Structor_);
593 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
596 void (*GetValue())() const {
597 return reinterpret_cast<void (*)()>(value_);
601 struct Closure_privateData :
604 JSContextRef context_;
605 JSObjectRef function_;
607 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
608 Functor_privateData(type, NULL),
612 JSValueProtect(context_, function_);
615 virtual ~Closure_privateData() {
616 JSValueUnprotect(context_, function_);
620 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
621 return JSValueMakeBoolean(context, value);
624 JSValueRef CYCastJSValue(JSContextRef context, double value) {
625 return JSValueMakeNumber(context, value);
628 #define CYCastJSValue_(Type_) \
629 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
630 return JSValueMakeNumber(context, static_cast<double>(value)); \
634 CYCastJSValue_(unsigned int)
635 CYCastJSValue_(long int)
636 CYCastJSValue_(long unsigned int)
637 CYCastJSValue_(long long int)
638 CYCastJSValue_(long long unsigned int)
640 JSValueRef CYJSUndefined(JSContextRef context) {
641 return JSValueMakeUndefined(context);
644 double CYCastDouble(const char *value, size_t size) {
646 double number(strtod(value, &end));
647 if (end != value + size)
652 double CYCastDouble(const char *value) {
653 return CYCastDouble(value, strlen(value));
656 double CYCastDouble(JSContextRef context, JSValueRef value) {
657 JSValueRef exception(NULL);
658 double number(JSValueToNumber(context, value, &exception));
659 CYThrow(context, exception);
663 bool CYCastBool(JSContextRef context, JSValueRef value) {
664 return JSValueToBoolean(context, value);
667 JSValueRef CYJSNull(JSContextRef context) {
668 return JSValueMakeNull(context);
671 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
672 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
675 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
676 return CYCastJSValue(context, CYJSString(value));
679 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
680 JSValueRef exception(NULL);
681 JSObjectRef object(JSValueToObject(context, value, &exception));
682 CYThrow(context, exception);
686 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
687 JSValueRef exception(NULL);
688 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
689 CYThrow(context, exception);
693 bool CYIsCallable(JSContextRef context, JSValueRef value) {
694 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
697 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSObjectRef object);
699 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
703 printf("%s\n", CYCastCString(context, arguments[0]));
704 return CYJSUndefined(context);
707 static size_t Nonce_(0);
709 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
711 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
712 return CYCastJSValue(context, name);
715 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
716 JSGarbageCollect(context);
717 return CYJSUndefined(context);
720 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) { CYTry {
721 switch (JSType type = JSValueGetType(context, value)) {
722 case kJSTypeUndefined:
727 return CYCastBool(context, value) ? "true" : "false";
729 case kJSTypeNumber: {
730 std::ostringstream str;
731 CYNumerify(str, CYCastDouble(context, value));
732 std::string value(str.str());
733 return apr_pstrmemdup(pool, value.c_str(), value.size());
736 case kJSTypeString: {
737 std::ostringstream str;
738 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, value)));
739 CYStringify(str, string.data, string.size);
740 std::string value(str.str());
741 return apr_pstrmemdup(pool, value.c_str(), value.size());
745 return CYPoolCCYON(pool, context, (JSObjectRef) value);
747 throw CYError(context, "JSValueGetType() == 0x%x", type);
751 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
752 JSValueRef exception(NULL);
753 const char *cyon(CYPoolCCYON(pool, context, value, &exception));
754 CYThrow(context, exception);
758 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
759 JSValueRef toCYON(CYGetProperty(context, object, toCYON_));
760 if (CYIsCallable(context, toCYON)) {
761 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
762 return CYPoolCString(pool, context, value);
765 JSValueRef toJSON(CYGetProperty(context, object, toJSON_));
766 if (CYIsCallable(context, toJSON)) {
767 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
768 JSValueRef exception(NULL);
769 const char *cyon(CYPoolCCYON(pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments), &exception));
770 CYThrow(context, exception);
774 std::ostringstream str;
778 // XXX: this is, sadly, going to leak
779 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
783 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
784 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
785 JSValueRef value(CYGetProperty(context, object, name));
792 CYUTF8String string(CYPoolUTF8String(pool, context, name));
796 CYStringify(str, string.data, string.size);
798 str << ':' << CYPoolCCYON(pool, context, value);
803 JSPropertyNameArrayRelease(names);
805 std::string string(str.str());
806 return apr_pstrmemdup(pool, string.c_str(), string.size());
809 static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
811 std::ostringstream str;
815 JSValueRef length(CYGetProperty(context, _this, length_));
818 for (size_t index(0), count(CYCastDouble(context, length)); index != count; ++index) {
819 JSValueRef value(CYGetProperty(context, _this, index));
826 if (!JSValueIsUndefined(context, value))
827 str << CYPoolCCYON(pool, context, value);
836 std::string value(str.str());
837 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
840 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
841 Pointer *internal(new Pointer(pointer, context, owner, type));
842 return JSObjectMake(context, Pointer_, internal);
845 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
846 Functor_privateData *internal(new Functor_privateData(type, function));
847 return JSObjectMake(context, Functor_, internal);
850 static bool CYGetOffset(apr_pool_t *pool, JSContextRef context, JSStringRef value, ssize_t &index) {
851 return CYGetOffset(CYPoolCString(pool, context, value), index);
854 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
855 switch (JSValueGetType(context, value)) {
858 /*case kJSTypeString:
859 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
861 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
862 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
863 return internal->value_;
866 double number(CYCastDouble(context, value));
867 if (std::isnan(number))
868 throw CYError(context, "cannot convert value to pointer");
869 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
873 template <typename Type_>
874 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
875 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
878 #define CYObjectiveTry \
880 #define CYObjectiveCatch \
881 catch (const CYError &error) { \
882 @throw CYCastNSObject(NULL, error.context_, error.value_); \
885 #define CYPoolTry { \
887 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
889 #define CYPoolCatch(value) \
890 @catch (NSException *error) { \
891 _saved = [error retain]; \
892 throw CYError(context, CYCastJSValue(context, error)); \
897 [_saved autorelease]; \
901 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
902 switch (type->primitive) {
904 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
907 #define CYPoolFFI_(primitive, native) \
908 case sig::primitive ## _P: \
909 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
912 CYPoolFFI_(uchar, unsigned char)
913 CYPoolFFI_(char, char)
914 CYPoolFFI_(ushort, unsigned short)
915 CYPoolFFI_(short, short)
916 CYPoolFFI_(ulong, unsigned long)
917 CYPoolFFI_(long, long)
918 CYPoolFFI_(uint, unsigned int)
920 CYPoolFFI_(ulonglong, unsigned long long)
921 CYPoolFFI_(longlong, long long)
922 CYPoolFFI_(float, float)
923 CYPoolFFI_(double, double)
926 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
930 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
933 case sig::struct_P: {
934 uint8_t *base(reinterpret_cast<uint8_t *>(data));
935 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
936 for (size_t index(0); index != type->data.signature.count; ++index) {
937 sig::Element *element(&type->data.signature.elements[index]);
938 ffi_type *field(ffi->elements[index]);
941 if (aggregate == NULL)
944 rhs = CYGetProperty(context, aggregate, index);
945 if (JSValueIsUndefined(context, rhs)) {
946 if (element->name != NULL)
947 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
950 if (JSValueIsUndefined(context, rhs)) undefined:
951 throw CYError(context, "unable to extract structure value");
955 CYPoolFFI(pool, context, element->type, field, base, rhs);
965 if (hooks_ != NULL && hooks_->PoolFFI != NULL)
966 if ((*hooks_->PoolFFI)(pool, context, type, ffi, data, value))
969 fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
974 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
975 switch (type->primitive) {
977 return CYCastJSValue(context, *reinterpret_cast<bool *>(data));
979 #define CYFromFFI_(primitive, native) \
980 case sig::primitive ## _P: \
981 return CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
983 CYFromFFI_(uchar, unsigned char)
984 CYFromFFI_(char, char)
985 CYFromFFI_(ushort, unsigned short)
986 CYFromFFI_(short, short)
987 CYFromFFI_(ulong, unsigned long)
988 CYFromFFI_(long, long)
989 CYFromFFI_(uint, unsigned int)
991 CYFromFFI_(ulonglong, unsigned long long)
992 CYFromFFI_(longlong, long long)
993 CYFromFFI_(float, float)
994 CYFromFFI_(double, double)
997 if (void *pointer = *reinterpret_cast<void **>(data))
998 return CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1002 if (char *utf8 = *reinterpret_cast<char **>(data))
1003 return CYCastJSValue(context, utf8);
1007 return CYMakeStruct(context, data, type, ffi, owner);
1009 return CYJSUndefined(context);
1012 return CYJSNull(context);
1014 if (hooks_ != NULL && hooks_->FromFFI != NULL)
1015 if (JSValueRef value = (*hooks_->FromFFI)(context, type, ffi, data, initialize, owner))
1018 fprintf(stderr, "CYFromFFI(%c)\n", type->primitive);
1023 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1024 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1026 JSContextRef context(internal->context_);
1028 size_t count(internal->cif_.nargs);
1029 JSValueRef values[count];
1031 for (size_t index(0); index != count; ++index)
1032 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1034 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
1035 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1038 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
1039 // XXX: in case of exceptions this will leak
1040 // XXX: in point of fact, this may /need/ to leak :(
1041 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
1043 ffi_closure *closure((ffi_closure *) _syscall(mmap(
1044 NULL, sizeof(ffi_closure),
1045 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1049 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
1050 _assert(status == FFI_OK);
1052 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1054 internal->value_ = closure;
1059 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1060 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
1061 return JSObjectMake(context, Functor_, internal);
1064 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
1065 JSValueRef exception(NULL);
1066 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
1067 CYThrow(context, exception);
1070 JSObjectRef function(CYCastJSObject(context, value));
1071 return CYMakeFunctor(context, function, type);
1073 void (*function)()(CYCastPointer<void (*)()>(context, value));
1074 return CYMakeFunctor(context, function, type);
1078 static bool Index_(apr_pool_t *pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1079 Type_privateData *typical(internal->type_);
1080 sig::Type *type(typical->type_);
1084 const char *name(CYPoolCString(pool, context, property));
1085 size_t length(strlen(name));
1086 double number(CYCastDouble(name, length));
1088 size_t count(type->data.signature.count);
1090 if (std::isnan(number)) {
1091 if (property == NULL)
1094 sig::Element *elements(type->data.signature.elements);
1096 for (size_t local(0); local != count; ++local) {
1097 sig::Element *element(&elements[local]);
1098 if (element->name != NULL && strcmp(name, element->name) == 0) {
1106 index = static_cast<ssize_t>(number);
1107 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1112 ffi_type **elements(typical->GetFFI()->elements);
1114 base = reinterpret_cast<uint8_t *>(internal->value_);
1115 for (ssize_t local(0); local != index; ++local)
1116 base += elements[local]->size;
1121 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) { CYTry {
1122 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1123 Type_privateData *typical(internal->type_);
1125 ffi_type *ffi(typical->GetFFI());
1127 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1128 base += ffi->size * index;
1130 JSObjectRef owner(internal->GetOwner() ?: object);
1131 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
1134 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1136 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1137 Type_privateData *typical(internal->type_);
1139 if (typical->type_ == NULL)
1143 if (!CYGetOffset(pool, context, property, offset))
1146 return Pointer_getIndex(context, object, offset, exception);
1149 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1150 return Pointer_getIndex(context, object, 0, exception);
1153 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) { CYTry {
1154 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1155 Type_privateData *typical(internal->type_);
1157 ffi_type *ffi(typical->GetFFI());
1159 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1160 base += ffi->size * index;
1162 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
1166 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1168 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1169 Type_privateData *typical(internal->type_);
1171 if (typical->type_ == NULL)
1175 if (!CYGetOffset(pool, context, property, offset))
1178 return Pointer_setIndex(context, object, offset, value, exception);
1181 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1182 return Pointer_setIndex(context, object, 0, value, exception);
1185 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1186 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
1187 Type_privateData *typical(internal->type_);
1188 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
1191 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1193 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1194 Type_privateData *typical(internal->type_);
1199 if (!Index_(pool, context, internal, property, index, base))
1202 JSObjectRef owner(internal->GetOwner() ?: object);
1204 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
1207 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1209 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1210 Type_privateData *typical(internal->type_);
1215 if (!Index_(pool, context, internal, property, index, base))
1218 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
1222 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1223 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1224 Type_privateData *typical(internal->type_);
1225 sig::Type *type(typical->type_);
1230 size_t count(type->data.signature.count);
1231 sig::Element *elements(type->data.signature.elements);
1235 for (size_t index(0); index != count; ++index) {
1237 name = elements[index].name;
1240 sprintf(number, "%lu", index);
1244 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1248 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)()) { CYTry {
1249 if (setups + count != signature->count - 1)
1250 throw CYError(context, "incorrect number of arguments to ffi function");
1252 size_t size(setups + count);
1254 memcpy(values, setup, sizeof(void *) * setups);
1256 for (size_t index(setups); index != size; ++index) {
1257 sig::Element *element(&signature->elements[index + 1]);
1258 ffi_type *ffi(cif->arg_types[index]);
1260 values[index] = new(pool) uint8_t[ffi->size];
1261 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1264 uint8_t value[cif->rtype->size];
1265 ffi_call(cif, function, value, values);
1267 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
1270 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1272 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1273 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
1276 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
1277 Type_privateData *internal(new Type_privateData(NULL, type));
1278 return JSObjectMake(context, Type_privateData::Class_, internal);
1281 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
1282 Type_privateData *internal(new Type_privateData(type));
1283 return JSObjectMake(context, Type_privateData::Class_, internal);
1286 static void *CYCastSymbol(const char *name) {
1287 return dlsym(RTLD_DEFAULT, name);
1290 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1292 CYUTF8String name(CYPoolUTF8String(pool, context, property));
1294 if (hooks_ != NULL && hooks_->RuntimeProperty != NULL)
1295 if (JSValueRef value = (*hooks_->RuntimeProperty)(context, name))
1298 sqlite3_stmt *statement;
1300 _sqlcall(sqlite3_prepare(Bridge_,
1302 "\"bridge\".\"mode\", "
1303 "\"bridge\".\"value\" "
1306 " \"bridge\".\"name\" = ?"
1308 , -1, &statement, NULL));
1310 _sqlcall(sqlite3_bind_text(statement, 1, name.data, name.size, SQLITE_STATIC));
1315 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
1319 mode = sqlite3_column_int(statement, 0);
1320 value = sqlite3_column_pooled(pool, statement, 1);
1323 _sqlcall(sqlite3_finalize(statement));
1332 return JSEvaluateScript(CYGetJSContext(), CYJSString(value), NULL, NULL, 0, NULL);
1334 return CYMakeFunctor(context, reinterpret_cast<void (*)()>(CYCastSymbol(name.data)), value);
1337 // XXX: this is horrendously inefficient
1338 sig::Signature signature;
1339 sig::Parse(pool, &signature, value, &Structor_);
1341 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1342 return CYFromFFI(context, signature.elements[0].type, cif.rtype, CYCastSymbol(name.data));
1345 // XXX: implement case 3
1347 return CYMakeType(context, value);
1351 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1353 throw CYError(context, "incorrect number of arguments to Functor constructor");
1355 void *value(CYCastPointer<void *>(context, arguments[0]));
1356 const char *type(CYCastCString(context, arguments[1]));
1360 sig::Signature signature;
1361 sig::Parse(pool, &signature, type, &Structor_);
1363 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
1366 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1368 throw CYError(context, "incorrect number of arguments to Type constructor");
1369 const char *type(CYCastCString(context, arguments[0]));
1370 return CYMakeType(context, type);
1373 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1374 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1378 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
1379 type.primitive = sig::pointer_P;
1380 type.data.data.size = 0;
1383 size_t index(CYGetIndex(pool, context, property));
1384 if (index == _not(size_t))
1386 type.primitive = sig::array_P;
1387 type.data.data.size = index;
1393 type.data.data.type = internal->type_;
1395 return CYMakeType(context, &type);
1398 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1399 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1402 throw CYError(context, "incorrect number of arguments to type cast function");
1403 sig::Type *type(internal->type_);
1404 ffi_type *ffi(internal->GetFFI());
1406 uint8_t value[ffi->size];
1408 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
1409 return CYFromFFI(context, type, ffi, value);
1412 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1414 throw CYError(context, "incorrect number of arguments to type cast function");
1415 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1417 sig::Type *type(internal->type_);
1420 if (type->primitive != sig::array_P)
1423 size = type->data.data.size;
1424 type = type->data.data.type;
1427 void *value(malloc(internal->GetFFI()->size));
1428 return CYMakePointer(context, value, type, NULL, NULL);
1431 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1433 throw CYError(context, "incorrect number of arguments to Functor constructor");
1434 const char *type(CYCastCString(context, arguments[1]));
1435 return CYMakeFunctor(context, arguments[0], type);
1438 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1439 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1440 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
1443 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1444 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1447 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1448 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1450 sprintf(string, "%p", internal->value_);
1452 return CYCastJSValue(context, string);
1455 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1456 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1458 const char *type(sig::Unparse(pool, internal->type_));
1459 return CYCastJSValue(context, CYJSString(type));
1462 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1463 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1465 const char *type(sig::Unparse(pool, internal->type_));
1466 size_t size(strlen(type));
1467 char *cyon(new(pool) char[12 + size + 1]);
1468 memcpy(cyon, "new Type(\"", 10);
1469 cyon[12 + size] = '\0';
1470 cyon[12 + size - 2] = '"';
1471 cyon[12 + size - 1] = ')';
1472 memcpy(cyon + 10, type, size);
1473 return CYCastJSValue(context, CYJSString(cyon));
1476 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1477 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
1480 static JSStaticValue Pointer_staticValues[2] = {
1481 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1482 {NULL, NULL, NULL, 0}
1485 static JSStaticFunction Pointer_staticFunctions[4] = {
1486 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1487 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1488 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1492 static JSStaticFunction Struct_staticFunctions[2] = {
1493 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1497 static JSStaticFunction Functor_staticFunctions[4] = {
1498 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1499 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1500 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1504 static JSStaticFunction Type_staticFunctions[4] = {
1505 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1506 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1507 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1511 void CYSetArgs(int argc, const char *argv[]) {
1512 JSContextRef context(CYGetJSContext());
1513 JSValueRef args[argc];
1514 for (int i(0); i != argc; ++i)
1515 args[i] = CYCastJSValue(context, argv[i]);
1516 JSValueRef exception(NULL);
1517 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1518 CYThrow(context, exception);
1519 CYSetProperty(context, System_, CYJSString("args"), array);
1522 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1523 return JSContextGetGlobalObject(context);
1526 const char *CYExecute(apr_pool_t *pool, const char *code) {
1527 JSContextRef context(CYGetJSContext());
1528 JSValueRef exception(NULL), result;
1531 if (hooks_ != NULL && hooks_->ExecuteStart != NULL)
1532 handle = (*hooks_->ExecuteStart)();
1539 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
1540 } catch (const char *error) {
1544 if (exception != NULL) { error:
1549 if (JSValueIsUndefined(context, result))
1553 json = CYPoolCCYON(pool, context, result, &exception);
1554 } catch (const char *error) {
1558 if (exception != NULL)
1561 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
1563 if (hooks_ != NULL && hooks_->ExecuteEnd != NULL)
1564 (*hooks_->ExecuteEnd)(handle);
1568 static apr_pool_t *Pool_;
1570 apr_pool_t *CYGetGlobalPool() {
1575 JSContextRef context(NULL);
1576 _aprcall(apr_initialize());
1577 _aprcall(apr_pool_create(&Pool_, NULL));
1578 _sqlcall(sqlite3_open("/usr/lib/libcycript.db", &Bridge_));
1581 void CYThrow(JSContextRef context, JSValueRef value) {
1584 throw CYError(context, value);
1587 CYError::CYError(JSContextRef context, const char *format, ...) {
1588 if (context == NULL)
1589 context = CYGetJSContext();
1594 va_start (args, format);
1595 const char *message(apr_pvsprintf(pool, format, args));
1598 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(message))};
1600 JSValueRef exception(NULL);
1601 value_ = JSObjectCallAsConstructor(context, Error_, 1, arguments, &exception);
1602 CYThrow(context, exception);
1605 void CYObjectiveC(JSContextRef context, JSObjectRef global);
1608 /* Objective-C {{{ */
1609 #include <Foundation/Foundation.h>
1610 #include "ObjectiveC/Internal.hpp"
1611 #include "Struct.hpp"
1614 #include <WebKit/WebScriptObject.h>
1617 /* Objective-C Pool Release {{{ */
1618 apr_status_t CYPoolRelease_(void *data) {
1619 id object(reinterpret_cast<id>(data));
1624 id CYPoolRelease_(apr_pool_t *pool, id object) {
1627 else if (pool == NULL)
1628 return [object autorelease];
1630 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1635 template <typename Type_>
1636 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
1637 return (Type_) CYPoolRelease_(pool, (id) object);
1640 /* Objective-C Strings {{{ */
1641 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
1643 return [value UTF8String];
1645 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
1646 char *string(new(pool) char[size]);
1647 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
1648 throw CYError(context, "[NSString getCString:maxLength:encoding:] == NO");
1653 JSStringRef CYCopyJSString_(NSString *value) {
1655 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
1658 return CYCopyJSString(CYPoolCString(pool, value));
1662 JSStringRef CYCopyJSString(id value) {
1665 // XXX: this definition scares me; is anyone using this?!
1666 NSString *string([value description]);
1667 return CYCopyJSString_(string);
1670 NSString *CYCopyNSString(const CYUTF8String &value) {
1672 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
1674 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
1678 NSString *CYCopyNSString(JSStringRef value) {
1680 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
1682 return CYCopyNSString(CYCastCString_(value));
1686 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
1687 return CYCopyNSString(CYJSString(context, value));
1690 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
1691 return CYPoolRelease(pool, CYCopyNSString(value));
1694 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
1695 const char *name(sel_getName(sel));
1696 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
1699 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1700 return CYPoolRelease(pool, CYCopyNSString(value));
1703 CYUTF8String CYCastUTF8String(NSString *value) {
1704 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
1705 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
1709 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
1710 if (exception == NULL)
1712 *exception = CYCastJSValue(context, error);
1715 size_t CYGetIndex(NSString *value) {
1716 return CYGetIndex(CYCastUTF8String(value));
1719 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
1720 return CYGetOffset(CYPoolCString(pool, context, value), index);
1723 static JSClassRef Instance_;
1724 static JSClassRef Internal_;
1725 static JSClassRef Message_;
1726 static JSClassRef Messages_;
1727 static JSClassRef Selector_;
1728 static JSClassRef Super_;
1730 static JSClassRef ObjectiveC_Classes_;
1731 static JSClassRef ObjectiveC_Image_Classes_;
1732 static JSClassRef ObjectiveC_Images_;
1733 static JSClassRef ObjectiveC_Protocols_;
1735 static JSObjectRef Instance_prototype_;
1738 static Class NSCFBoolean_;
1739 static Class NSCFType_;
1742 static Class NSArray_;
1743 static Class NSDictionary_;
1744 static Class NSMessageBuilder_;
1745 static Class NSZombie_;
1746 static Class Object_;
1748 static Type_privateData *Object_type;
1749 static Type_privateData *Selector_type;
1751 Type_privateData *Instance::GetType() const {
1755 Type_privateData *Selector_privateData::GetType() const {
1756 return Selector_type;
1759 // XXX: trick this out with associated objects!
1760 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
1762 return Instance_prototype_;
1764 // XXX: I need to think through multi-context
1765 typedef std::map<id, JSValueRef> CacheMap;
1766 static CacheMap cache_;
1768 JSValueRef &value(cache_[self]);
1772 JSClassRef _class(NULL);
1773 JSValueRef prototype;
1775 if (self == NSArray_)
1776 prototype = Array_prototype_;
1777 else if (self == NSDictionary_)
1778 prototype = Object_prototype_;
1780 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
1782 JSObjectRef object(JSObjectMake(context, _class, NULL));
1783 JSObjectSetPrototype(context, object, prototype);
1785 JSValueProtect(context, object);
1790 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
1791 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
1792 if (_class == NSArray_)
1794 if (Class super = class_getSuperclass(_class))
1795 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
1797 JSObjectSetPrototype(context, value, Array_prototype_);*/
1801 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
1802 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
1806 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
1807 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
1811 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
1812 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
1813 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
1817 Instance::~Instance() {
1818 if ((flags_ & Transient) == 0)
1819 // XXX: does this handle background threads correctly?
1820 // XXX: this simply does not work on the console because I'm stupid
1821 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
1824 struct Message_privateData :
1829 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
1830 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
1836 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
1837 Instance::Flags flags;
1840 flags = Instance::Transient;
1842 flags = Instance::None;
1843 object = [object retain];
1846 return Instance::Make(context, object, flags);
1849 @interface NSMethodSignature (Cycript)
1850 - (NSString *) _typeString;
1853 @interface NSObject (Cycript)
1855 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1856 - (JSType) cy$JSType;
1858 - (NSObject *) cy$toJSON:(NSString *)key;
1859 - (NSString *) cy$toCYON;
1860 - (NSString *) cy$toKey;
1862 - (bool) cy$hasProperty:(NSString *)name;
1863 - (NSObject *) cy$getProperty:(NSString *)name;
1864 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
1865 - (bool) cy$deleteProperty:(NSString *)name;
1870 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1873 NSString *CYCastNSCYON(id value) {
1879 Class _class(object_getClass(value));
1880 SEL sel(@selector(cy$toCYON));
1882 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
1883 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1884 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1885 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1886 string = [value cy$toCYON];
1889 if (value == NSZombie_)
1890 string = @"_NSZombie_";
1891 else if (_class == NSZombie_)
1892 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1893 // XXX: frowny /in/ the pants
1894 else if (value == NSMessageBuilder_ || value == Object_)
1897 string = [NSString stringWithFormat:@"%@", value];
1900 // XXX: frowny pants
1902 string = @"undefined";
1909 struct PropertyAttributes {
1914 const char *variable;
1916 const char *getter_;
1917 const char *setter_;
1927 PropertyAttributes(objc_property_t property) :
1939 name = property_getName(property);
1940 const char *attributes(property_getAttributes(property));
1942 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
1944 case 'R': readonly = true; break;
1945 case 'C': copy = true; break;
1946 case '&': retain = true; break;
1947 case 'N': nonatomic = true; break;
1948 case 'G': getter_ = token + 1; break;
1949 case 'S': setter_ = token + 1; break;
1950 case 'V': variable = token + 1; break;
1954 /*if (variable == NULL) {
1955 variable = property_getName(property);
1956 size_t size(strlen(variable));
1957 char *name(new(pool_) char[size + 2]);
1959 memcpy(name + 1, variable, size);
1960 name[size + 1] = '\0';
1965 const char *Getter() {
1966 if (getter_ == NULL)
1967 getter_ = apr_pstrdup(pool_, name);
1971 const char *Setter() {
1972 if (setter_ == NULL && !readonly) {
1973 size_t length(strlen(name));
1975 char *temp(new(pool_) char[length + 5]);
1981 temp[3] = toupper(name[0]);
1982 memcpy(temp + 4, name + 1, length - 1);
1985 temp[length + 3] = ':';
1986 temp[length + 4] = '\0';
1997 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
1998 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
2003 @interface CYWebUndefined : NSObject {
2006 + (CYWebUndefined *) undefined;
2010 @implementation CYWebUndefined
2012 + (CYWebUndefined *) undefined {
2013 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
2019 #define WebUndefined CYWebUndefined
2022 /* Bridge: CYJSObject {{{ */
2023 @interface CYJSObject : NSMutableDictionary {
2024 JSObjectRef object_;
2025 JSContextRef context_;
2028 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
2030 - (NSObject *) cy$toJSON:(NSString *)key;
2032 - (NSUInteger) count;
2033 - (id) objectForKey:(id)key;
2034 - (NSEnumerator *) keyEnumerator;
2035 - (void) setObject:(id)object forKey:(id)key;
2036 - (void) removeObjectForKey:(id)key;
2040 /* Bridge: CYJSArray {{{ */
2041 @interface CYJSArray : NSMutableArray {
2042 JSObjectRef object_;
2043 JSContextRef context_;
2046 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
2048 - (NSUInteger) count;
2049 - (id) objectAtIndex:(NSUInteger)index;
2051 - (void) addObject:(id)anObject;
2052 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
2053 - (void) removeLastObject;
2054 - (void) removeObjectAtIndex:(NSUInteger)index;
2055 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
2060 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
2061 JSValueRef exception(NULL);
2062 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
2063 CYThrow(context, exception);
2064 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
2065 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
2068 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
2069 if (!JSValueIsObjectOfClass(context, object, Instance_))
2070 return CYCastNSObject_(pool, context, object);
2072 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2073 return internal->GetValue();
2077 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
2078 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
2081 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
2085 switch (JSType type = JSValueGetType(context, value)) {
2086 case kJSTypeUndefined:
2087 object = [WebUndefined undefined];
2095 case kJSTypeBoolean:
2097 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
2100 object = [[NSNumber alloc] initWithBool:CYCastBool(context, value)];
2106 object = CYCopyNSNumber(context, value);
2111 object = CYCopyNSString(context, value);
2116 // XXX: this might could be more efficient
2117 object = CYCastNSObject(pool, context, (JSObjectRef) value);
2122 throw CYError(context, "JSValueGetType() == 0x%x", type);
2129 return CYPoolRelease(pool, object);
2131 return [object retain];
2134 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
2135 return CYNSObject(pool, context, value, true);
2138 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
2139 return CYNSObject(pool, context, value, false);
2142 /* Bridge: NSArray {{{ */
2143 @implementation NSArray (Cycript)
2145 - (NSString *) cy$toCYON {
2146 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
2147 [json appendString:@"["];
2151 for (id object in self) {
2153 for (size_t index(0), count([self count]); index != count; ++index) {
2154 id object([self objectAtIndex:index]);
2157 [json appendString:@","];
2160 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
2161 [json appendString:CYCastNSCYON(object)];
2163 [json appendString:@","];
2168 [json appendString:@"]"];
2172 - (bool) cy$hasProperty:(NSString *)name {
2173 if ([name isEqualToString:@"length"])
2176 size_t index(CYGetIndex(name));
2177 if (index == _not(size_t) || index >= [self count])
2178 return [super cy$hasProperty:name];
2183 - (NSObject *) cy$getProperty:(NSString *)name {
2184 if ([name isEqualToString:@"length"]) {
2185 NSUInteger count([self count]);
2187 return [NSNumber numberWithUnsignedInteger:count];
2189 return [NSNumber numberWithUnsignedInt:count];
2193 size_t index(CYGetIndex(name));
2194 if (index == _not(size_t) || index >= [self count])
2195 return [super cy$getProperty:name];
2197 return [self objectAtIndex:index];
2202 /* Bridge: NSDictionary {{{ */
2203 @implementation NSDictionary (Cycript)
2205 - (NSString *) cy$toCYON {
2206 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
2207 [json appendString:@"{"];
2211 for (id key in self) {
2213 NSEnumerator *keys([self keyEnumerator]);
2214 while (id key = [keys nextObject]) {
2217 [json appendString:@","];
2220 [json appendString:[key cy$toKey]];
2221 [json appendString:@":"];
2222 NSObject *object([self objectForKey:key]);
2223 [json appendString:CYCastNSCYON(object)];
2226 [json appendString:@"}"];
2230 - (bool) cy$hasProperty:(NSString *)name {
2231 return [self objectForKey:name] != nil;
2234 - (NSObject *) cy$getProperty:(NSString *)name {
2235 return [self objectForKey:name];
2240 /* Bridge: NSMutableArray {{{ */
2241 @implementation NSMutableArray (Cycript)
2243 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
2244 if ([name isEqualToString:@"length"]) {
2245 // XXX: is this not intelligent?
2246 NSNumber *number(reinterpret_cast<NSNumber *>(value));
2248 NSUInteger size([number unsignedIntegerValue]);
2250 NSUInteger size([number unsignedIntValue]);
2252 NSUInteger count([self count]);
2254 [self removeObjectsInRange:NSMakeRange(size, count - size)];
2255 else if (size != count) {
2256 WebUndefined *undefined([WebUndefined undefined]);
2257 for (size_t i(count); i != size; ++i)
2258 [self addObject:undefined];
2263 size_t index(CYGetIndex(name));
2264 if (index == _not(size_t))
2265 return [super cy$setProperty:name to:value];
2267 id object(value ?: [NSNull null]);
2269 size_t count([self count]);
2271 [self replaceObjectAtIndex:index withObject:object];
2273 if (index != count) {
2274 WebUndefined *undefined([WebUndefined undefined]);
2275 for (size_t i(count); i != index; ++i)
2276 [self addObject:undefined];
2279 [self addObject:object];
2285 - (bool) cy$deleteProperty:(NSString *)name {
2286 size_t index(CYGetIndex(name));
2287 if (index == _not(size_t) || index >= [self count])
2288 return [super cy$deleteProperty:name];
2289 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
2295 /* Bridge: NSMutableDictionary {{{ */
2296 @implementation NSMutableDictionary (Cycript)
2298 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
2299 [self setObject:(value ?: [NSNull null]) forKey:name];
2303 - (bool) cy$deleteProperty:(NSString *)name {
2304 if ([self objectForKey:name] == nil)
2307 [self removeObjectForKey:name];
2314 /* Bridge: NSNumber {{{ */
2315 @implementation NSNumber (Cycript)
2317 - (JSType) cy$JSType {
2319 // XXX: this just seems stupid
2320 if ([self class] == NSCFBoolean_)
2321 return kJSTypeBoolean;
2323 return kJSTypeNumber;
2326 - (NSObject *) cy$toJSON:(NSString *)key {
2330 - (NSString *) cy$toCYON {
2331 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
2334 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry {
2335 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
2336 } CYObjectiveCatch }
2340 /* Bridge: NSNull {{{ */
2341 @implementation NSNull (Cycript)
2343 - (JSType) cy$JSType {
2347 - (NSObject *) cy$toJSON:(NSString *)key {
2351 - (NSString *) cy$toCYON {
2357 /* Bridge: NSObject {{{ */
2358 @implementation NSObject (Cycript)
2360 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry {
2361 return CYMakeInstance(context, self, false);
2362 } CYObjectiveCatch }
2364 - (JSType) cy$JSType {
2365 return kJSTypeObject;
2368 - (NSObject *) cy$toJSON:(NSString *)key {
2369 return [self description];
2372 - (NSString *) cy$toCYON {
2373 return [[self cy$toJSON:@""] cy$toCYON];
2376 - (NSString *) cy$toKey {
2377 return [self cy$toCYON];
2380 - (bool) cy$hasProperty:(NSString *)name {
2384 - (NSObject *) cy$getProperty:(NSString *)name {
2388 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
2392 - (bool) cy$deleteProperty:(NSString *)name {
2398 /* Bridge: NSProxy {{{ */
2399 @implementation NSProxy (Cycript)
2401 - (NSObject *) cy$toJSON:(NSString *)key {
2402 return [self description];
2405 - (NSString *) cy$toCYON {
2406 return [[self cy$toJSON:@""] cy$toCYON];
2411 /* Bridge: NSString {{{ */
2412 @implementation NSString (Cycript)
2414 - (JSType) cy$JSType {
2415 return kJSTypeString;
2418 - (NSObject *) cy$toJSON:(NSString *)key {
2422 - (NSString *) cy$toCYON {
2423 std::ostringstream str;
2424 CYUTF8String string(CYCastUTF8String(self));
2425 CYStringify(str, string.data, string.size);
2426 std::string value(str.str());
2427 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
2430 - (NSString *) cy$toKey {
2431 if (CYIsKey(CYCastUTF8String(self)))
2433 return [self cy$toCYON];
2438 /* Bridge: WebUndefined {{{ */
2439 @implementation WebUndefined (Cycript)
2441 - (JSType) cy$JSType {
2442 return kJSTypeUndefined;
2445 - (NSObject *) cy$toJSON:(NSString *)key {
2449 - (NSString *) cy$toCYON {
2450 return @"undefined";
2453 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry {
2454 return CYJSUndefined(context);
2455 } CYObjectiveCatch }
2460 static bool CYIsClass(id self) {
2461 // XXX: this is a lame object_isClass
2462 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2465 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
2466 id self(CYCastNSObject(pool, context, value));
2467 if (CYIsClass(self))
2468 return (Class) self;
2469 throw CYError(context, "got something that is not a Class");
2473 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
2475 size_t size(JSPropertyNameArrayGetCount(names));
2476 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
2477 for (size_t index(0); index != size; ++index)
2478 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
2482 JSValueRef CYCastJSValue(JSContextRef context, id value) { CYPoolTry {
2484 return CYJSNull(context);
2485 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
2486 return [value cy$JSValueInContext:context];
2488 return CYMakeInstance(context, value, false);
2489 } CYPoolCatch(NULL) }
2491 @implementation CYJSObject
2493 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
2494 if ((self = [super init]) != nil) {
2497 JSValueProtect(context_, object_);
2499 } CYObjectiveCatch }
2501 - (void) dealloc { CYObjectiveTry {
2502 JSValueUnprotect(context_, object_);
2504 } CYObjectiveCatch }
2506 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
2507 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
2508 if (!CYIsCallable(context_, toJSON))
2509 return [super cy$toJSON:key];
2511 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
2512 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
2513 // XXX: do I really want an NSNull here?!
2514 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
2516 } CYObjectiveCatch }
2518 - (NSString *) cy$toCYON { CYObjectiveTry {
2520 JSValueRef exception(NULL);
2521 const char *cyon(CYPoolCCYON(pool, context_, object_));
2522 CYThrow(context_, exception);
2524 return [super cy$toCYON];
2526 return [NSString stringWithUTF8String:cyon];
2527 } CYObjectiveCatch }
2529 - (NSUInteger) count { CYObjectiveTry {
2530 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
2531 size_t size(JSPropertyNameArrayGetCount(names));
2532 JSPropertyNameArrayRelease(names);
2534 } CYObjectiveCatch }
2536 - (id) objectForKey:(id)key { CYObjectiveTry {
2537 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
2538 if (JSValueIsUndefined(context_, value))
2540 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
2541 } CYObjectiveCatch }
2543 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
2544 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
2545 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
2546 JSPropertyNameArrayRelease(names);
2548 } CYObjectiveCatch }
2550 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
2551 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
2552 } CYObjectiveCatch }
2554 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
2555 JSValueRef exception(NULL);
2556 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
2557 CYThrow(context_, exception);
2558 } CYObjectiveCatch }
2562 @implementation CYJSArray
2564 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
2565 if ((self = [super init]) != nil) {
2568 JSValueProtect(context_, object_);
2570 } CYObjectiveCatch }
2572 - (void) dealloc { CYObjectiveTry {
2573 JSValueUnprotect(context_, object_);
2575 } CYObjectiveCatch }
2577 - (NSUInteger) count { CYObjectiveTry {
2578 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
2579 } CYObjectiveCatch }
2581 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
2582 size_t bounds([self count]);
2583 if (index >= bounds)
2584 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
2585 JSValueRef exception(NULL);
2586 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
2587 CYThrow(context_, exception);
2588 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
2589 } CYObjectiveCatch }
2591 - (void) addObject:(id)object { CYObjectiveTry {
2592 JSValueRef exception(NULL);
2593 JSValueRef arguments[1];
2594 arguments[0] = CYCastJSValue(context_, object);
2595 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
2596 CYThrow(context_, exception);
2597 } CYObjectiveCatch }
2599 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
2600 size_t bounds([self count] + 1);
2601 if (index >= bounds)
2602 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
2603 JSValueRef exception(NULL);
2604 JSValueRef arguments[3];
2605 arguments[0] = CYCastJSValue(context_, index);
2606 arguments[1] = CYCastJSValue(context_, 0);
2607 arguments[2] = CYCastJSValue(context_, object);
2608 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
2609 CYThrow(context_, exception);
2610 } CYObjectiveCatch }
2612 - (void) removeLastObject { CYObjectiveTry {
2613 JSValueRef exception(NULL);
2614 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
2615 CYThrow(context_, exception);
2616 } CYObjectiveCatch }
2618 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
2619 size_t bounds([self count]);
2620 if (index >= bounds)
2621 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
2622 JSValueRef exception(NULL);
2623 JSValueRef arguments[2];
2624 arguments[0] = CYCastJSValue(context_, index);
2625 arguments[1] = CYCastJSValue(context_, 1);
2626 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
2627 CYThrow(context_, exception);
2628 } CYObjectiveCatch }
2630 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
2631 size_t bounds([self count]);
2632 if (index >= bounds)
2633 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
2634 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
2635 } CYObjectiveCatch }
2639 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
2643 JSObjectRef object_;
2651 // XXX: delete object_? ;(
2654 static CYInternal *Get(id self) {
2655 CYInternal *internal(NULL);
2656 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
2657 // XXX: do something epic? ;P
2663 static CYInternal *Set(id self) {
2664 CYInternal *internal(NULL);
2665 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
2666 if (internal == NULL) {
2667 internal = new CYInternal();
2668 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
2671 // XXX: do something epic? ;P
2677 bool HasProperty(JSContextRef context, JSStringRef name) {
2678 if (object_ == NULL)
2680 return JSObjectHasProperty(context, object_, name);
2683 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
2684 if (object_ == NULL)
2686 return CYGetProperty(context, object_, name);
2689 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
2690 if (object_ == NULL)
2691 object_ = JSObjectMake(context, NULL, NULL);
2692 CYSetProperty(context, object_, name, value);
2696 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
2697 Selector_privateData *internal(new Selector_privateData(sel));
2698 return JSObjectMake(context, Selector_, internal);
2701 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
2702 if (JSValueIsObjectOfClass(context, value, Selector_)) {
2703 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2704 return reinterpret_cast<SEL>(internal->value_);
2706 return CYCastPointer<SEL>(context, value);
2709 void *CYObjectiveC_ExecuteStart() {
2710 return (void *) [[NSAutoreleasePool alloc] init];
2713 void CYObjectiveC_ExecuteEnd(void *handle) {
2714 return [(NSAutoreleasePool *) handle release];
2717 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) {
2719 return Instance::Make(context, nil);
2720 if (Class _class = objc_getClass(name.data))
2721 return CYMakeInstance(context, _class, true);
2725 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
2726 switch (type->primitive) {
2728 case sig::typename_P:
2729 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
2732 case sig::selector_P:
2733 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
2743 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) {
2744 switch (type->primitive) {
2746 if (id object = *reinterpret_cast<id *>(data)) {
2747 JSValueRef value(CYCastJSValue(context, object));
2753 case sig::typename_P:
2754 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
2756 case sig::selector_P:
2757 if (SEL sel = *reinterpret_cast<SEL *>(data))
2758 return CYMakeSelector(context, sel);
2762 return CYJSNull(context);
2768 CYHooks CYObjectiveCHooks = {
2769 &CYObjectiveC_ExecuteStart,
2770 &CYObjectiveC_ExecuteEnd,
2771 &CYObjectiveC_RuntimeProperty,
2772 &CYObjectiveC_PoolFFI,
2773 &CYObjectiveC_FromFFI,
2776 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
2777 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
2781 method_getReturnType(method, type, sizeof(type));
2786 // XXX: possibly use a more "awesome" check?
2790 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, Class _class, SEL sel, objc_method *method) {
2792 return method_getTypeEncoding(method);
2794 const char *name(sel_getName(sel));
2796 sqlite3_stmt *statement;
2798 _sqlcall(sqlite3_prepare(Bridge_,
2800 "\"bridge\".\"mode\", "
2801 "\"bridge\".\"value\" "
2804 " \"bridge\".\"mode\" in (3, 4) and"
2805 " \"bridge\".\"name\" = ?"
2807 , -1, &statement, NULL));
2809 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
2814 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
2818 mode = sqlite3_column_int(statement, 0);
2819 value = sqlite3_column_pooled(pool, statement, 1);
2822 _sqlcall(sqlite3_finalize(statement));
2830 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2831 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2833 JSContextRef context(internal->context_);
2835 size_t count(internal->cif_.nargs);
2836 JSValueRef values[count];
2838 for (size_t index(0); index != count; ++index)
2839 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2841 JSObjectRef _this(CYCastJSObject(context, values[0]));
2843 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2844 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2847 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2848 Message_privateData *internal(new Message_privateData(sel, type, imp));
2849 return JSObjectMake(context, Message_, internal);
2852 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2853 JSObjectRef function(CYCastJSObject(context, value));
2854 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2855 return reinterpret_cast<IMP>(internal->GetValue());
2858 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2859 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2860 Class _class(internal->GetValue());
2863 const char *name(CYPoolCString(pool, context, property));
2865 if (SEL sel = sel_getUid(name))
2866 if (class_getInstanceMethod(_class, sel) != NULL)
2872 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2873 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2874 Class _class(internal->GetValue());
2877 const char *name(CYPoolCString(pool, context, property));
2879 if (SEL sel = sel_getUid(name))
2880 if (objc_method *method = class_getInstanceMethod(_class, sel))
2881 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2886 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2887 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2888 Class _class(internal->GetValue());
2891 const char *name(CYPoolCString(pool, context, property));
2893 SEL sel(sel_registerName(name));
2895 objc_method *method(class_getInstanceMethod(_class, sel));
2900 if (JSValueIsObjectOfClass(context, value, Message_)) {
2901 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2902 type = sig::Unparse(pool, &message->signature_);
2903 imp = reinterpret_cast<IMP>(message->GetValue());
2905 type = CYPoolTypeEncoding(pool, context, _class, sel, method);
2906 imp = CYMakeMessage(context, value, type);
2910 method_setImplementation(method, imp);
2912 class_replaceMethod(_class, sel, imp, type);
2918 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2919 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2920 Class _class(internal->GetValue());
2923 const char *name(CYPoolCString(pool, property));
2925 if (SEL sel = sel_getUid(name))
2926 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
2927 objc_method_list list = {NULL, 1, {method}};
2928 class_removeMethods(_class, &list);
2936 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2937 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2938 Class _class(internal->GetValue());
2941 objc_method **data(class_copyMethodList(_class, &size));
2942 for (size_t i(0); i != size; ++i)
2943 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2947 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2948 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2949 id self(internal->GetValue());
2951 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2955 NSString *name(CYCastNSString(pool, property));
2957 if (CYInternal *internal = CYInternal::Get(self))
2958 if (internal->HasProperty(context, property))
2961 Class _class(object_getClass(self));
2964 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2965 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2966 if ([self cy$hasProperty:name])
2968 } CYPoolCatch(false)
2970 const char *string(CYPoolCString(pool, context, name));
2972 if (class_getProperty(_class, string) != NULL)
2975 if (SEL sel = sel_getUid(string))
2976 if (CYImplements(self, _class, sel, true))
2982 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2983 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2984 id self(internal->GetValue());
2986 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2987 return Internal::Make(context, self, object);
2990 NSString *name(CYCastNSString(pool, property));
2992 if (CYInternal *internal = CYInternal::Get(self))
2993 if (JSValueRef value = internal->GetProperty(context, property))
2997 if (NSObject *data = [self cy$getProperty:name])
2998 return CYCastJSValue(context, data);
3001 const char *string(CYPoolCString(pool, context, name));
3002 Class _class(object_getClass(self));
3005 if (objc_property_t property = class_getProperty(_class, string)) {
3006 PropertyAttributes attributes(property);
3007 SEL sel(sel_registerName(attributes.Getter()));
3008 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
3012 if (SEL sel = sel_getUid(string))
3013 if (CYImplements(self, _class, sel, true))
3014 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
3019 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
3020 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3021 id self(internal->GetValue());
3025 NSString *name(CYCastNSString(pool, property));
3026 NSObject *data(CYCastNSObject(pool, context, value));
3029 if ([self cy$setProperty:name to:data])
3033 const char *string(CYPoolCString(pool, context, name));
3034 Class _class(object_getClass(self));
3037 if (objc_property_t property = class_getProperty(_class, string)) {
3038 PropertyAttributes attributes(property);
3039 if (const char *setter = attributes.Setter()) {
3040 SEL sel(sel_registerName(setter));
3041 JSValueRef arguments[1] = {value};
3042 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
3048 size_t length(strlen(string));
3050 char set[length + 5];
3056 if (string[0] != '\0') {
3057 set[3] = toupper(string[0]);
3058 memcpy(set + 4, string + 1, length - 1);
3061 set[length + 3] = ':';
3062 set[length + 4] = '\0';
3064 if (SEL sel = sel_getUid(set))
3065 if (CYImplements(self, _class, sel, false)) {
3066 JSValueRef arguments[1] = {value};
3067 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
3070 if (CYInternal *internal = CYInternal::Set(self)) {
3071 internal->SetProperty(context, property, value);
3078 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
3079 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3080 id self(internal->GetValue());
3083 NSString *name(CYCastNSString(NULL, property));
3084 return [self cy$deleteProperty:name];
3088 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3089 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3090 id self(internal->GetValue());
3093 Class _class(object_getClass(self));
3098 objc_property_t *data(class_copyPropertyList(_class, &size));
3099 for (size_t i(0); i != size; ++i)
3100 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
3106 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
3107 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3108 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
3112 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
3113 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
3114 Class _class(internal->GetValue());
3115 if (!CYIsClass(_class))
3118 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
3119 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
3120 // XXX: this isn't always safe
3121 return [linternal->GetValue() isKindOfClass:_class];
3127 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
3128 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
3131 id self(internal->GetValue());
3132 const char *name(CYPoolCString(pool, context, property));
3134 if (object_getInstanceVariable(self, name, NULL) != NULL)
3140 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
3141 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
3144 id self(internal->GetValue());
3145 const char *name(CYPoolCString(pool, context, property));
3147 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
3148 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
3149 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
3155 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
3156 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
3159 id self(internal->GetValue());
3160 const char *name(CYPoolCString(pool, context, property));
3162 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
3163 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
3164 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
3171 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
3172 if (Class super = class_getSuperclass(_class))
3173 Internal_getPropertyNames_(super, names);
3176 Ivar *data(class_copyIvarList(_class, &size));
3177 for (size_t i(0); i != size; ++i)
3178 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
3182 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3183 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
3186 id self(internal->GetValue());
3187 Class _class(object_getClass(self));
3189 Internal_getPropertyNames_(_class, names);
3192 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3193 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
3194 return internal->GetOwner();
3197 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
3199 NSString *name(CYCastNSString(pool, property));
3200 if (Class _class = NSClassFromString(name))
3201 return CYMakeInstance(context, _class, true);
3205 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3206 size_t size(objc_getClassList(NULL, 0));
3207 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
3210 size_t writ(objc_getClassList(data, size));
3213 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
3219 for (size_t i(0); i != writ; ++i)
3220 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
3226 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
3227 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
3230 const char *name(CYPoolCString(pool, context, property));
3232 const char **data(objc_copyClassNamesForImage(internal, &size));
3234 for (size_t i(0); i != size; ++i)
3235 if (strcmp(name, data[i]) == 0) {
3236 if (Class _class = objc_getClass(name)) {
3237 value = CYMakeInstance(context, _class, true);
3248 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3249 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
3251 const char **data(objc_copyClassNamesForImage(internal, &size));
3252 for (size_t i(0); i != size; ++i)
3253 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3257 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
3259 const char *name(CYPoolCString(pool, context, property));
3261 const char **data(objc_copyImageNames(&size));
3262 for (size_t i(0); i != size; ++i)
3263 if (strcmp(name, data[i]) == 0) {
3272 JSObjectRef value(JSObjectMake(context, NULL, NULL));
3273 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
3277 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3279 const char **data(objc_copyImageNames(&size));
3280 for (size_t i(0); i != size; ++i)
3281 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3285 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
3287 NSString *name(CYCastNSString(pool, property));
3288 if (Protocol *protocol = NSProtocolFromString(name))
3289 return CYMakeInstance(context, protocol, true);
3293 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3295 Protocol **data(objc_copyProtocolList(&size));
3296 for (size_t i(0); i != size; ++i)
3297 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
3301 static bool stret(ffi_type *ffi_type) {
3302 return ffi_type->type == FFI_TYPE_STRUCT && (
3303 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
3304 struct_forward_array[ffi_type->size] != 0
3308 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) { CYTry {
3312 _class = object_getClass(self);
3314 if (objc_method *method = class_getInstanceMethod(_class, _cmd))
3315 type = method_getTypeEncoding(method);
3318 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
3320 throw CYError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3321 type = CYPoolCString(pool, context, [method _typeString]);
3325 objc_super super = {self, _class};
3326 void *arg0 = &super;
3332 sig::Signature signature;
3333 sig::Parse(pool, &signature, type, &Structor_);
3336 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3338 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSendSuper_stret) : reinterpret_cast<void (*)()>(&objc_msgSendSuper);
3339 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3342 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
3344 throw CYError(context, "too few arguments to objc_msgSend");
3354 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
3355 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3356 self = internal->GetValue();
3357 _class = internal->class_;;
3358 uninitialized = false;
3359 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
3360 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3361 self = internal->GetValue();
3363 uninitialized = internal->IsUninitialized();
3365 internal->value_ = nil;
3367 self = CYCastNSObject(pool, context, arguments[0]);
3369 uninitialized = false;
3373 return CYJSNull(context);
3375 _cmd = CYCastSEL(context, arguments[1]);
3377 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
3380 /* Hook: objc_registerClassPair {{{ */
3381 // XXX: replace this with associated objects
3383 MSHook(void, CYDealloc, id self, SEL sel) {
3384 CYInternal *internal;
3385 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
3386 if (internal != NULL)
3388 _CYDealloc(self, sel);
3391 MSHook(void, objc_registerClassPair, Class _class) {
3392 Class super(class_getSuperclass(_class));
3393 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
3394 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
3395 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
3398 _objc_registerClassPair(_class);
3401 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
3403 throw CYError(context, "incorrect number of arguments to objc_registerClassPair");
3405 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3406 if (value == NULL || !CYIsClass(value))
3407 throw CYError(context, "incorrect number of arguments to objc_registerClassPair");
3408 Class _class((Class) value);
3409 $objc_registerClassPair(_class);
3410 return CYJSUndefined(context);
3414 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3415 JSValueRef setup[count + 2];
3418 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
3419 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
3422 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3424 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
3426 // XXX: handle Instance::Uninitialized?
3427 id self(CYCastNSObject(pool, context, _this));
3431 setup[1] = &internal->sel_;
3433 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3436 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
3438 throw CYError(context, "incorrect number of arguments to Super constructor");
3440 id self(CYCastNSObject(pool, context, arguments[0]));
3441 Class _class(CYCastClass(pool, context, arguments[1]));
3442 return cy::Super::Make(context, self, _class);
3445 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
3447 throw CYError(context, "incorrect number of arguments to Selector constructor");
3448 const char *name(CYCastCString(context, arguments[0]));
3449 return CYMakeSelector(context, sel_registerName(name));
3452 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
3454 throw CYError(context, "incorrect number of arguments to Instance constructor");
3455 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3456 return Instance::Make(context, self);
3459 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3460 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3461 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3464 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3465 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3466 Type_privateData *typical(internal->GetType());
3471 if (typical == NULL) {
3475 type = typical->type_;
3476 ffi = typical->ffi_;
3479 return CYMakePointer(context, &internal->value_, type, ffi, object);
3482 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3483 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3484 return Instance::Make(context, object_getClass(internal->GetValue()));
3487 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
3488 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3489 id self(internal->GetValue());
3490 if (!CYIsClass(self))
3491 return CYJSUndefined(context);
3492 return CYGetClassPrototype(context, self);
3495 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3496 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3497 id self(internal->GetValue());
3498 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3499 return CYJSUndefined(context);
3500 return Messages::Make(context, self);
3503 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
3504 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3507 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3508 return CYCastJSValue(context, CYJSString(CYCastNSCYON(internal->GetValue())));
3511 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
3512 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3515 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3518 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3519 // XXX: check for support of cy$toJSON?
3520 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3524 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
3525 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3528 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3531 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
3532 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3536 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
3537 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3538 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3541 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3542 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3545 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
3546 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3547 const char *name(sel_getName(internal->GetValue()));
3550 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3554 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
3556 throw CYError(context, "incorrect number of arguments to Selector.type");
3558 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3559 if (Class _class = CYCastClass(pool, context, arguments[0])) {
3560 SEL sel(internal->GetValue());
3561 if (objc_method *method = class_getInstanceMethod(_class, sel))
3562 if (const char *type = CYPoolTypeEncoding(pool, context, _class, sel, method))
3563 return CYCastJSValue(context, CYJSString(type));
3566 // XXX: do a lookup of some kind
3567 return CYJSNull(context);
3570 static JSStaticValue Selector_staticValues[2] = {
3571 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3572 {NULL, NULL, NULL, 0}
3575 static JSStaticValue Instance_staticValues[5] = {
3576 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3577 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3578 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3579 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3580 {NULL, NULL, NULL, 0}
3583 static JSStaticFunction Instance_staticFunctions[5] = {
3584 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3585 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3586 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3587 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3591 static JSStaticFunction Internal_staticFunctions[2] = {
3592 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3596 static JSStaticFunction Selector_staticFunctions[5] = {
3597 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3598 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3599 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3600 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3604 void CYObjectiveC(JSContextRef context, JSObjectRef global) {
3605 hooks_ = &CYObjectiveCHooks;
3607 Object_type = new(Pool_) Type_privateData(Pool_, "@");
3608 Selector_type = new(Pool_) Type_privateData(Pool_, ":");
3611 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3612 NSCFType_ = objc_getClass("NSCFType");
3615 NSArray_ = objc_getClass("NSArray");
3616 NSDictionary_ = objc_getClass("NSDictonary");
3617 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3618 NSZombie_ = objc_getClass("_NSZombie_");
3619 Object_ = objc_getClass("Object");
3621 JSClassDefinition definition;
3623 definition = kJSClassDefinitionEmpty;
3624 definition.className = "Instance";
3625 definition.staticValues = Instance_staticValues;
3626 definition.staticFunctions = Instance_staticFunctions;
3627 definition.hasProperty = &Instance_hasProperty;
3628 definition.getProperty = &Instance_getProperty;
3629 definition.setProperty = &Instance_setProperty;
3630 definition.deleteProperty = &Instance_deleteProperty;
3631 definition.getPropertyNames = &Instance_getPropertyNames;
3632 definition.callAsConstructor = &Instance_callAsConstructor;
3633 definition.hasInstance = &Instance_hasInstance;
3634 definition.finalize = &Finalize;
3635 Instance_ = JSClassCreate(&definition);
3637 definition = kJSClassDefinitionEmpty;
3638 definition.className = "Internal";
3639 definition.staticFunctions = Internal_staticFunctions;
3640 definition.hasProperty = &Internal_hasProperty;
3641 definition.getProperty = &Internal_getProperty;
3642 definition.setProperty = &Internal_setProperty;
3643 definition.getPropertyNames = &Internal_getPropertyNames;
3644 definition.finalize = &Finalize;
3645 Internal_ = JSClassCreate(&definition);
3647 definition = kJSClassDefinitionEmpty;
3648 definition.className = "Message";
3649 definition.staticFunctions = Functor_staticFunctions;
3650 definition.callAsFunction = &Message_callAsFunction;
3651 definition.finalize = &Finalize;
3652 Message_ = JSClassCreate(&definition);
3654 definition = kJSClassDefinitionEmpty;
3655 definition.className = "Messages";
3656 definition.hasProperty = &Messages_hasProperty;
3657 definition.getProperty = &Messages_getProperty;
3658 definition.setProperty = &Messages_setProperty;
3660 definition.deleteProperty = &Messages_deleteProperty;
3662 definition.getPropertyNames = &Messages_getPropertyNames;
3663 definition.finalize = &Finalize;
3664 Messages_ = JSClassCreate(&definition);
3666 definition = kJSClassDefinitionEmpty;
3667 definition.className = "Selector";
3668 definition.staticValues = Selector_staticValues;
3669 definition.staticFunctions = Selector_staticFunctions;
3670 definition.callAsFunction = &Selector_callAsFunction;
3671 definition.finalize = &Finalize;
3672 Selector_ = JSClassCreate(&definition);
3674 definition = kJSClassDefinitionEmpty;
3675 definition.className = "Super";
3676 definition.staticFunctions = Internal_staticFunctions;
3677 definition.finalize = &Finalize;
3678 Super_ = JSClassCreate(&definition);
3680 definition = kJSClassDefinitionEmpty;
3681 definition.className = "ObjectiveC::Classes";
3682 definition.getProperty = &ObjectiveC_Classes_getProperty;
3683 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3684 ObjectiveC_Classes_ = JSClassCreate(&definition);
3686 definition = kJSClassDefinitionEmpty;
3687 definition.className = "ObjectiveC::Images";
3688 definition.getProperty = &ObjectiveC_Images_getProperty;
3689 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3690 ObjectiveC_Images_ = JSClassCreate(&definition);
3692 definition = kJSClassDefinitionEmpty;
3693 definition.className = "ObjectiveC::Image::Classes";
3694 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3695 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3696 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3698 definition = kJSClassDefinitionEmpty;
3699 definition.className = "ObjectiveC::Protocols";
3700 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3701 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3702 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3704 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
3705 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC);
3707 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3708 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3709 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3711 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3712 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3713 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3714 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
3716 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3717 JSValueProtect(context, Instance_prototype_);
3719 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3720 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3721 CYSetProperty(context, global, CYJSString("Super"), Super);
3723 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3724 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3726 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), Function_prototype_);
3727 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), Function_prototype_);
3729 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3732 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3738 JSGlobalContextRef CYGetJSContext() {
3739 if (Context_ == NULL) {
3740 JSClassDefinition definition;
3742 definition = kJSClassDefinitionEmpty;
3743 definition.className = "Functor";
3744 definition.staticFunctions = Functor_staticFunctions;
3745 definition.callAsFunction = &Functor_callAsFunction;
3746 definition.finalize = &Finalize;
3747 Functor_ = JSClassCreate(&definition);
3749 definition = kJSClassDefinitionEmpty;
3750 definition.className = "Pointer";
3751 definition.staticValues = Pointer_staticValues;
3752 definition.staticFunctions = Pointer_staticFunctions;
3753 definition.getProperty = &Pointer_getProperty;
3754 definition.setProperty = &Pointer_setProperty;
3755 definition.finalize = &Finalize;
3756 Pointer_ = JSClassCreate(&definition);
3758 definition = kJSClassDefinitionEmpty;
3759 definition.className = "Struct";
3760 definition.staticFunctions = Struct_staticFunctions;
3761 definition.getProperty = &Struct_getProperty;
3762 definition.setProperty = &Struct_setProperty;
3763 definition.getPropertyNames = &Struct_getPropertyNames;
3764 definition.finalize = &Finalize;
3765 Struct_ = JSClassCreate(&definition);
3767 definition = kJSClassDefinitionEmpty;
3768 definition.className = "Type";
3769 definition.staticFunctions = Type_staticFunctions;
3770 definition.getProperty = &Type_getProperty;
3771 definition.callAsFunction = &Type_callAsFunction;
3772 definition.callAsConstructor = &Type_callAsConstructor;
3773 definition.finalize = &Finalize;
3774 Type_privateData::Class_ = JSClassCreate(&definition);
3776 definition = kJSClassDefinitionEmpty;
3777 definition.className = "Runtime";
3778 definition.getProperty = &Runtime_getProperty;
3779 Runtime_ = JSClassCreate(&definition);
3781 definition = kJSClassDefinitionEmpty;
3782 //definition.getProperty = &Global_getProperty;
3783 JSClassRef Global(JSClassCreate(&definition));
3785 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3787 JSObjectRef global(CYGetGlobalObject(context));
3789 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3791 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3792 JSValueProtect(context, Array_);
3794 Error_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error")));
3795 JSValueProtect(context, Error_);
3797 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3798 JSValueProtect(context, Function_);
3800 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3801 JSValueProtect(context, String_);
3803 length_ = JSStringCreateWithUTF8CString("length");
3804 message_ = JSStringCreateWithUTF8CString("message");
3805 name_ = JSStringCreateWithUTF8CString("name");
3806 prototype_ = JSStringCreateWithUTF8CString("prototype");
3807 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3808 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3810 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3811 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3812 JSValueProtect(context, Object_prototype_);
3814 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3815 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3816 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3817 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3819 CYSetProperty(context, Array_prototype_, toCYON_, JSObjectMakeFunctionWithCallback(context, toCYON_, &Array_callAsFunction_toCYON), kJSPropertyAttributeDontEnum);
3821 JSValueProtect(context, Array_prototype_);
3822 JSValueProtect(context, Array_pop_);
3823 JSValueProtect(context, Array_push_);
3824 JSValueProtect(context, Array_splice_);
3826 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3828 Function_prototype_ = (JSObjectRef) CYGetProperty(context, Function_, prototype_);
3829 JSValueProtect(context, Function_prototype_);
3831 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), Function_prototype_);
3833 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3834 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3835 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
3837 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
3838 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
3839 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
3841 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3843 System_ = JSObjectMake(context, NULL, NULL);
3844 JSValueProtect(context, System_);
3846 CYSetProperty(context, global, CYJSString("system"), System_);
3847 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3848 //CYSetProperty(context, System_, CYJSString("global"), global);
3850 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3852 Result_ = JSStringCreateWithUTF8CString("_");
3854 CYObjectiveC(context, global);