1 /* Cycript - Remote Execution Server and Disassembler
2 * Copyright (C) 2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 #include <substrate.h>
41 #include <minimal/sqlite3.h>
46 #include "cycript.hpp"
48 #include "sig/parse.hpp"
49 #include "sig/ffi_type.hpp"
51 #include "Pooling.hpp"
58 #include <CoreFoundation/CoreFoundation.h>
59 #include <CoreFoundation/CFLogUtilities.h>
60 #include <JavaScriptCore/JSStringRefCF.h>
65 #include <WebKit/WebScriptObject.h>
67 #include <Foundation/Foundation.h>
73 #include <ext/stdio_filebuf.h>
81 #include "Cycript.tab.hh"
87 #define _throw(name, args...) \
88 @throw [NSException exceptionWithName:name reason:[NSString stringWithFormat:@args] userInfo:nil]
90 #define _throw(name, args...) ({ \
92 throw std::string(apr_psprintf(pool, args)); \
96 #define _assert(test, args...) do { \
98 _throw(NSInternalInconsistencyException, "*** _assert(%s):%s(%u):%s [errno=%d]", #test, __FILE__, __LINE__, __FUNCTION__, errno); \
101 #define _trace() do { \
102 fprintf(stderr, "_trace():%u\n", __LINE__); \
107 catch (NSException *error) { \
108 CYThrow(context, error, exception); \
120 *exception = CYCastJSValue(context, "catch(...)"); \
125 #define CYPoolTry { \
127 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
129 #define CYPoolCatch(value) \
130 @catch (NSException *error) { \
131 _saved = [error retain]; \
137 [_saved autorelease]; \
142 #define CYPoolCatch }
146 #define class_getSuperclass GSObjCSuper
147 #define object_getClass GSObjCClass
150 char *sqlite3_column_pooled(apr_pool_t *pool, sqlite3_stmt *stmt, int n) {
151 if (const unsigned char *value = sqlite3_column_text(stmt, n))
152 return apr_pstrdup(pool, (const char *) value);
156 void CYThrow(JSContextRef context, JSValueRef value);
158 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
160 struct CYUTF8String {
164 CYUTF8String(const char *data, size_t size) :
171 struct CYUTF16String {
172 const uint16_t *data;
175 CYUTF16String(const uint16_t *data, size_t size) :
182 /* JavaScript Properties {{{ */
183 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
184 JSValueRef exception(NULL);
185 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
186 CYThrow(context, exception);
190 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
191 JSValueRef exception(NULL);
192 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
193 CYThrow(context, exception);
197 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
198 JSValueRef exception(NULL);
199 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
200 CYThrow(context, exception);
203 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes = kJSPropertyAttributeNone) {
204 JSValueRef exception(NULL);
205 JSObjectSetProperty(context, object, name, value, attributes, &exception);
206 CYThrow(context, exception);
209 /* JavaScript Strings {{{ */
210 JSStringRef CYCopyJSString(const char *value) {
211 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
214 JSStringRef CYCopyJSString(JSStringRef value) {
215 return value == NULL ? NULL : JSStringRetain(value);
218 JSStringRef CYCopyJSString(CYUTF8String value) {
219 // XXX: this is very wrong
220 return CYCopyJSString(value.data);
223 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
224 if (JSValueIsNull(context, value))
226 JSValueRef exception(NULL);
227 JSStringRef string(JSValueToStringCopy(context, value, &exception));
228 CYThrow(context, exception);
238 JSStringRelease(string_);
242 CYJSString(const CYJSString &rhs) :
243 string_(CYCopyJSString(rhs.string_))
247 template <typename Arg0_>
248 CYJSString(Arg0_ arg0) :
249 string_(CYCopyJSString(arg0))
253 template <typename Arg0_, typename Arg1_>
254 CYJSString(Arg0_ arg0, Arg1_ arg1) :
255 string_(CYCopyJSString(arg0, arg1))
259 CYJSString &operator =(const CYJSString &rhs) {
261 string_ = CYCopyJSString(rhs.string_);
274 operator JSStringRef() const {
279 static CYUTF16String CYCastUTF16String(JSStringRef value) {
280 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
283 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value) {
284 _assert(pool != NULL);
286 CYUTF16String utf16(CYCastUTF16String(value));
287 const char *in(reinterpret_cast<const char *>(utf16.data));
289 iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL")));
291 size_t size(JSStringGetMaximumUTF8CStringSize(value));
292 char *out(new(pool) char[size]);
293 CYUTF8String utf8(out, size);
295 size = utf16.size * 2;
296 _syscall(iconv(conversion, const_cast<char **>(&in), &size, &out, &utf8.size));
299 utf8.size = out - utf8.data;
301 _syscall(iconv_close(conversion));
306 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
307 CYUTF8String utf8(CYPoolUTF8String(pool, value));
308 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
312 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
313 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
317 // XXX: this macro is unhygenic
318 #define CYCastCString_(string) ({ \
320 if (string == NULL) \
323 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
324 utf8 = reinterpret_cast<char *>(alloca(size)); \
325 JSStringGetUTF8CString(string, utf8, size); \
330 // XXX: this macro is unhygenic
331 #define CYCastCString(context, value) ({ \
335 else if (JSStringRef string = CYCopyJSString(context, value)) { \
336 utf8 = CYCastCString_(string); \
337 JSStringRelease(string); \
346 /* Objective-C Pool Release {{{ */
347 apr_status_t CYPoolRelease_(void *data) {
348 id object(reinterpret_cast<id>(data));
353 id CYPoolRelease_(apr_pool_t *pool, id object) {
356 else if (pool == NULL)
357 return [object autorelease];
359 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
364 template <typename Type_>
365 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
366 return (Type_) CYPoolRelease_(pool, (id) object);
369 /* Objective-C Strings {{{ */
370 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
372 return [value UTF8String];
374 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
375 char *string(new(pool) char[size]);
376 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
377 _throw(NSInternalInconsistencyException, "[NSString getCString:maxLength:encoding:] == NO");
382 JSStringRef CYCopyJSString_(NSString *value) {
384 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
387 return CYCopyJSString(CYPoolCString(pool, value));
391 JSStringRef CYCopyJSString(id value) {
394 // XXX: this definition scares me; is anyone using this?!
395 NSString *string([value description]);
396 return CYCopyJSString_(string);
399 NSString *CYCopyNSString(const CYUTF8String &value) {
401 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
403 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
407 NSString *CYCopyNSString(JSStringRef value) {
409 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
411 return CYCopyNSString(CYCastCString_(value));
415 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
416 return CYCopyNSString(CYJSString(context, value));
419 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
420 return CYPoolRelease(pool, CYCopyNSString(value));
423 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
424 const char *name(sel_getName(sel));
425 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
428 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
429 return CYPoolRelease(pool, CYCopyNSString(value));
432 CYUTF8String CYCastUTF8String(NSString *value) {
433 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
434 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
439 /* Index Offsets {{{ */
440 size_t CYGetIndex(const CYUTF8String &value) {
441 if (value.data[0] != '0') {
443 size_t index(strtoul(value.data, &end, 10));
444 if (value.data + value.size == end)
446 } else if (value.data[1] == '\0')
451 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
452 return CYGetIndex(CYPoolUTF8String(pool, value));
455 bool CYGetOffset(const char *value, ssize_t &index) {
456 if (value[0] != '0') {
458 index = strtol(value, &end, 10);
459 if (value + strlen(value) == end)
461 } else if (value[1] == '\0') {
470 size_t CYGetIndex(NSString *value) {
471 return CYGetIndex(CYCastUTF8String(value));
474 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
475 return CYGetOffset(CYPoolCString(pool, value), index);
480 /* JavaScript *ify {{{ */
481 void CYStringify(std::ostringstream &str, const char *data, size_t size) {
482 unsigned quot(0), apos(0);
483 for (const char *value(data), *end(data + size); value != end; ++value)
486 else if (*value == '\'')
489 bool single(quot > apos);
491 str << (single ? '\'' : '"');
493 for (const char *value(data), *end(data + size); value != end; ++value)
495 case '\\': str << "\\\\"; break;
496 case '\b': str << "\\b"; break;
497 case '\f': str << "\\f"; break;
498 case '\n': str << "\\n"; break;
499 case '\r': str << "\\r"; break;
500 case '\t': str << "\\t"; break;
501 case '\v': str << "\\v"; break;
516 if (*value < 0x20 || *value >= 0x7f)
517 str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(*value);
522 str << (single ? '\'' : '"');
525 void CYNumerify(std::ostringstream &str, double value) {
527 // XXX: I want this to print 1e3 rather than 1000
528 sprintf(string, "%.17g", value);
533 bool CYIsKey(CYUTF8String value) {
534 const char *data(value.data);
535 size_t size(value.size);
540 if (DigitRange_[data[0]]) {
541 size_t index(CYGetIndex(value));
542 if (index == _not(size_t))
545 if (!WordStartRange_[data[0]])
547 for (size_t i(1); i != size; ++i)
548 if (!WordEndRange_[data[i]])
555 static JSGlobalContextRef Context_;
556 static JSObjectRef System_;
558 static JSClassRef Functor_;
559 static JSClassRef Pointer_;
560 static JSClassRef Runtime_;
561 static JSClassRef Struct_;
564 static JSClassRef Instance_;
565 static JSClassRef Internal_;
566 static JSClassRef Message_;
567 static JSClassRef Messages_;
568 static JSClassRef Selector_;
569 static JSClassRef Super_;
571 static JSClassRef ObjectiveC_Classes_;
572 static JSClassRef ObjectiveC_Image_Classes_;
573 static JSClassRef ObjectiveC_Images_;
574 static JSClassRef ObjectiveC_Protocols_;
576 static JSObjectRef Instance_prototype_;
579 static JSObjectRef Array_;
580 static JSObjectRef Function_;
581 static JSObjectRef String_;
583 static JSStringRef Result_;
585 static JSStringRef length_;
586 static JSStringRef message_;
587 static JSStringRef name_;
588 static JSStringRef prototype_;
589 static JSStringRef toCYON_;
590 static JSStringRef toJSON_;
592 static JSObjectRef Object_prototype_;
594 static JSObjectRef Array_prototype_;
595 static JSObjectRef Array_pop_;
596 static JSObjectRef Array_push_;
597 static JSObjectRef Array_splice_;
601 static Class NSCFBoolean_;
602 static Class NSCFType_;
605 static Class NSArray_;
606 static Class NSDictionary_;
607 static Class NSMessageBuilder_;
608 static Class NSZombie_;
609 static Class Object_;
614 static void Finalize(JSObjectRef object) {
615 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
618 class Type_privateData;
628 CYValue(const void *value) :
629 value_(const_cast<void *>(value))
633 CYValue(const CYValue &rhs) :
638 virtual Type_privateData *GetType() const {
647 JSContextRef context_;
651 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
657 JSValueProtect(context_, owner_);
662 JSValueUnprotect(context_, owner_);
665 JSObjectRef GetOwner() const {
671 struct Selector_privateData :
674 Selector_privateData(SEL value) :
679 SEL GetValue() const {
680 return reinterpret_cast<SEL>(value_);
683 virtual Type_privateData *GetType() const;
686 // XXX: trick this out with associated objects!
687 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
689 return Instance_prototype_;
691 // XXX: I need to think through multi-context
692 typedef std::map<id, JSValueRef> CacheMap;
693 static CacheMap cache_;
695 JSValueRef &value(cache_[self]);
699 JSClassRef _class(NULL);
700 JSValueRef prototype;
702 if (self == NSArray_)
703 prototype = Array_prototype_;
704 else if (self == NSDictionary_)
705 prototype = Object_prototype_;
707 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
709 JSObjectRef object(JSObjectMake(context, _class, NULL));
710 JSObjectSetPrototype(context, object, prototype);
712 JSValueProtect(context, object);
722 Transient = (1 << 0),
723 Uninitialized = (1 << 1),
728 Instance(id value, Flags flags) :
734 virtual ~Instance() {
735 if ((flags_ & Transient) == 0)
736 // XXX: does this handle background threads correctly?
737 // XXX: this simply does not work on the console because I'm stupid
738 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
741 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
742 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
743 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
747 id GetValue() const {
748 return reinterpret_cast<id>(value_);
751 bool IsUninitialized() const {
752 return (flags_ & Uninitialized) != 0;
755 virtual Type_privateData *GetType() const;
763 Super(id value, Class _class) :
764 Instance(value, Instance::Transient),
769 static JSObjectRef Make(JSContextRef context, id object, Class _class) {
770 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
778 Messages(Class value) :
783 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
784 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
785 if (_class == NSArray_)
787 if (Class super = class_getSuperclass(_class))
788 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
790 JSObjectSetPrototype(context, value, Array_prototype_);*/
794 Class GetValue() const {
795 return reinterpret_cast<Class>(value_);
802 Internal(id value, JSContextRef context, JSObjectRef owner) :
803 CYOwned(value, context, owner)
807 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
808 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
811 id GetValue() const {
812 return reinterpret_cast<id>(value_);
819 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
821 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
822 lhs.name = apr_pstrdup(pool, rhs.name);
823 if (rhs.type == NULL)
826 lhs.type = new(pool) Type;
827 Copy(pool, *lhs.type, *rhs.type);
829 lhs.offset = rhs.offset;
832 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
833 size_t count(rhs.count);
835 lhs.elements = new(pool) Element[count];
836 for (size_t index(0); index != count; ++index)
837 Copy(pool, lhs.elements[index], rhs.elements[index]);
840 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
841 lhs.primitive = rhs.primitive;
842 lhs.name = apr_pstrdup(pool, rhs.name);
843 lhs.flags = rhs.flags;
845 if (sig::IsAggregate(rhs.primitive))
846 Copy(pool, lhs.data.signature, rhs.data.signature);
848 sig::Type *&lht(lhs.data.data.type);
849 sig::Type *&rht(rhs.data.data.type);
854 lht = new(pool) Type;
855 Copy(pool, *lht, *rht);
858 lhs.data.data.size = rhs.data.data.size;
862 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
864 lhs.alignment = rhs.alignment;
866 if (rhs.elements == NULL)
870 while (rhs.elements[count] != NULL)
873 lhs.elements = new(pool) ffi_type *[count + 1];
874 lhs.elements[count] = NULL;
876 for (size_t index(0); index != count; ++index) {
877 // XXX: if these are libffi native then you can just take them
878 ffi_type *ffi(new(pool) ffi_type);
879 lhs.elements[index] = ffi;
880 sig::Copy(pool, *ffi, *rhs.elements[index]);
887 struct CStringMapLess :
888 std::binary_function<const char *, const char *, bool>
890 _finline bool operator ()(const char *lhs, const char *rhs) const {
891 return strcmp(lhs, rhs) < 0;
895 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
899 sqlite3_stmt *statement;
901 _sqlcall(sqlite3_prepare(Bridge_,
903 "\"bridge\".\"mode\", "
904 "\"bridge\".\"value\" "
907 " \"bridge\".\"mode\" in (3, 4) and"
908 " \"bridge\".\"name\" = ?"
910 , -1, &statement, NULL));
912 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
917 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
921 mode = sqlite3_column_int(statement, 0);
922 value = sqlite3_column_pooled(pool, statement, 1);
925 _sqlcall(sqlite3_finalize(statement));
934 sig::Parse(pool, &type->data.signature, value, &Structor_);
938 sig::Signature signature;
939 sig::Parse(pool, &signature, value, &Structor_);
940 type = signature.elements[0].type;
945 struct Type_privateData :
949 static Type_privateData *Object;
950 static Type_privateData *Selector;
953 static JSClassRef Class_;
958 void Set(sig::Type *type) {
959 type_ = new(pool_) sig::Type;
960 sig::Copy(pool_, *type_, *type);
963 Type_privateData(apr_pool_t *pool, const char *type) :
969 sig::Signature signature;
970 sig::Parse(pool_, &signature, type, &Structor_);
971 type_ = signature.elements[0].type;
974 Type_privateData(sig::Type *type) :
981 Type_privateData(sig::Type *type, ffi_type *ffi) {
982 ffi_ = new(pool_) ffi_type;
983 sig::Copy(pool_, *ffi_, *ffi);
989 ffi_ = new(pool_) ffi_type;
991 sig::Element element;
993 element.type = type_;
996 sig::Signature signature;
997 signature.elements = &element;
1001 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
1009 JSClassRef Type_privateData::Class_;
1012 Type_privateData *Type_privateData::Object;
1013 Type_privateData *Type_privateData::Selector;
1015 Type_privateData *Instance::GetType() const {
1016 return Type_privateData::Object;
1019 Type_privateData *Selector_privateData::GetType() const {
1020 return Type_privateData::Selector;
1027 Type_privateData *type_;
1029 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
1030 CYOwned(value, context, owner),
1031 type_(new(pool_) Type_privateData(type))
1036 struct Struct_privateData :
1039 Type_privateData *type_;
1041 Struct_privateData(JSContextRef context, JSObjectRef owner) :
1042 CYOwned(NULL, context, owner)
1047 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
1048 static TypeMap Types_;
1050 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1051 Struct_privateData *internal(new Struct_privateData(context, owner));
1052 apr_pool_t *pool(internal->pool_);
1053 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
1054 internal->type_ = typical;
1057 internal->value_ = data;
1059 size_t size(typical->GetFFI()->size);
1060 void *copy(apr_palloc(internal->pool_, size));
1061 memcpy(copy, data, size);
1062 internal->value_ = copy;
1065 return JSObjectMake(context, Struct_, internal);
1068 struct Functor_privateData :
1071 sig::Signature signature_;
1074 Functor_privateData(const char *type, void (*value)()) :
1075 CYValue(reinterpret_cast<void *>(value))
1077 sig::Parse(pool_, &signature_, type, &Structor_);
1078 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
1081 void (*GetValue())() const {
1082 return reinterpret_cast<void (*)()>(value_);
1086 struct Closure_privateData :
1089 JSContextRef context_;
1090 JSObjectRef function_;
1092 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
1093 Functor_privateData(type, NULL),
1097 JSValueProtect(context_, function_);
1100 virtual ~Closure_privateData() {
1101 JSValueUnprotect(context_, function_);
1106 struct Message_privateData :
1111 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
1112 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
1118 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
1119 Instance::Flags flags;
1122 flags = Instance::Transient;
1124 flags = Instance::None;
1125 object = [object retain];
1128 return Instance::Make(context, object, flags);
1132 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
1133 return JSValueMakeBoolean(context, value);
1136 JSValueRef CYCastJSValue(JSContextRef context, double value) {
1137 return JSValueMakeNumber(context, value);
1140 #define CYCastJSValue_(Type_) \
1141 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
1142 return JSValueMakeNumber(context, static_cast<double>(value)); \
1146 CYCastJSValue_(unsigned int)
1147 CYCastJSValue_(long int)
1148 CYCastJSValue_(long unsigned int)
1149 CYCastJSValue_(long long int)
1150 CYCastJSValue_(long long unsigned int)
1152 JSValueRef CYJSUndefined(JSContextRef context) {
1153 return JSValueMakeUndefined(context);
1157 @interface NSMethodSignature (Cycript)
1158 - (NSString *) _typeString;
1161 @interface NSObject (Cycript)
1163 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1164 - (JSType) cy$JSType;
1166 - (NSObject *) cy$toJSON:(NSString *)key;
1167 - (NSString *) cy$toCYON;
1168 - (NSString *) cy$toKey;
1170 - (bool) cy$hasProperty:(NSString *)name;
1171 - (NSObject *) cy$getProperty:(NSString *)name;
1172 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
1173 - (bool) cy$deleteProperty:(NSString *)name;
1178 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1183 NSString *CYCastNSCYON(id value) {
1189 Class _class(object_getClass(value));
1190 SEL sel(@selector(cy$toCYON));
1192 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
1193 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1194 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1195 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1196 string = [value cy$toCYON];
1199 if (value == NSZombie_)
1200 string = @"_NSZombie_";
1201 else if (_class == NSZombie_)
1202 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1203 // XXX: frowny /in/ the pants
1204 else if (value == NSMessageBuilder_ || value == Object_)
1207 string = [NSString stringWithFormat:@"%@", value];
1210 // XXX: frowny pants
1212 string = @"undefined";
1221 struct PropertyAttributes {
1226 const char *variable;
1228 const char *getter_;
1229 const char *setter_;
1239 PropertyAttributes(objc_property_t property) :
1251 name = property_getName(property);
1252 const char *attributes(property_getAttributes(property));
1254 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
1256 case 'R': readonly = true; break;
1257 case 'C': copy = true; break;
1258 case '&': retain = true; break;
1259 case 'N': nonatomic = true; break;
1260 case 'G': getter_ = token + 1; break;
1261 case 'S': setter_ = token + 1; break;
1262 case 'V': variable = token + 1; break;
1266 /*if (variable == NULL) {
1267 variable = property_getName(property);
1268 size_t size(strlen(variable));
1269 char *name(new(pool_) char[size + 2]);
1271 memcpy(name + 1, variable, size);
1272 name[size + 1] = '\0';
1277 const char *Getter() {
1278 if (getter_ == NULL)
1279 getter_ = apr_pstrdup(pool_, name);
1283 const char *Setter() {
1284 if (setter_ == NULL && !readonly) {
1285 size_t length(strlen(name));
1287 char *temp(new(pool_) char[length + 5]);
1293 temp[3] = toupper(name[0]);
1294 memcpy(temp + 4, name + 1, length - 1);
1297 temp[length + 3] = ':';
1298 temp[length + 4] = '\0';
1311 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
1312 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
1319 @interface CYWebUndefined : NSObject {
1322 + (CYWebUndefined *) undefined;
1326 @implementation CYWebUndefined
1328 + (CYWebUndefined *) undefined {
1329 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
1335 #define WebUndefined CYWebUndefined
1340 /* Bridge: NSArray {{{ */
1341 @implementation NSArray (Cycript)
1343 - (NSString *) cy$toCYON {
1344 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1345 [json appendString:@"["];
1349 for (id object in self) {
1351 for (size_t index(0), count([self count]); index != count; ++index) {
1352 id object([self objectAtIndex:index]);
1355 [json appendString:@","];
1358 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
1359 [json appendString:CYCastNSCYON(object)];
1361 [json appendString:@","];
1366 [json appendString:@"]"];
1370 - (bool) cy$hasProperty:(NSString *)name {
1371 if ([name isEqualToString:@"length"])
1374 size_t index(CYGetIndex(name));
1375 if (index == _not(size_t) || index >= [self count])
1376 return [super cy$hasProperty:name];
1381 - (NSObject *) cy$getProperty:(NSString *)name {
1382 if ([name isEqualToString:@"length"]) {
1383 NSUInteger count([self count]);
1385 return [NSNumber numberWithUnsignedInteger:count];
1387 return [NSNumber numberWithUnsignedInt:count];
1391 size_t index(CYGetIndex(name));
1392 if (index == _not(size_t) || index >= [self count])
1393 return [super cy$getProperty:name];
1395 return [self objectAtIndex:index];
1400 /* Bridge: NSDictionary {{{ */
1401 @implementation NSDictionary (Cycript)
1403 - (NSString *) cy$toCYON {
1404 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1405 [json appendString:@"{"];
1409 for (id key in self) {
1411 NSEnumerator *keys([self keyEnumerator]);
1412 while (id key = [keys nextObject]) {
1415 [json appendString:@","];
1418 [json appendString:[key cy$toKey]];
1419 [json appendString:@":"];
1420 NSObject *object([self objectForKey:key]);
1421 [json appendString:CYCastNSCYON(object)];
1424 [json appendString:@"}"];
1428 - (bool) cy$hasProperty:(NSString *)name {
1429 return [self objectForKey:name] != nil;
1432 - (NSObject *) cy$getProperty:(NSString *)name {
1433 return [self objectForKey:name];
1438 /* Bridge: NSMutableArray {{{ */
1439 @implementation NSMutableArray (Cycript)
1441 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1442 if ([name isEqualToString:@"length"]) {
1443 // XXX: is this not intelligent?
1444 NSNumber *number(reinterpret_cast<NSNumber *>(value));
1446 NSUInteger size([number unsignedIntegerValue]);
1448 NSUInteger size([number unsignedIntValue]);
1450 NSUInteger count([self count]);
1452 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1453 else if (size != count) {
1454 WebUndefined *undefined([WebUndefined undefined]);
1455 for (size_t i(count); i != size; ++i)
1456 [self addObject:undefined];
1461 size_t index(CYGetIndex(name));
1462 if (index == _not(size_t))
1463 return [super cy$setProperty:name to:value];
1465 id object(value ?: [NSNull null]);
1467 size_t count([self count]);
1469 [self replaceObjectAtIndex:index withObject:object];
1471 if (index != count) {
1472 WebUndefined *undefined([WebUndefined undefined]);
1473 for (size_t i(count); i != index; ++i)
1474 [self addObject:undefined];
1477 [self addObject:object];
1483 - (bool) cy$deleteProperty:(NSString *)name {
1484 size_t index(CYGetIndex(name));
1485 if (index == _not(size_t) || index >= [self count])
1486 return [super cy$deleteProperty:name];
1487 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1493 /* Bridge: NSMutableDictionary {{{ */
1494 @implementation NSMutableDictionary (Cycript)
1496 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1497 [self setObject:(value ?: [NSNull null]) forKey:name];
1501 - (bool) cy$deleteProperty:(NSString *)name {
1502 if ([self objectForKey:name] == nil)
1505 [self removeObjectForKey:name];
1512 /* Bridge: NSNumber {{{ */
1513 @implementation NSNumber (Cycript)
1515 - (JSType) cy$JSType {
1517 // XXX: this just seems stupid
1518 if ([self class] == NSCFBoolean_)
1519 return kJSTypeBoolean;
1521 return kJSTypeNumber;
1524 - (NSObject *) cy$toJSON:(NSString *)key {
1528 - (NSString *) cy$toCYON {
1529 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1532 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1533 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1538 /* Bridge: NSNull {{{ */
1539 @implementation NSNull (Cycript)
1541 - (JSType) cy$JSType {
1545 - (NSObject *) cy$toJSON:(NSString *)key {
1549 - (NSString *) cy$toCYON {
1555 /* Bridge: NSObject {{{ */
1556 @implementation NSObject (Cycript)
1558 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1559 return CYMakeInstance(context, self, false);
1562 - (JSType) cy$JSType {
1563 return kJSTypeObject;
1566 - (NSObject *) cy$toJSON:(NSString *)key {
1567 return [self description];
1570 - (NSString *) cy$toCYON {
1571 return [[self cy$toJSON:@""] cy$toCYON];
1574 - (NSString *) cy$toKey {
1575 return [self cy$toCYON];
1578 - (bool) cy$hasProperty:(NSString *)name {
1582 - (NSObject *) cy$getProperty:(NSString *)name {
1586 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1590 - (bool) cy$deleteProperty:(NSString *)name {
1596 /* Bridge: NSProxy {{{ */
1597 @implementation NSProxy (Cycript)
1599 - (NSObject *) cy$toJSON:(NSString *)key {
1600 return [self description];
1603 - (NSString *) cy$toCYON {
1604 return [[self cy$toJSON:@""] cy$toCYON];
1609 /* Bridge: NSString {{{ */
1610 @implementation NSString (Cycript)
1612 - (JSType) cy$JSType {
1613 return kJSTypeString;
1616 - (NSObject *) cy$toJSON:(NSString *)key {
1620 - (NSString *) cy$toCYON {
1621 std::ostringstream str;
1622 CYUTF8String string(CYCastUTF8String(self));
1623 CYStringify(str, string.data, string.size);
1624 std::string value(str.str());
1625 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1628 - (NSString *) cy$toKey {
1629 if (CYIsKey(CYCastUTF8String(self)))
1631 return [self cy$toCYON];
1636 /* Bridge: WebUndefined {{{ */
1637 @implementation WebUndefined (Cycript)
1639 - (JSType) cy$JSType {
1640 return kJSTypeUndefined;
1643 - (NSObject *) cy$toJSON:(NSString *)key {
1647 - (NSString *) cy$toCYON {
1648 return @"undefined";
1651 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1652 return CYJSUndefined(context);
1658 /* Bridge: CYJSObject {{{ */
1659 @interface CYJSObject : NSMutableDictionary {
1660 JSObjectRef object_;
1661 JSContextRef context_;
1664 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1666 - (NSObject *) cy$toJSON:(NSString *)key;
1668 - (NSUInteger) count;
1669 - (id) objectForKey:(id)key;
1670 - (NSEnumerator *) keyEnumerator;
1671 - (void) setObject:(id)object forKey:(id)key;
1672 - (void) removeObjectForKey:(id)key;
1676 /* Bridge: CYJSArray {{{ */
1677 @interface CYJSArray : NSMutableArray {
1678 JSObjectRef object_;
1679 JSContextRef context_;
1682 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1684 - (NSUInteger) count;
1685 - (id) objectAtIndex:(NSUInteger)index;
1687 - (void) addObject:(id)anObject;
1688 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1689 - (void) removeLastObject;
1690 - (void) removeObjectAtIndex:(NSUInteger)index;
1691 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1698 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1699 JSValueRef exception(NULL);
1700 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1701 CYThrow(context, exception);
1702 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1703 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1706 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1707 if (!JSValueIsObjectOfClass(context, object, Instance_))
1708 return CYCastNSObject_(pool, context, object);
1710 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1711 return internal->GetValue();
1716 double CYCastDouble(const char *value, size_t size) {
1718 double number(strtod(value, &end));
1719 if (end != value + size)
1724 double CYCastDouble(const char *value) {
1725 return CYCastDouble(value, strlen(value));
1728 double CYCastDouble(JSContextRef context, JSValueRef value) {
1729 JSValueRef exception(NULL);
1730 double number(JSValueToNumber(context, value, &exception));
1731 CYThrow(context, exception);
1736 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
1737 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
1741 bool CYCastBool(JSContextRef context, JSValueRef value) {
1742 return JSValueToBoolean(context, value);
1746 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1750 switch (JSType type = JSValueGetType(context, value)) {
1751 case kJSTypeUndefined:
1752 object = [WebUndefined undefined];
1760 case kJSTypeBoolean:
1762 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
1765 object = [[NSNumber alloc] initWithBool:CYCastBool(context, value)];
1771 object = CYCopyNSNumber(context, value);
1776 object = CYCopyNSString(context, value);
1781 // XXX: this might could be more efficient
1782 object = CYCastNSObject(pool, context, (JSObjectRef) value);
1787 _throw(NSInternalInconsistencyException, "JSValueGetType() == 0x%x", type);
1794 return CYPoolRelease(pool, object);
1796 return [object retain];
1799 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1800 return CYNSObject(pool, context, value, true);
1802 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1803 return CYNSObject(pool, context, value, false);
1806 static bool CYIsClass(id self) {
1807 // XXX: this is a lame object_isClass
1808 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1811 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1812 id self(CYCastNSObject(pool, context, value));
1813 if (CYIsClass(self))
1814 return (Class) self;
1815 _throw(NSInvalidArgumentException, "got something that is not a Class");
1819 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1821 size_t size(JSPropertyNameArrayGetCount(names));
1822 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1823 for (size_t index(0); index != size; ++index)
1824 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1829 void CYThrow(JSContextRef context, JSValueRef value) {
1833 @throw CYCastNSObject(NULL, context, value);
1836 throw "throwing something";
1840 JSValueRef CYJSNull(JSContextRef context) {
1841 return JSValueMakeNull(context);
1844 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1845 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1848 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1849 return CYCastJSValue(context, CYJSString(value));
1853 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1855 return CYJSNull(context);
1856 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1857 return [value cy$JSValueInContext:context];
1859 return CYMakeInstance(context, value, false);
1863 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1864 JSValueRef exception(NULL);
1865 JSObjectRef object(JSValueToObject(context, value, &exception));
1866 CYThrow(context, exception);
1870 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1871 if (exception == NULL)
1873 *exception = CYCastJSValue(context, error);
1876 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1877 JSValueRef exception(NULL);
1878 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1879 CYThrow(context, exception);
1883 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1884 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
1887 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSObjectRef object);
1890 @implementation CYJSObject
1892 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1893 if ((self = [super init]) != nil) {
1896 JSValueProtect(context_, object_);
1901 JSValueUnprotect(context_, object_);
1905 - (NSObject *) cy$toJSON:(NSString *)key {
1906 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1907 if (!CYIsCallable(context_, toJSON))
1908 return [super cy$toJSON:key];
1910 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1911 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1912 // XXX: do I really want an NSNull here?!
1913 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1917 - (NSString *) cy$toCYON {
1919 JSValueRef exception(NULL);
1920 const char *cyon(CYPoolCCYON(pool, context_, object_));
1921 CYThrow(context_, exception);
1922 return cyon == NULL ? [super cy$toCYON] : [NSString stringWithUTF8String:cyon];
1925 - (NSUInteger) count {
1926 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1927 size_t size(JSPropertyNameArrayGetCount(names));
1928 JSPropertyNameArrayRelease(names);
1932 - (id) objectForKey:(id)key {
1933 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1934 if (JSValueIsUndefined(context_, value))
1936 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1939 - (NSEnumerator *) keyEnumerator {
1940 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1941 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1942 JSPropertyNameArrayRelease(names);
1946 - (void) setObject:(id)object forKey:(id)key {
1947 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1950 - (void) removeObjectForKey:(id)key {
1951 JSValueRef exception(NULL);
1952 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1953 CYThrow(context_, exception);
1958 @implementation CYJSArray
1960 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1961 if ((self = [super init]) != nil) {
1964 JSValueProtect(context_, object_);
1969 JSValueUnprotect(context_, object_);
1973 - (NSUInteger) count {
1974 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1977 - (id) objectAtIndex:(NSUInteger)index {
1978 size_t bounds([self count]);
1979 if (index >= bounds)
1980 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1981 JSValueRef exception(NULL);
1982 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1983 CYThrow(context_, exception);
1984 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1987 - (void) addObject:(id)object {
1988 JSValueRef exception(NULL);
1989 JSValueRef arguments[1];
1990 arguments[0] = CYCastJSValue(context_, object);
1991 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1992 CYThrow(context_, exception);
1995 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1996 size_t bounds([self count] + 1);
1997 if (index >= bounds)
1998 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1999 JSValueRef exception(NULL);
2000 JSValueRef arguments[3];
2001 arguments[0] = CYCastJSValue(context_, index);
2002 arguments[1] = CYCastJSValue(context_, 0);
2003 arguments[2] = CYCastJSValue(context_, object);
2004 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
2005 CYThrow(context_, exception);
2008 - (void) removeLastObject {
2009 JSValueRef exception(NULL);
2010 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
2011 CYThrow(context_, exception);
2014 - (void) removeObjectAtIndex:(NSUInteger)index {
2015 size_t bounds([self count]);
2016 if (index >= bounds)
2017 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
2018 JSValueRef exception(NULL);
2019 JSValueRef arguments[2];
2020 arguments[0] = CYCastJSValue(context_, index);
2021 arguments[1] = CYCastJSValue(context_, 1);
2022 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
2023 CYThrow(context_, exception);
2026 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
2027 size_t bounds([self count]);
2028 if (index >= bounds)
2029 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
2030 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
2036 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
2037 switch (JSType type = JSValueGetType(context, value)) {
2038 case kJSTypeUndefined:
2042 case kJSTypeBoolean:
2043 return CYCastBool(context, value) ? "true" : "false";
2045 case kJSTypeNumber: {
2046 std::ostringstream str;
2047 CYNumerify(str, CYCastDouble(context, value));
2048 std::string value(str.str());
2049 return apr_pstrmemdup(pool, value.c_str(), value.size());
2052 case kJSTypeString: {
2053 std::ostringstream str;
2054 CYUTF8String string(CYPoolUTF8String(pool, CYJSString(context, value)));
2055 CYStringify(str, string.data, string.size);
2056 std::string value(str.str());
2057 return apr_pstrmemdup(pool, value.c_str(), value.size());
2060 case kJSTypeObject: CYTry {
2061 return CYPoolCCYON(pool, context, (JSObjectRef) value);
2065 _throw(NSInternalInconsistencyException, "JSValueGetType() == 0x%x", type);
2071 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
2072 JSValueRef exception(NULL);
2073 const char *cyon(CYPoolCCYON(pool, context, value, &exception));
2074 CYThrow(context, exception);
2078 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
2079 JSValueRef toCYON(CYGetProperty(context, object, toCYON_));
2080 if (CYIsCallable(context, toCYON)) {
2081 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
2082 return CYPoolCString(pool, context, value);
2085 JSValueRef toJSON(CYGetProperty(context, object, toJSON_));
2086 if (CYIsCallable(context, toJSON)) {
2087 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
2088 JSValueRef exception(NULL);
2089 const char *cyon(CYPoolCCYON(pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments), &exception));
2090 CYThrow(context, exception);
2094 std::ostringstream str;
2098 // XXX: this is, sadly, going to leak
2099 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
2103 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
2104 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
2105 JSValueRef value(CYGetProperty(context, object, name));
2112 CYUTF8String string(CYPoolUTF8String(pool, name));
2113 if (CYIsKey(string))
2116 CYStringify(str, string.data, string.size);
2118 str << ':' << CYPoolCCYON(pool, context, value);
2123 JSPropertyNameArrayRelease(names);
2125 std::string string(str.str());
2126 return apr_pstrmemdup(pool, string.c_str(), string.size());
2129 static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2131 std::ostringstream str;
2135 // XXX: this is, sadly, going to leak
2136 // XXX: shouldn't this be done with .length?!
2137 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, _this));
2141 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
2142 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
2143 JSValueRef value(CYGetProperty(context, _this, name));
2150 if (!JSValueIsUndefined(context, value))
2151 str << CYPoolCCYON(pool, context, value);
2160 JSPropertyNameArrayRelease(names);
2162 std::string value(str.str());
2163 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
2167 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
2171 JSObjectRef object_;
2179 // XXX: delete object_? ;(
2182 static CYInternal *Get(id self) {
2183 CYInternal *internal(NULL);
2184 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
2185 // XXX: do something epic? ;P
2191 static CYInternal *Set(id self) {
2192 CYInternal *internal(NULL);
2193 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
2194 if (internal == NULL) {
2195 internal = new CYInternal();
2196 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
2199 // XXX: do something epic? ;P
2205 bool HasProperty(JSContextRef context, JSStringRef name) {
2206 if (object_ == NULL)
2208 return JSObjectHasProperty(context, object_, name);
2211 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
2212 if (object_ == NULL)
2214 return CYGetProperty(context, object_, name);
2217 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
2218 if (object_ == NULL)
2219 object_ = JSObjectMake(context, NULL, NULL);
2220 CYSetProperty(context, object_, name, value);
2226 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
2227 Selector_privateData *internal(new Selector_privateData(sel));
2228 return JSObjectMake(context, Selector_, internal);
2232 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
2233 Pointer *internal(new Pointer(pointer, context, owner, type));
2234 return JSObjectMake(context, Pointer_, internal);
2237 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
2238 Functor_privateData *internal(new Functor_privateData(type, function));
2239 return JSObjectMake(context, Functor_, internal);
2242 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
2243 return CYGetOffset(CYPoolCString(pool, value), index);
2246 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
2247 switch (JSValueGetType(context, value)) {
2250 /*case kJSTypeString:
2251 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
2253 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
2254 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
2255 return internal->value_;
2258 double number(CYCastDouble(context, value));
2259 if (std::isnan(number))
2260 _throw(NSInvalidArgumentException, "cannot convert value to pointer");
2261 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
2265 template <typename Type_>
2266 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
2267 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
2271 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
2272 if (JSValueIsObjectOfClass(context, value, Selector_)) {
2273 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2274 return reinterpret_cast<SEL>(internal->value_);
2276 return CYCastPointer<SEL>(context, value);
2280 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
2281 switch (type->primitive) {
2282 case sig::boolean_P:
2283 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
2286 #define CYPoolFFI_(primitive, native) \
2287 case sig::primitive ## _P: \
2288 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
2291 CYPoolFFI_(uchar, unsigned char)
2292 CYPoolFFI_(char, char)
2293 CYPoolFFI_(ushort, unsigned short)
2294 CYPoolFFI_(short, short)
2295 CYPoolFFI_(ulong, unsigned long)
2296 CYPoolFFI_(long, long)
2297 CYPoolFFI_(uint, unsigned int)
2298 CYPoolFFI_(int, int)
2299 CYPoolFFI_(ulonglong, unsigned long long)
2300 CYPoolFFI_(longlong, long long)
2301 CYPoolFFI_(float, float)
2302 CYPoolFFI_(double, double)
2306 case sig::typename_P:
2307 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
2310 case sig::selector_P:
2311 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
2315 case sig::pointer_P:
2316 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
2320 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
2323 case sig::struct_P: {
2324 uint8_t *base(reinterpret_cast<uint8_t *>(data));
2325 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
2326 for (size_t index(0); index != type->data.signature.count; ++index) {
2327 sig::Element *element(&type->data.signature.elements[index]);
2328 ffi_type *field(ffi->elements[index]);
2331 if (aggregate == NULL)
2334 rhs = CYGetProperty(context, aggregate, index);
2335 if (JSValueIsUndefined(context, rhs)) {
2336 if (element->name != NULL)
2337 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
2340 if (JSValueIsUndefined(context, rhs)) undefined:
2341 _throw(NSInvalidArgumentException, "unable to extract structure value");
2345 CYPoolFFI(pool, context, element->type, field, base, rhs);
2347 base += field->size;
2355 fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
2360 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
2363 switch (type->primitive) {
2364 case sig::boolean_P:
2365 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
2368 #define CYFromFFI_(primitive, native) \
2369 case sig::primitive ## _P: \
2370 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
2373 CYFromFFI_(uchar, unsigned char)
2374 CYFromFFI_(char, char)
2375 CYFromFFI_(ushort, unsigned short)
2376 CYFromFFI_(short, short)
2377 CYFromFFI_(ulong, unsigned long)
2378 CYFromFFI_(long, long)
2379 CYFromFFI_(uint, unsigned int)
2380 CYFromFFI_(int, int)
2381 CYFromFFI_(ulonglong, unsigned long long)
2382 CYFromFFI_(longlong, long long)
2383 CYFromFFI_(float, float)
2384 CYFromFFI_(double, double)
2387 case sig::object_P: {
2388 if (id object = *reinterpret_cast<id *>(data)) {
2389 value = CYCastJSValue(context, object);
2395 case sig::typename_P:
2396 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
2399 case sig::selector_P:
2400 if (SEL sel = *reinterpret_cast<SEL *>(data))
2401 value = CYMakeSelector(context, sel);
2406 case sig::pointer_P:
2407 if (void *pointer = *reinterpret_cast<void **>(data))
2408 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
2413 if (char *utf8 = *reinterpret_cast<char **>(data))
2414 value = CYCastJSValue(context, utf8);
2419 value = CYMakeStruct(context, data, type, ffi, owner);
2423 value = CYJSUndefined(context);
2427 value = CYJSNull(context);
2431 fprintf(stderr, "CYFromFFI(%c)\n", type->primitive);
2439 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
2440 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
2444 method_getReturnType(method, type, sizeof(type));
2449 // XXX: possibly use a more "awesome" check?
2455 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, objc_method *method) {
2457 return method_getTypeEncoding(method);
2459 const char *name(sel_getName(sel));
2461 sqlite3_stmt *statement;
2463 _sqlcall(sqlite3_prepare(Bridge_,
2465 "\"bridge\".\"mode\", "
2466 "\"bridge\".\"value\" "
2469 " \"bridge\".\"mode\" in (3, 4) and"
2470 " \"bridge\".\"name\" = ?"
2472 , -1, &statement, NULL));
2474 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
2479 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
2483 mode = sqlite3_column_int(statement, 0);
2484 value = sqlite3_column_pooled(pool, statement, 1);
2487 _sqlcall(sqlite3_finalize(statement));
2496 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2497 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2499 JSContextRef context(internal->context_);
2501 size_t count(internal->cif_.nargs);
2502 JSValueRef values[count];
2504 for (size_t index(0); index != count; ++index)
2505 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2507 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2508 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2512 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2513 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2515 JSContextRef context(internal->context_);
2517 size_t count(internal->cif_.nargs);
2518 JSValueRef values[count];
2520 for (size_t index(0); index != count; ++index)
2521 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2523 JSObjectRef _this(CYCastJSObject(context, values[0]));
2525 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2526 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2530 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2531 // XXX: in case of exceptions this will leak
2532 // XXX: in point of fact, this may /need/ to leak :(
2533 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2535 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2536 NULL, sizeof(ffi_closure),
2537 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2541 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2542 _assert(status == FFI_OK);
2544 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2546 internal->value_ = closure;
2551 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2552 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2553 return JSObjectMake(context, Functor_, internal);
2556 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2557 JSValueRef exception(NULL);
2558 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2559 CYThrow(context, exception);
2562 JSObjectRef function(CYCastJSObject(context, value));
2563 return CYMakeFunctor(context, function, type);
2565 void (*function)()(CYCastPointer<void (*)()>(context, value));
2566 return CYMakeFunctor(context, function, type);
2571 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2572 Message_privateData *internal(new Message_privateData(sel, type, imp));
2573 return JSObjectMake(context, Message_, internal);
2576 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2577 JSObjectRef function(CYCastJSObject(context, value));
2578 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2579 return reinterpret_cast<IMP>(internal->GetValue());
2582 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2583 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2584 Class _class(internal->GetValue());
2587 const char *name(CYPoolCString(pool, property));
2589 if (SEL sel = sel_getUid(name))
2590 if (class_getInstanceMethod(_class, sel) != NULL)
2596 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2597 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2598 Class _class(internal->GetValue());
2601 const char *name(CYPoolCString(pool, property));
2603 if (SEL sel = sel_getUid(name))
2604 if (objc_method *method = class_getInstanceMethod(_class, sel))
2605 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2610 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2611 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2612 Class _class(internal->GetValue());
2615 const char *name(CYPoolCString(pool, property));
2617 SEL sel(sel_registerName(name));
2619 objc_method *method(class_getInstanceMethod(_class, sel));
2624 if (JSValueIsObjectOfClass(context, value, Message_)) {
2625 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2626 type = sig::Unparse(pool, &message->signature_);
2627 imp = reinterpret_cast<IMP>(message->GetValue());
2629 type = CYPoolTypeEncoding(pool, _class, sel, method);
2630 imp = CYMakeMessage(context, value, type);
2634 method_setImplementation(method, imp);
2636 class_replaceMethod(_class, sel, imp, type);
2642 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2643 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2644 Class _class(internal->GetValue());
2647 const char *name(CYPoolCString(pool, property));
2649 if (SEL sel = sel_getUid(name))
2650 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
2651 objc_method_list list = {NULL, 1, {method}};
2652 class_removeMethods(_class, &list);
2660 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2661 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2662 Class _class(internal->GetValue());
2665 objc_method **data(class_copyMethodList(_class, &size));
2666 for (size_t i(0); i != size; ++i)
2667 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2671 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2672 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2673 id self(internal->GetValue());
2675 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2679 NSString *name(CYCastNSString(pool, property));
2681 if (CYInternal *internal = CYInternal::Get(self))
2682 if (internal->HasProperty(context, property))
2685 Class _class(object_getClass(self));
2688 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2689 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2690 if ([self cy$hasProperty:name])
2692 } CYPoolCatch(false)
2694 const char *string(CYPoolCString(pool, name));
2696 if (class_getProperty(_class, string) != NULL)
2699 if (SEL sel = sel_getUid(string))
2700 if (CYImplements(self, _class, sel, true))
2706 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2707 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2708 id self(internal->GetValue());
2710 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2711 return Internal::Make(context, self, object);
2715 NSString *name(CYCastNSString(pool, property));
2717 if (CYInternal *internal = CYInternal::Get(self))
2718 if (JSValueRef value = internal->GetProperty(context, property))
2722 if (NSObject *data = [self cy$getProperty:name])
2723 return CYCastJSValue(context, data);
2726 const char *string(CYPoolCString(pool, name));
2727 Class _class(object_getClass(self));
2730 if (objc_property_t property = class_getProperty(_class, string)) {
2731 PropertyAttributes attributes(property);
2732 SEL sel(sel_registerName(attributes.Getter()));
2733 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
2737 if (SEL sel = sel_getUid(string))
2738 if (CYImplements(self, _class, sel, true))
2739 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
2745 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2746 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2747 id self(internal->GetValue());
2752 NSString *name(CYCastNSString(pool, property));
2753 NSObject *data(CYCastNSObject(pool, context, value));
2756 if ([self cy$setProperty:name to:data])
2760 const char *string(CYPoolCString(pool, name));
2761 Class _class(object_getClass(self));
2764 if (objc_property_t property = class_getProperty(_class, string)) {
2765 PropertyAttributes attributes(property);
2766 if (const char *setter = attributes.Setter()) {
2767 SEL sel(sel_registerName(setter));
2768 JSValueRef arguments[1] = {value};
2769 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
2775 size_t length(strlen(string));
2777 char set[length + 5];
2783 if (string[0] != '\0') {
2784 set[3] = toupper(string[0]);
2785 memcpy(set + 4, string + 1, length - 1);
2788 set[length + 3] = ':';
2789 set[length + 4] = '\0';
2791 if (SEL sel = sel_getUid(set))
2792 if (CYImplements(self, _class, sel, false)) {
2793 JSValueRef arguments[1] = {value};
2794 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
2797 if (CYInternal *internal = CYInternal::Set(self)) {
2798 internal->SetProperty(context, property, value);
2806 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2807 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2808 id self(internal->GetValue());
2812 NSString *name(CYCastNSString(NULL, property));
2813 return [self cy$deleteProperty:name];
2818 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2819 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2820 id self(internal->GetValue());
2823 Class _class(object_getClass(self));
2827 objc_property_t *data(class_copyPropertyList(_class, &size));
2828 for (size_t i(0); i != size; ++i)
2829 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2834 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2836 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2837 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2842 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2843 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2844 Class _class(internal->GetValue());
2845 if (!CYIsClass(_class))
2848 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2849 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2850 // XXX: this isn't always safe
2852 return [linternal->GetValue() isKindOfClass:_class];
2859 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2860 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2863 id self(internal->GetValue());
2864 const char *name(CYPoolCString(pool, property));
2866 if (object_getInstanceVariable(self, name, NULL) != NULL)
2872 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2873 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2877 id self(internal->GetValue());
2878 const char *name(CYPoolCString(pool, property));
2880 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2881 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2882 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2889 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2890 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2894 id self(internal->GetValue());
2895 const char *name(CYPoolCString(pool, property));
2897 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2898 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2899 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2907 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2908 if (Class super = class_getSuperclass(_class))
2909 Internal_getPropertyNames_(super, names);
2912 Ivar *data(class_copyIvarList(_class, &size));
2913 for (size_t i(0); i != size; ++i)
2914 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2918 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2919 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2922 id self(internal->GetValue());
2923 Class _class(object_getClass(self));
2925 Internal_getPropertyNames_(_class, names);
2928 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2929 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2930 return internal->GetOwner();
2934 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2935 Type_privateData *typical(internal->type_);
2936 sig::Type *type(typical->type_);
2940 const char *name(CYPoolCString(pool, property));
2941 size_t length(strlen(name));
2942 double number(CYCastDouble(name, length));
2944 size_t count(type->data.signature.count);
2946 if (std::isnan(number)) {
2947 if (property == NULL)
2950 sig::Element *elements(type->data.signature.elements);
2952 for (size_t local(0); local != count; ++local) {
2953 sig::Element *element(&elements[local]);
2954 if (element->name != NULL && strcmp(name, element->name) == 0) {
2962 index = static_cast<ssize_t>(number);
2963 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2968 ffi_type **elements(typical->GetFFI()->elements);
2970 base = reinterpret_cast<uint8_t *>(internal->value_);
2971 for (ssize_t local(0); local != index; ++local)
2972 base += elements[local]->size;
2977 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2978 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2979 Type_privateData *typical(internal->type_);
2981 ffi_type *ffi(typical->GetFFI());
2983 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2984 base += ffi->size * index;
2986 JSObjectRef owner(internal->GetOwner() ?: object);
2989 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2993 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2995 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2996 Type_privateData *typical(internal->type_);
2998 if (typical->type_ == NULL)
3002 if (!CYGetOffset(pool, property, offset))
3005 return Pointer_getIndex(context, object, offset, exception);
3008 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3009 return Pointer_getIndex(context, object, 0, exception);
3012 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
3013 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
3014 Type_privateData *typical(internal->type_);
3016 ffi_type *ffi(typical->GetFFI());
3018 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
3019 base += ffi->size * index;
3022 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
3027 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
3029 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
3030 Type_privateData *typical(internal->type_);
3032 if (typical->type_ == NULL)
3036 if (!CYGetOffset(pool, property, offset))
3039 return Pointer_setIndex(context, object, offset, value, exception);
3042 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
3043 return Pointer_setIndex(context, object, 0, value, exception);
3046 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3047 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
3048 Type_privateData *typical(internal->type_);
3049 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
3052 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3054 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
3055 Type_privateData *typical(internal->type_);
3061 if (!Index_(pool, internal, property, index, base))
3064 JSObjectRef owner(internal->GetOwner() ?: object);
3066 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
3070 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
3072 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
3073 Type_privateData *typical(internal->type_);
3079 if (!Index_(pool, internal, property, index, base))
3082 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
3087 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3088 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
3089 Type_privateData *typical(internal->type_);
3090 sig::Type *type(typical->type_);
3095 size_t count(type->data.signature.count);
3096 sig::Element *elements(type->data.signature.elements);
3100 for (size_t index(0); index != count; ++index) {
3102 name = elements[index].name;
3105 sprintf(number, "%lu", index);
3109 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
3113 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)()) {
3115 if (setups + count != signature->count - 1)
3116 _throw(NSInvalidArgumentException, "incorrect number of arguments to ffi function");
3118 size_t size(setups + count);
3120 memcpy(values, setup, sizeof(void *) * setups);
3122 for (size_t index(setups); index != size; ++index) {
3123 sig::Element *element(&signature->elements[index + 1]);
3124 ffi_type *ffi(cif->arg_types[index]);
3126 values[index] = new(pool) uint8_t[ffi->size];
3127 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
3130 uint8_t value[cif->rtype->size];
3131 ffi_call(cif, function, value, values);
3133 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
3138 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3141 NSString *name(CYCastNSString(pool, property));
3142 if (Class _class = NSClassFromString(name))
3143 return CYMakeInstance(context, _class, true);
3148 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3149 size_t size(objc_getClassList(NULL, 0));
3150 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
3153 size_t writ(objc_getClassList(data, size));
3156 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
3162 for (size_t i(0); i != writ; ++i)
3163 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
3169 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3170 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
3174 const char *name(CYPoolCString(pool, property));
3176 const char **data(objc_copyClassNamesForImage(internal, &size));
3178 for (size_t i(0); i != size; ++i)
3179 if (strcmp(name, data[i]) == 0) {
3180 if (Class _class = objc_getClass(name)) {
3181 value = CYMakeInstance(context, _class, true);
3193 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3194 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
3196 const char **data(objc_copyClassNamesForImage(internal, &size));
3197 for (size_t i(0); i != size; ++i)
3198 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3202 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3205 const char *name(CYPoolCString(pool, property));
3207 const char **data(objc_copyImageNames(&size));
3208 for (size_t i(0); i != size; ++i)
3209 if (strcmp(name, data[i]) == 0) {
3218 JSObjectRef value(JSObjectMake(context, NULL, NULL));
3219 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
3224 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3226 const char **data(objc_copyImageNames(&size));
3227 for (size_t i(0); i != size; ++i)
3228 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3232 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3235 NSString *name(CYCastNSString(pool, property));
3236 if (Protocol *protocol = NSProtocolFromString(name))
3237 return CYMakeInstance(context, protocol, true);
3242 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3244 Protocol **data(objc_copyProtocolList(&size));
3245 for (size_t i(0); i != size; ++i)
3246 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
3251 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
3252 Type_privateData *internal(new Type_privateData(NULL, type));
3253 return JSObjectMake(context, Type_privateData::Class_, internal);
3256 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
3257 Type_privateData *internal(new Type_privateData(type));
3258 return JSObjectMake(context, Type_privateData::Class_, internal);
3261 static void *CYCastSymbol(const char *name) {
3262 return dlsym(RTLD_DEFAULT, name);
3265 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3267 if (JSStringIsEqualToUTF8CString(property, "nil"))
3268 return Instance::Make(context, nil);
3273 const char *name(CYPoolCString(pool, property));
3276 if (Class _class = objc_getClass(name))
3277 return CYMakeInstance(context, _class, true);
3280 sqlite3_stmt *statement;
3282 _sqlcall(sqlite3_prepare(Bridge_,
3284 "\"bridge\".\"mode\", "
3285 "\"bridge\".\"value\" "
3288 " \"bridge\".\"name\" = ?"
3290 , -1, &statement, NULL));
3292 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
3297 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
3301 mode = sqlite3_column_int(statement, 0);
3302 value = sqlite3_column_pooled(pool, statement, 1);
3305 _sqlcall(sqlite3_finalize(statement));
3314 return JSEvaluateScript(CYGetJSContext(), CYJSString(value), NULL, NULL, 0, NULL);
3316 return CYMakeFunctor(context, reinterpret_cast<void (*)()>(CYCastSymbol(name)), value);
3319 // XXX: this is horrendously inefficient
3320 sig::Signature signature;
3321 sig::Parse(pool, &signature, value, &Structor_);
3323 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3324 return CYFromFFI(context, signature.elements[0].type, cif.rtype, CYCastSymbol(name));
3327 // XXX: implement case 3
3329 return CYMakeType(context, value);
3335 static bool stret(ffi_type *ffi_type) {
3336 return ffi_type->type == FFI_TYPE_STRUCT && (
3337 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
3338 struct_forward_array[ffi_type->size] != 0
3343 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3348 printf("%s\n", CYCastCString(context, arguments[0]));
3349 return CYJSUndefined(context);
3354 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
3358 _class = object_getClass(self);
3360 if (objc_method *method = class_getInstanceMethod(_class, _cmd))
3361 type = method_getTypeEncoding(method);
3365 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
3367 _throw(NSInvalidArgumentException, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3368 type = CYPoolCString(pool, [method _typeString]);
3373 objc_super super = {self, _class};
3374 void *arg0 = &super;
3380 sig::Signature signature;
3381 sig::Parse(pool, &signature, type, &Structor_);
3384 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3386 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSendSuper_stret) : reinterpret_cast<void (*)()>(&objc_msgSendSuper);
3387 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3391 static size_t Nonce_(0);
3393 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3395 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
3396 return CYCastJSValue(context, name);
3400 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3411 _throw(NSInvalidArgumentException, "too few arguments to objc_msgSend");
3413 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
3414 Super *internal(reinterpret_cast<Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3415 self = internal->GetValue();
3416 _class = internal->class_;;
3417 uninitialized = false;
3418 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
3419 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3420 self = internal->GetValue();
3422 uninitialized = internal->IsUninitialized();
3424 internal->value_ = nil;
3426 self = CYCastNSObject(pool, context, arguments[0]);
3428 uninitialized = false;
3432 return CYJSNull(context);
3434 _cmd = CYCastSEL(context, arguments[1]);
3437 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
3442 /* Hook: objc_registerClassPair {{{ */
3443 // XXX: replace this with associated objects
3445 MSHook(void, CYDealloc, id self, SEL sel) {
3446 CYInternal *internal;
3447 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
3448 if (internal != NULL)
3450 _CYDealloc(self, sel);
3453 MSHook(void, objc_registerClassPair, Class _class) {
3454 Class super(class_getSuperclass(_class));
3455 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
3456 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
3457 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
3460 _objc_registerClassPair(_class);
3463 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3466 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3468 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3469 if (value == NULL || !CYIsClass(value))
3470 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3471 Class _class((Class) value);
3472 $objc_registerClassPair(_class);
3473 return CYJSUndefined(context);
3479 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3480 JSGarbageCollect(context);
3481 return CYJSUndefined(context);
3485 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3486 JSValueRef setup[count + 2];
3489 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
3490 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
3493 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3495 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
3497 // XXX: handle Instance::Uninitialized?
3498 id self(CYCastNSObject(pool, context, _this));
3502 setup[1] = &internal->sel_;
3504 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3508 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3510 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
3511 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3515 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3518 _throw(NSInvalidArgumentException, "incorrect number of arguments to Super constructor");
3520 NSObject *self(CYCastNSObject(pool, context, arguments[0]));
3521 Class _class(CYCastClass(pool, context, arguments[1]));
3522 return Super::Make(context, self, _class);
3526 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3529 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector constructor");
3530 const char *name(CYCastCString(context, arguments[0]));
3531 return CYMakeSelector(context, sel_registerName(name));
3536 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3539 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3541 void *value(CYCastPointer<void *>(context, arguments[0]));
3542 const char *type(CYCastCString(context, arguments[1]));
3546 sig::Signature signature;
3547 sig::Parse(pool, &signature, type, &Structor_);
3549 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
3553 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3556 _throw(NSInvalidArgumentException, "incorrect number of arguments to Type constructor");
3557 const char *type(CYCastCString(context, arguments[0]));
3558 return CYMakeType(context, type);
3562 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3563 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3568 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3569 type.primitive = sig::pointer_P;
3570 type.data.data.size = 0;
3573 size_t index(CYGetIndex(pool, property));
3574 if (index == _not(size_t))
3576 type.primitive = sig::array_P;
3577 type.data.data.size = index;
3583 type.data.data.type = internal->type_;
3585 return CYMakeType(context, &type);
3589 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3590 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3594 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3595 sig::Type *type(internal->type_);
3596 ffi_type *ffi(internal->GetFFI());
3598 uint8_t value[ffi->size];
3600 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3601 return CYFromFFI(context, type, ffi, value);
3605 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3608 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3609 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3611 sig::Type *type(internal->type_);
3614 if (type->primitive != sig::array_P)
3617 size = type->data.data.size;
3618 type = type->data.data.type;
3621 void *value(malloc(internal->GetFFI()->size));
3622 return CYMakePointer(context, value, type, NULL, NULL);
3627 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3630 _throw(NSInvalidArgumentException, "incorrect number of arguments to Instance constructor");
3631 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3632 return Instance::Make(context, self);
3637 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3640 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3641 const char *type(CYCastCString(context, arguments[1]));
3642 return CYMakeFunctor(context, arguments[0], type);
3647 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3648 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3649 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3652 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3653 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3654 Type_privateData *typical(internal->GetType());
3659 if (typical == NULL) {
3663 type = typical->type_;
3664 ffi = typical->ffi_;
3667 return CYMakePointer(context, &internal->value_, type, ffi, object);
3671 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3672 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3675 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3679 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3680 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3683 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3684 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3686 sprintf(string, "%p", internal->value_);
3689 return CYCastJSValue(context, string);
3694 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3695 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3696 return Instance::Make(context, object_getClass(internal->GetValue()));
3699 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3700 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3701 id self(internal->GetValue());
3702 if (!CYIsClass(self))
3703 return CYJSUndefined(context);
3705 return CYGetClassPrototype(context, self);
3709 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3710 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3711 id self(internal->GetValue());
3712 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3713 return CYJSUndefined(context);
3714 return Messages::Make(context, self);
3717 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3718 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3721 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3725 return CYCastJSValue(context, CYJSString(CYCastNSCYON(internal->GetValue())));
3730 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3731 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3734 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3738 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3739 // XXX: check for support of cy$toJSON?
3740 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3745 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3746 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3749 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3753 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3758 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3759 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3762 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3766 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3767 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3770 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3771 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3772 const char *name(sel_getName(internal->GetValue()));
3776 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3781 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3784 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector.type");
3786 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3787 if (Class _class = CYCastClass(pool, context, arguments[0])) {
3788 SEL sel(internal->GetValue());
3789 if (objc_method *method = class_getInstanceMethod(_class, sel))
3790 if (const char *type = CYPoolTypeEncoding(pool, _class, sel, method))
3791 return CYCastJSValue(context, CYJSString(type));
3794 // XXX: do a lookup of some kind
3795 return CYJSNull(context);
3800 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3802 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3804 const char *type(sig::Unparse(pool, internal->type_));
3805 return CYCastJSValue(context, CYJSString(type));
3809 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3811 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3813 const char *type(sig::Unparse(pool, internal->type_));
3814 size_t size(strlen(type));
3815 char *cyon(new(pool) char[12 + size + 1]);
3816 memcpy(cyon, "new Type(\"", 10);
3817 cyon[12 + size] = '\0';
3818 cyon[12 + size - 2] = '"';
3819 cyon[12 + size - 1] = ')';
3820 memcpy(cyon + 10, type, size);
3821 return CYCastJSValue(context, CYJSString(cyon));
3825 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3826 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3830 static JSStaticValue Selector_staticValues[2] = {
3831 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3832 {NULL, NULL, NULL, 0}
3836 static JSStaticValue Pointer_staticValues[2] = {
3837 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3838 {NULL, NULL, NULL, 0}
3841 static JSStaticFunction Pointer_staticFunctions[4] = {
3842 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3843 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3844 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3848 static JSStaticFunction Struct_staticFunctions[2] = {
3849 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3853 static JSStaticFunction Functor_staticFunctions[4] = {
3854 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3855 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3856 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3861 static JSStaticValue Instance_staticValues[5] = {
3862 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3863 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3864 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3865 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3866 {NULL, NULL, NULL, 0}
3869 static JSStaticFunction Instance_staticFunctions[5] = {
3870 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3871 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3872 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3873 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3877 static JSStaticFunction Internal_staticFunctions[2] = {
3878 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3882 static JSStaticFunction Selector_staticFunctions[5] = {
3883 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3884 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3885 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3886 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3891 static JSStaticFunction Type_staticFunctions[4] = {
3892 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3893 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3894 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3898 void CYSetArgs(int argc, const char *argv[]) {
3899 JSContextRef context(CYGetJSContext());
3900 JSValueRef args[argc];
3901 for (int i(0); i != argc; ++i)
3902 args[i] = CYCastJSValue(context, argv[i]);
3903 JSValueRef exception(NULL);
3904 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3905 CYThrow(context, exception);
3906 CYSetProperty(context, System_, CYJSString("args"), array);
3909 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3910 return JSContextGetGlobalObject(context);
3913 const char *CYExecute(apr_pool_t *pool, const char *code) {
3914 JSContextRef context(CYGetJSContext());
3915 JSValueRef exception(NULL), result;
3921 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3922 } catch (const char *error) {
3926 if (exception != NULL) { error:
3931 if (JSValueIsUndefined(context, result))
3935 json = CYPoolCCYON(pool, context, result, &exception);
3936 } catch (const char *error) {
3940 if (exception != NULL)
3944 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3948 static apr_pool_t *Pool_;
3950 apr_pool_t *CYGetGlobalPool() {
3955 _aprcall(apr_initialize());
3956 _aprcall(apr_pool_create(&Pool_, NULL));
3958 _sqlcall(sqlite3_open("/usr/lib/libcycript.db", &Bridge_));
3961 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3962 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3965 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3966 NSCFType_ = objc_getClass("NSCFType");
3969 NSArray_ = objc_getClass("NSArray");
3970 NSDictionary_ = objc_getClass("NSDictonary");
3971 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3972 NSZombie_ = objc_getClass("_NSZombie_");
3973 Object_ = objc_getClass("Object");
3977 JSGlobalContextRef CYGetJSContext() {
3978 if (Context_ == NULL) {
3979 JSClassDefinition definition;
3981 definition = kJSClassDefinitionEmpty;
3982 definition.className = "Functor";
3983 definition.staticFunctions = Functor_staticFunctions;
3984 definition.callAsFunction = &Functor_callAsFunction;
3985 definition.finalize = &Finalize;
3986 Functor_ = JSClassCreate(&definition);
3988 definition = kJSClassDefinitionEmpty;
3989 definition.className = "Pointer";
3990 definition.staticValues = Pointer_staticValues;
3991 definition.staticFunctions = Pointer_staticFunctions;
3992 definition.getProperty = &Pointer_getProperty;
3993 definition.setProperty = &Pointer_setProperty;
3994 definition.finalize = &Finalize;
3995 Pointer_ = JSClassCreate(&definition);
3997 definition = kJSClassDefinitionEmpty;
3998 definition.className = "Struct";
3999 definition.staticFunctions = Struct_staticFunctions;
4000 definition.getProperty = &Struct_getProperty;
4001 definition.setProperty = &Struct_setProperty;
4002 definition.getPropertyNames = &Struct_getPropertyNames;
4003 definition.finalize = &Finalize;
4004 Struct_ = JSClassCreate(&definition);
4006 definition = kJSClassDefinitionEmpty;
4007 definition.className = "Type";
4008 definition.staticFunctions = Type_staticFunctions;
4009 definition.getProperty = &Type_getProperty;
4010 definition.callAsFunction = &Type_callAsFunction;
4011 definition.callAsConstructor = &Type_callAsConstructor;
4012 definition.finalize = &Finalize;
4013 Type_privateData::Class_ = JSClassCreate(&definition);
4015 definition = kJSClassDefinitionEmpty;
4016 definition.className = "Runtime";
4017 definition.getProperty = &Runtime_getProperty;
4018 Runtime_ = JSClassCreate(&definition);
4020 definition = kJSClassDefinitionEmpty;
4021 //definition.getProperty = &Global_getProperty;
4022 JSClassRef Global(JSClassCreate(&definition));
4024 JSGlobalContextRef context(JSGlobalContextCreate(Global));
4026 JSObjectRef global(CYGetGlobalObject(context));
4028 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
4030 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
4031 JSValueProtect(context, Array_);
4033 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
4034 JSValueProtect(context, Function_);
4036 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
4037 JSValueProtect(context, String_);
4039 length_ = JSStringCreateWithUTF8CString("length");
4040 message_ = JSStringCreateWithUTF8CString("message");
4041 name_ = JSStringCreateWithUTF8CString("name");
4042 prototype_ = JSStringCreateWithUTF8CString("prototype");
4043 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
4044 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
4046 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
4047 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
4048 JSValueProtect(context, Object_prototype_);
4050 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
4051 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
4052 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
4053 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
4055 CYSetProperty(context, Array_prototype_, toCYON_, JSObjectMakeFunctionWithCallback(context, toCYON_, &Array_callAsFunction_toCYON), kJSPropertyAttributeDontEnum);
4057 JSValueProtect(context, Array_prototype_);
4058 JSValueProtect(context, Array_pop_);
4059 JSValueProtect(context, Array_push_);
4060 JSValueProtect(context, Array_splice_);
4062 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
4064 JSValueRef function(CYGetProperty(context, Function_, prototype_));
4066 /* Objective-C Classes {{{ */
4068 definition = kJSClassDefinitionEmpty;
4069 definition.className = "Instance";
4070 definition.staticValues = Instance_staticValues;
4071 definition.staticFunctions = Instance_staticFunctions;
4072 definition.hasProperty = &Instance_hasProperty;
4073 definition.getProperty = &Instance_getProperty;
4074 definition.setProperty = &Instance_setProperty;
4075 definition.deleteProperty = &Instance_deleteProperty;
4076 definition.getPropertyNames = &Instance_getPropertyNames;
4077 definition.callAsConstructor = &Instance_callAsConstructor;
4078 definition.hasInstance = &Instance_hasInstance;
4079 definition.finalize = &Finalize;
4080 Instance_ = JSClassCreate(&definition);
4082 definition = kJSClassDefinitionEmpty;
4083 definition.className = "Internal";
4084 definition.staticFunctions = Internal_staticFunctions;
4085 definition.hasProperty = &Internal_hasProperty;
4086 definition.getProperty = &Internal_getProperty;
4087 definition.setProperty = &Internal_setProperty;
4088 definition.getPropertyNames = &Internal_getPropertyNames;
4089 definition.finalize = &Finalize;
4090 Internal_ = JSClassCreate(&definition);
4092 definition = kJSClassDefinitionEmpty;
4093 definition.className = "Message";
4094 definition.staticFunctions = Functor_staticFunctions;
4095 definition.callAsFunction = &Message_callAsFunction;
4096 definition.finalize = &Finalize;
4097 Message_ = JSClassCreate(&definition);
4099 definition = kJSClassDefinitionEmpty;
4100 definition.className = "Messages";
4101 definition.hasProperty = &Messages_hasProperty;
4102 definition.getProperty = &Messages_getProperty;
4103 definition.setProperty = &Messages_setProperty;
4105 definition.deleteProperty = &Messages_deleteProperty;
4107 definition.getPropertyNames = &Messages_getPropertyNames;
4108 definition.finalize = &Finalize;
4109 Messages_ = JSClassCreate(&definition);
4111 definition = kJSClassDefinitionEmpty;
4112 definition.className = "Selector";
4113 definition.staticValues = Selector_staticValues;
4114 definition.staticFunctions = Selector_staticFunctions;
4115 definition.callAsFunction = &Selector_callAsFunction;
4116 definition.finalize = &Finalize;
4117 Selector_ = JSClassCreate(&definition);
4119 definition = kJSClassDefinitionEmpty;
4120 definition.className = "Super";
4121 definition.staticFunctions = Internal_staticFunctions;
4122 definition.finalize = &Finalize;
4123 Super_ = JSClassCreate(&definition);
4125 definition = kJSClassDefinitionEmpty;
4126 definition.className = "ObjectiveC::Classes";
4127 definition.getProperty = &ObjectiveC_Classes_getProperty;
4128 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
4129 ObjectiveC_Classes_ = JSClassCreate(&definition);
4131 definition = kJSClassDefinitionEmpty;
4132 definition.className = "ObjectiveC::Images";
4133 definition.getProperty = &ObjectiveC_Images_getProperty;
4134 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
4135 ObjectiveC_Images_ = JSClassCreate(&definition);
4137 definition = kJSClassDefinitionEmpty;
4138 definition.className = "ObjectiveC::Image::Classes";
4139 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
4140 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
4141 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
4143 definition = kJSClassDefinitionEmpty;
4144 definition.className = "ObjectiveC::Protocols";
4145 definition.getProperty = &ObjectiveC_Protocols_getProperty;
4146 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
4147 ObjectiveC_Protocols_ = JSClassCreate(&definition);
4149 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
4150 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC);
4152 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
4153 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
4154 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
4156 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
4157 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
4158 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
4159 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
4161 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
4162 JSValueProtect(context, Instance_prototype_);
4164 CYSetProperty(context, global, CYJSString("Instance"), Instance);
4165 CYSetProperty(context, global, CYJSString("Selector"), Selector);
4166 CYSetProperty(context, global, CYJSString("Super"), Super);
4168 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
4169 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
4171 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
4172 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
4176 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
4178 CYSetProperty(context, global, CYJSString("Functor"), Functor);
4179 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
4180 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
4183 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
4188 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
4192 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
4193 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
4194 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
4196 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
4198 System_ = JSObjectMake(context, NULL, NULL);
4199 JSValueProtect(context, System_);
4201 CYSetProperty(context, global, CYJSString("system"), System_);
4202 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
4203 //CYSetProperty(context, System_, CYJSString("global"), global);
4205 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
4207 Result_ = JSStringCreateWithUTF8CString("_");