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 "cycript.hpp"
 
  43 #include "sig/parse.hpp"
 
  44 #include "sig/ffi_type.hpp"
 
  46 #include "Pooling.hpp"
 
  50 #include <CoreFoundation/CoreFoundation.h>
 
  51 #include <CoreFoundation/CFLogUtilities.h>
 
  52 #include <JavaScriptCore/JSStringRefCF.h>
 
  53 #include <WebKit/WebScriptObject.h>
 
  56 #include <Foundation/Foundation.h>
 
  61 #include <ext/stdio_filebuf.h>
 
  69 #include "Cycript.tab.hh"
 
  71 #include <apr_thread_proc.h>
 
  76 #define _assert(test) do { \
 
  78         @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
 
  81 #define _trace() do { \
 
  82     fprintf(stderr, "_trace():%u\n", __LINE__); \
 
  87     NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
 
  89 #define CYPoolCatch(value) \
 
  90     @catch (NSException *error) { \
 
  91         _saved = [error retain]; \
 
  97             [_saved autorelease]; \
 
 101 void CYThrow(JSContextRef context, JSValueRef value);
 
 103 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception);
 
 104 JSStringRef CYCopyJSString(const char *value);
 
 106 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value);
 
 108 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)());
 
 109 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
 
 111 /* JavaScript Properties {{{ */
 
 112 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
 
 113     JSValueRef exception(NULL);
 
 114     JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
 
 115     CYThrow(context, exception);
 
 119 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
 
 120     JSValueRef exception(NULL);
 
 121     JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
 
 122     CYThrow(context, exception);
 
 126 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
 
 127     JSValueRef exception(NULL);
 
 128     JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
 
 129     CYThrow(context, exception);
 
 132 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
 
 133     JSValueRef exception(NULL);
 
 134     JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
 
 135     CYThrow(context, exception);
 
 138 /* JavaScript Strings {{{ */
 
 139 JSStringRef CYCopyJSString(const char *value) {
 
 140     return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
 
 143 JSStringRef CYCopyJSString(JSStringRef value) {
 
 144     return value == NULL ? NULL : JSStringRetain(value);
 
 147 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
 
 148     if (JSValueIsNull(context, value))
 
 150     JSValueRef exception(NULL);
 
 151     JSStringRef string(JSValueToStringCopy(context, value, &exception));
 
 152     CYThrow(context, exception);
 
 162             JSStringRelease(string_);
 
 166     CYJSString(const CYJSString &rhs) :
 
 167         string_(CYCopyJSString(rhs.string_))
 
 171     template <typename Arg0_>
 
 172     CYJSString(Arg0_ arg0) :
 
 173         string_(CYCopyJSString(arg0))
 
 177     template <typename Arg0_, typename Arg1_>
 
 178     CYJSString(Arg0_ arg0, Arg1_ arg1) :
 
 179         string_(CYCopyJSString(arg0, arg1))
 
 183     CYJSString &operator =(const CYJSString &rhs) {
 
 185         string_ = CYCopyJSString(rhs.string_);
 
 198     operator JSStringRef() const {
 
 204 // XXX: this macro is unhygenic
 
 205 #define CYCastCString_(string) ({ \
 
 207     if (string == NULL) \
 
 210         size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
 
 211         utf8 = reinterpret_cast<char *>(alloca(size)); \
 
 212         JSStringGetUTF8CString(string, utf8, size); \
 
 217 // XXX: this macro is unhygenic
 
 218 #define CYCastCString(context, value) ({ \
 
 222     else if (JSStringRef string = CYCopyJSString(context, value)) { \
 
 223         utf8 = CYCastCString_(string); \
 
 224         JSStringRelease(string); \
 
 230 /* Objective-C Strings {{{ */
 
 231 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
 
 233         return [value UTF8String];
 
 235         size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
 
 236         char *string(new(pool) char[size]);
 
 237         if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
 
 238             @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
 
 243 JSStringRef CYCopyJSString_(NSString *value) {
 
 245     return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
 
 248     return CYCopyJSString(CYPoolCString(pool, value));
 
 252 JSStringRef CYCopyJSString(id value) {
 
 255     // XXX: this definition scares me; is anyone using this?!
 
 256     NSString *string([value description]);
 
 257     return CYCopyJSString_(string);
 
 261 CFStringRef CYCopyCFString(JSStringRef value) {
 
 262     return JSStringCopyCFString(kCFAllocatorDefault, value);
 
 265 CFStringRef CYCopyCFString(const char *value) {
 
 266     return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
 
 269 template <typename Type_>
 
 270 NSString *CYCopyNSString(Type_ value) {
 
 271     return (NSString *) CYCopyCFString(value);
 
 274 NSString *CYCopyNSString(const char *value) {
 
 275     return [NSString stringWithUTF8String:value];
 
 278 NSString *CYCopyNSString(JSStringRef value) {
 
 279     return CYCopyNSString(CYCastCString_(value));
 
 283 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
 
 284     return CYCopyNSString(CYJSString(context, value));
 
 288 static JSGlobalContextRef Context_;
 
 289 static JSObjectRef System_;
 
 290 static JSObjectRef ObjectiveC_;
 
 292 static JSClassRef Functor_;
 
 293 static JSClassRef Instance_;
 
 294 static JSClassRef Internal_;
 
 295 static JSClassRef Message_;
 
 296 static JSClassRef Messages_;
 
 297 static JSClassRef NSArrayPrototype_;
 
 298 static JSClassRef Pointer_;
 
 299 static JSClassRef Runtime_;
 
 300 static JSClassRef Selector_;
 
 301 static JSClassRef Struct_;
 
 303 static JSClassRef ObjectiveC_Classes_;
 
 304 static JSClassRef ObjectiveC_Image_Classes_;
 
 305 static JSClassRef ObjectiveC_Images_;
 
 306 static JSClassRef ObjectiveC_Protocols_;
 
 308 static JSObjectRef Array_;
 
 309 static JSObjectRef Function_;
 
 310 static JSObjectRef String_;
 
 312 static JSStringRef Result_;
 
 314 static JSStringRef length_;
 
 315 static JSStringRef message_;
 
 316 static JSStringRef name_;
 
 317 static JSStringRef prototype_;
 
 318 static JSStringRef toCYON_;
 
 319 static JSStringRef toJSON_;
 
 321 static JSObjectRef Instance_prototype_;
 
 322 static JSObjectRef Object_prototype_;
 
 324 static JSObjectRef Array_prototype_;
 
 325 static JSObjectRef Array_pop_;
 
 326 static JSObjectRef Array_push_;
 
 327 static JSObjectRef Array_splice_;
 
 330 static Class NSCFBoolean_;
 
 331 static Class NSCFType_;
 
 334 static Class NSArray_;
 
 335 static Class NSDictionary_;
 
 336 static Class NSMessageBuilder_;
 
 337 static Class NSZombie_;
 
 338 static Class Object_;
 
 340 static NSArray *Bridge_;
 
 342 static void Finalize(JSObjectRef object) {
 
 343     delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
 
 346 class Type_privateData;
 
 356     CYValue(const void *value) :
 
 357         value_(const_cast<void *>(value))
 
 361     CYValue(const CYValue &rhs) :
 
 366     virtual Type_privateData *GetType() const {
 
 371 struct Selector_privateData :
 
 374     Selector_privateData(SEL value) :
 
 379     SEL GetValue() const {
 
 380         return reinterpret_cast<SEL>(value_);
 
 383     virtual Type_privateData *GetType() const;
 
 386 // XXX: trick this out with associated objects!
 
 387 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
 
 389         return Instance_prototype_;
 
 391     // XXX: I need to think through multi-context
 
 392     typedef std::map<id, JSValueRef> CacheMap;
 
 393     static CacheMap cache_;
 
 395     JSValueRef &value(cache_[self]);
 
 399     JSClassRef _class(NULL);
 
 400     JSValueRef prototype;
 
 402     if (self == NSArray_)
 
 403         prototype = Array_prototype_;
 
 404     else if (self == NSDictionary_)
 
 405         prototype = Object_prototype_;
 
 407         prototype = CYGetClassPrototype(context, class_getSuperclass(self));
 
 409     JSObjectRef object(JSObjectMake(context, _class, NULL));
 
 410     JSObjectSetPrototype(context, object, prototype);
 
 412     JSValueProtect(context, object);
 
 422         Transient     = (1 << 0),
 
 423         Uninitialized = (1 << 1),
 
 428     Instance(id value, Flags flags) :
 
 434     virtual ~Instance() {
 
 435         if ((flags_ & Transient) == 0)
 
 436             // XXX: does this handle background threads correctly?
 
 437             // XXX: this simply does not work on the console because I'm stupid
 
 438             [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
 
 441     static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
 
 442         JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
 
 443         JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object == nil ? nil : object_getClass(object)));
 
 447     id GetValue() const {
 
 448         return reinterpret_cast<id>(value_);
 
 451     bool IsUninitialized() const {
 
 452         return (flags_ & Uninitialized) != 0;
 
 455     virtual Type_privateData *GetType() const;
 
 461     Messages(Class value) :
 
 466     static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
 
 467         JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
 
 468         if (_class == NSArray_)
 
 470         if (Class super = class_getSuperclass(_class))
 
 471             JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
 
 473             JSObjectSetPrototype(context, value, Array_prototype_);*/
 
 477     Class GetValue() const {
 
 478         return reinterpret_cast<Class>(value_);
 
 486     JSContextRef context_;
 
 490     CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
 
 495         JSValueProtect(context_, owner_);
 
 499         JSValueUnprotect(context_, owner_);
 
 502     JSObjectRef GetOwner() const {
 
 510     Internal(id value, JSContextRef context, JSObjectRef owner) :
 
 511         CYOwned(value, context, owner)
 
 515     static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
 
 516         return JSObjectMake(context, Internal_, new Internal(object, context, owner));
 
 519     id GetValue() const {
 
 520         return reinterpret_cast<id>(value_);
 
 526 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
 
 528 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
 
 529     lhs.name = apr_pstrdup(pool, rhs.name);
 
 530     if (rhs.type == NULL)
 
 533         lhs.type = new(pool) Type;
 
 534         Copy(pool, *lhs.type, *rhs.type);
 
 536     lhs.offset = rhs.offset;
 
 539 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
 
 540     size_t count(rhs.count);
 
 542     lhs.elements = new(pool) Element[count];
 
 543     for (size_t index(0); index != count; ++index)
 
 544         Copy(pool, lhs.elements[index], rhs.elements[index]);
 
 547 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
 
 548     lhs.primitive = rhs.primitive;
 
 549     lhs.name = apr_pstrdup(pool, rhs.name);
 
 550     lhs.flags = rhs.flags;
 
 552     if (sig::IsAggregate(rhs.primitive))
 
 553         Copy(pool, lhs.data.signature, rhs.data.signature);
 
 555         sig::Type *&lht(lhs.data.data.type);
 
 556         sig::Type *&rht(rhs.data.data.type);
 
 561             lht = new(pool) Type;
 
 562             Copy(pool, *lht, *rht);
 
 565         lhs.data.data.size = rhs.data.data.size;
 
 569 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
 
 571     lhs.alignment = rhs.alignment;
 
 573     if (rhs.elements == NULL)
 
 577         while (rhs.elements[count] != NULL)
 
 580         lhs.elements = new(pool) ffi_type *[count + 1];
 
 581         lhs.elements[count] = NULL;
 
 583         for (size_t index(0); index != count; ++index) {
 
 584             // XXX: if these are libffi native then you can just take them
 
 585             ffi_type *ffi(new(pool) ffi_type);
 
 586             lhs.elements[index] = ffi;
 
 587             sig::Copy(pool, *ffi, *rhs.elements[index]);
 
 594 struct CStringMapLess :
 
 595     std::binary_function<const char *, const char *, bool>
 
 597     _finline bool operator ()(const char *lhs, const char *rhs) const {
 
 598         return strcmp(lhs, rhs) < 0;
 
 602 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
 
 607         if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
 
 608             switch ([[entry objectAtIndex:0] intValue]) {
 
 610                     sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
 
 614                     sig::Signature signature;
 
 615                     sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
 
 616                     type = signature.elements[0].type;
 
 622 struct Type_privateData :
 
 625     static Type_privateData *Object;
 
 626     static Type_privateData *Selector;
 
 628     static JSClassRef Class_;
 
 633     void Set(sig::Type *type) {
 
 634         type_ = new(pool_) sig::Type;
 
 635         sig::Copy(pool_, *type_, *type);
 
 638     Type_privateData(apr_pool_t *pool, const char *type) :
 
 644         sig::Signature signature;
 
 645         sig::Parse(pool_, &signature, type, &Structor_);
 
 646         type_ = signature.elements[0].type;
 
 649     Type_privateData(sig::Type *type) :
 
 656     Type_privateData(sig::Type *type, ffi_type *ffi) {
 
 657         ffi_ = new(pool_) ffi_type;
 
 658         sig::Copy(pool_, *ffi_, *ffi);
 
 664             ffi_ = new(pool_) ffi_type;
 
 666             sig::Element element;
 
 668             element.type = type_;
 
 671             sig::Signature signature;
 
 672             signature.elements = &element;
 
 676             sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
 
 684 JSClassRef Type_privateData::Class_;
 
 685 Type_privateData *Type_privateData::Object;
 
 686 Type_privateData *Type_privateData::Selector;
 
 688 Type_privateData *Instance::GetType() const {
 
 689     return Type_privateData::Object;
 
 692 Type_privateData *Selector_privateData::GetType() const {
 
 693     return Type_privateData::Selector;
 
 699     Type_privateData *type_;
 
 701     Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
 
 702         CYOwned(value, context, owner),
 
 703         type_(new(pool_) Type_privateData(type))
 
 708 struct Struct_privateData :
 
 711     Type_privateData *type_;
 
 713     Struct_privateData(JSContextRef context, JSObjectRef owner) :
 
 714         CYOwned(NULL, context, owner)
 
 719 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
 
 720 static TypeMap Types_;
 
 722 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
 
 723     Struct_privateData *internal(new Struct_privateData(context, owner));
 
 724     apr_pool_t *pool(internal->pool_);
 
 725     Type_privateData *typical(new(pool) Type_privateData(type, ffi));
 
 726     internal->type_ = typical;
 
 729         internal->value_ = data;
 
 731         size_t size(typical->GetFFI()->size);
 
 732         void *copy(apr_palloc(internal->pool_, size));
 
 733         memcpy(copy, data, size);
 
 734         internal->value_ = copy;
 
 737     return JSObjectMake(context, Struct_, internal);
 
 740 struct Functor_privateData :
 
 743     sig::Signature signature_;
 
 747     Functor_privateData(const char *type, void (*value)()) :
 
 748         CYValue(reinterpret_cast<void *>(value))
 
 750         sig::Parse(pool_, &signature_, type, &Structor_);
 
 751         sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
 
 754     void (*GetValue())() const {
 
 755         return reinterpret_cast<void (*)()>(value_);
 
 759 struct Closure_privateData :
 
 762     JSContextRef context_;
 
 763     JSObjectRef function_;
 
 765     Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
 
 766         Functor_privateData(type, NULL),
 
 770         JSValueProtect(context_, function_);
 
 773     virtual ~Closure_privateData() {
 
 774         JSValueUnprotect(context_, function_);
 
 778 struct Message_privateData :
 
 783     Message_privateData(SEL sel, const char *type, IMP value = NULL) :
 
 784         Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
 
 790 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
 
 791     Instance::Flags flags;
 
 794         flags = Instance::Transient;
 
 796         flags = Instance::None;
 
 797         object = [object retain];
 
 800     return Instance::Make(context, object, flags);
 
 803 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
 
 804     return JSValueMakeBoolean(context, value);
 
 807 JSValueRef CYCastJSValue(JSContextRef context, double value) {
 
 808     return JSValueMakeNumber(context, value);
 
 811 #define CYCastJSValue_(Type_) \
 
 812     JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
 
 813         return JSValueMakeNumber(context, static_cast<double>(value)); \
 
 817 CYCastJSValue_(unsigned int)
 
 818 CYCastJSValue_(long int)
 
 819 CYCastJSValue_(long unsigned int)
 
 820 CYCastJSValue_(long long int)
 
 821 CYCastJSValue_(long long unsigned int)
 
 823 JSValueRef CYJSUndefined(JSContextRef context) {
 
 824     return JSValueMakeUndefined(context);
 
 827 size_t CYGetIndex(const char *value) {
 
 828     if (value[0] != '0') {
 
 830         size_t index(strtoul(value, &end, 10));
 
 831         if (value + strlen(value) == end)
 
 833     } else if (value[1] == '\0')
 
 839 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value);
 
 841 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
 
 842     return CYGetIndex(CYPoolCString(pool, value));
 
 845 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
 
 846     return CYGetIndex(CYPoolCString(pool, value));
 
 849 bool CYGetOffset(const char *value, ssize_t &index) {
 
 850     if (value[0] != '0') {
 
 852         index = strtol(value, &end, 10);
 
 853         if (value + strlen(value) == end)
 
 855     } else if (value[1] == '\0') {
 
 863 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
 
 864     return CYGetOffset(CYPoolCString(pool, value), index);
 
 867 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
 
 869 @interface NSMethodSignature (Cycript)
 
 870 - (NSString *) _typeString;
 
 873 @interface NSObject (Cycript)
 
 875 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 
 876 - (JSType) cy$JSType;
 
 878 - (NSObject *) cy$toJSON:(NSString *)key;
 
 879 - (NSString *) cy$toCYON;
 
 880 - (NSString *) cy$toKey;
 
 882 - (bool) cy$hasProperty:(NSString *)name;
 
 883 - (NSObject *) cy$getProperty:(NSString *)name;
 
 884 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
 
 885 - (bool) cy$deleteProperty:(NSString *)name;
 
 890 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 
 893 @interface NSString (Cycript)
 
 894 - (void *) cy$symbol;
 
 898 struct PropertyAttributes {
 
 903     const char *variable;
 
 916     PropertyAttributes(objc_property_t property) :
 
 928         name = property_getName(property);
 
 929         const char *attributes(property_getAttributes(property));
 
 931         for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
 
 933                 case 'R': readonly = true; break;
 
 934                 case 'C': copy = true; break;
 
 935                 case '&': retain = true; break;
 
 936                 case 'N': nonatomic = true; break;
 
 937                 case 'G': getter_ = token + 1; break;
 
 938                 case 'S': setter_ = token + 1; break;
 
 939                 case 'V': variable = token + 1; break;
 
 943         /*if (variable == NULL) {
 
 944             variable = property_getName(property);
 
 945             size_t size(strlen(variable));
 
 946             char *name(new(pool_) char[size + 2]);
 
 948             memcpy(name + 1, variable, size);
 
 949             name[size + 1] = '\0';
 
 954     const char *Getter() {
 
 956             getter_ = apr_pstrdup(pool_, name);
 
 960     const char *Setter() {
 
 961         if (setter_ == NULL && !readonly) {
 
 962             size_t length(strlen(name));
 
 964             char *temp(new(pool_) char[length + 5]);
 
 970                 temp[3] = toupper(name[0]);
 
 971                 memcpy(temp + 4, name + 1, length - 1);
 
 974             temp[length + 3] = ':';
 
 975             temp[length + 4] = '\0';
 
 986 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
 
 987     return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
 
 992 @interface CYWebUndefined : NSObject {
 
 995 + (CYWebUndefined *) undefined;
 
 999 @implementation CYWebUndefined
 
1001 + (CYWebUndefined *) undefined {
 
1002     static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
 
1008 #define WebUndefined CYWebUndefined
 
1011 /* Bridge: NSArray {{{ */
 
1012 @implementation NSArray (Cycript)
 
1014 - (NSString *) cy$toCYON {
 
1015     NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
 
1016     [json appendString:@"["];
 
1020     for (id object in self) {
 
1023     for (size_t index(0), count([self count]); index != count; ++index) {
 
1024         object = [self objectAtIndex:index];
 
1027             [json appendString:@","];
 
1030         if (object == nil || [object cy$JSType] != kJSTypeUndefined)
 
1031             [json appendString:CYPoolNSCYON(NULL, object)];
 
1033             [json appendString:@","];
 
1038     [json appendString:@"]"];
 
1042 - (bool) cy$hasProperty:(NSString *)name {
 
1043     if ([name isEqualToString:@"length"])
 
1046     size_t index(CYGetIndex(NULL, name));
 
1047     if (index == _not(size_t) || index >= [self count])
 
1048         return [super cy$hasProperty:name];
 
1053 - (NSObject *) cy$getProperty:(NSString *)name {
 
1054     if ([name isEqualToString:@"length"]) {
 
1055         NSUInteger count([self count]);
 
1057         return [NSNumber numberWithUnsignedInteger:count];
 
1059         return [NSNumber numberWithUnsignedInt:count];
 
1063     size_t index(CYGetIndex(NULL, name));
 
1064     if (index == _not(size_t) || index >= [self count])
 
1065         return [super cy$getProperty:name];
 
1067         return [self objectAtIndex:index];
 
1072 /* Bridge: NSDictionary {{{ */
 
1073 @implementation NSDictionary (Cycript)
 
1075 - (NSString *) cy$toCYON {
 
1076     NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
 
1077     [json appendString:@"{"];
 
1081     for (id key in self) {
 
1083     NSEnumerator *keys([self keyEnumerator]);
 
1084     while (id key = [keys nextObject]) {
 
1087             [json appendString:@","];
 
1090         [json appendString:[key cy$toKey]];
 
1091         [json appendString:@":"];
 
1092         NSObject *object([self objectForKey:key]);
 
1093         [json appendString:CYPoolNSCYON(NULL, object)];
 
1096     [json appendString:@"}"];
 
1100 - (bool) cy$hasProperty:(NSString *)name {
 
1101     return [self objectForKey:name] != nil;
 
1104 - (NSObject *) cy$getProperty:(NSString *)name {
 
1105     return [self objectForKey:name];
 
1110 /* Bridge: NSMutableArray {{{ */
 
1111 @implementation NSMutableArray (Cycript)
 
1113 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
1114     if ([name isEqualToString:@"length"]) {
 
1115         // XXX: is this not intelligent?
 
1116         NSNumber *number(reinterpret_cast<NSNumber *>(value));
 
1118         NSUInteger size([number unsignedIntegerValue]);
 
1120         NSUInteger size([number unsignedIntValue]);
 
1122         NSUInteger count([self count]);
 
1124             [self removeObjectsInRange:NSMakeRange(size, count - size)];
 
1125         else if (size != count) {
 
1126             WebUndefined *undefined([WebUndefined undefined]);
 
1127             for (size_t i(count); i != size; ++i)
 
1128                 [self addObject:undefined];
 
1133     size_t index(CYGetIndex(NULL, name));
 
1134     if (index == _not(size_t))
 
1135         return [super cy$setProperty:name to:value];
 
1137     id object(value ?: [NSNull null]);
 
1139     size_t count([self count]);
 
1141         [self replaceObjectAtIndex:index withObject:object];
 
1143         if (index != count) {
 
1144             WebUndefined *undefined([WebUndefined undefined]);
 
1145             for (size_t i(count); i != index; ++i)
 
1146                 [self addObject:undefined];
 
1149         [self addObject:object];
 
1155 - (bool) cy$deleteProperty:(NSString *)name {
 
1156     size_t index(CYGetIndex(NULL, name));
 
1157     if (index == _not(size_t) || index >= [self count])
 
1158         return [super cy$deleteProperty:name];
 
1159     [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
 
1165 /* Bridge: NSMutableDictionary {{{ */
 
1166 @implementation NSMutableDictionary (Cycript)
 
1168 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
1169     [self setObject:(value ?: [NSNull null]) forKey:name];
 
1173 - (bool) cy$deleteProperty:(NSString *)name {
 
1174     if ([self objectForKey:name] == nil)
 
1177         [self removeObjectForKey:name];
 
1184 /* Bridge: NSNumber {{{ */
 
1185 @implementation NSNumber (Cycript)
 
1187 - (JSType) cy$JSType {
 
1189     // XXX: this just seems stupid
 
1190     if ([self class] == NSCFBoolean_)
 
1191         return kJSTypeBoolean;
 
1193     return kJSTypeNumber;
 
1196 - (NSObject *) cy$toJSON:(NSString *)key {
 
1200 - (NSString *) cy$toCYON {
 
1201     return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
 
1204 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
1205     return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
 
1210 /* Bridge: NSNull {{{ */
 
1211 @implementation NSNull (Cycript)
 
1213 - (JSType) cy$JSType {
 
1217 - (NSObject *) cy$toJSON:(NSString *)key {
 
1221 - (NSString *) cy$toCYON {
 
1227 /* Bridge: NSObject {{{ */
 
1228 @implementation NSObject (Cycript)
 
1230 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
1231     return CYMakeInstance(context, self, false);
 
1234 - (JSType) cy$JSType {
 
1235     return kJSTypeObject;
 
1238 - (NSObject *) cy$toJSON:(NSString *)key {
 
1239     return [self description];
 
1242 - (NSString *) cy$toCYON {
 
1243     return [[self cy$toJSON:@""] cy$toCYON];
 
1246 - (NSString *) cy$toKey {
 
1247     return [self cy$toCYON];
 
1250 - (bool) cy$hasProperty:(NSString *)name {
 
1254 - (NSObject *) cy$getProperty:(NSString *)name {
 
1258 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
1262 - (bool) cy$deleteProperty:(NSString *)name {
 
1268 /* Bridge: NSProxy {{{ */
 
1269 @implementation NSProxy (Cycript)
 
1271 - (NSObject *) cy$toJSON:(NSString *)key {
 
1272     return [self description];
 
1275 - (NSString *) cy$toCYON {
 
1276     return [[self cy$toJSON:@""] cy$toCYON];
 
1281 /* Bridge: NSString {{{ */
 
1282 @implementation NSString (Cycript)
 
1284 - (JSType) cy$JSType {
 
1285     return kJSTypeString;
 
1288 - (NSObject *) cy$toJSON:(NSString *)key {
 
1292 - (NSString *) cy$toCYON {
 
1293     // XXX: this should use the better code from Output.cpp
 
1295     NSMutableString *json([self mutableCopy]);
 
1297     [json replaceOccurrencesOfString:@"\\" withString:@"\\\\" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
 
1298     [json replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
 
1299     [json replaceOccurrencesOfString:@"\t" withString:@"\\t" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
 
1300     [json replaceOccurrencesOfString:@"\r" withString:@"\\r" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
 
1301     [json replaceOccurrencesOfString:@"\n" withString:@"\\n" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
 
1303     [json appendString:@"\""];
 
1304     [json insertString:@"\"" atIndex:0];
 
1309 - (NSString *) cy$toKey {
 
1310     const char *value([self UTF8String]);
 
1311     size_t size(strlen(value));
 
1316     if (DigitRange_[value[0]]) {
 
1317         size_t index(CYGetIndex(NULL, self));
 
1318         if (index == _not(size_t))
 
1321         if (!WordStartRange_[value[0]])
 
1323         for (size_t i(1); i != size; ++i)
 
1324             if (!WordEndRange_[value[i]])
 
1331     return [self cy$toCYON];
 
1334 - (void *) cy$symbol {
 
1336     return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
 
1341 /* Bridge: WebUndefined {{{ */
 
1342 @implementation WebUndefined (Cycript)
 
1344 - (JSType) cy$JSType {
 
1345     return kJSTypeUndefined;
 
1348 - (NSObject *) cy$toJSON:(NSString *)key {
 
1352 - (NSString *) cy$toCYON {
 
1353     return @"undefined";
 
1356 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
1357     return CYJSUndefined(context);
 
1363 /* Bridge: CYJSObject {{{ */
 
1364 @interface CYJSObject : NSMutableDictionary {
 
1365     JSObjectRef object_;
 
1366     JSContextRef context_;
 
1369 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
 
1371 - (NSObject *) cy$toJSON:(NSString *)key;
 
1373 - (NSUInteger) count;
 
1374 - (id) objectForKey:(id)key;
 
1375 - (NSEnumerator *) keyEnumerator;
 
1376 - (void) setObject:(id)object forKey:(id)key;
 
1377 - (void) removeObjectForKey:(id)key;
 
1381 /* Bridge: CYJSArray {{{ */
 
1382 @interface CYJSArray : NSMutableArray {
 
1383     JSObjectRef object_;
 
1384     JSContextRef context_;
 
1387 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
 
1389 - (NSUInteger) count;
 
1390 - (id) objectAtIndex:(NSUInteger)index;
 
1392 - (void) addObject:(id)anObject;
 
1393 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
 
1394 - (void) removeLastObject;
 
1395 - (void) removeObjectAtIndex:(NSUInteger)index;
 
1396 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
 
1404     @catch (id error) { \
 
1405         CYThrow(context, error, exception); \
 
1409 apr_status_t CYPoolRelease_(void *data) {
 
1410     id object(reinterpret_cast<id>(data));
 
1415 id CYPoolRelease_(apr_pool_t *pool, id object) {
 
1418     else if (pool == NULL)
 
1419         return [object autorelease];
 
1421         apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
 
1426 template <typename Type_>
 
1427 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
 
1428     return (Type_) CYPoolRelease_(pool, (id) object);
 
1431 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
 
1432     JSValueRef exception(NULL);
 
1433     bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
 
1434     CYThrow(context, exception);
 
1435     id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
 
1436     return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
 
1439 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
 
1440     if (!JSValueIsObjectOfClass(context, object, Instance_))
 
1441         return CYCastNSObject_(pool, context, object);
 
1443         Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
1444         return internal->GetValue();
 
1448 double CYCastDouble(const char *value, size_t size) {
 
1450     double number(strtod(value, &end));
 
1451     if (end != value + size)
 
1456 double CYCastDouble(const char *value) {
 
1457     return CYCastDouble(value, strlen(value));
 
1460 double CYCastDouble(JSContextRef context, JSValueRef value) {
 
1461     JSValueRef exception(NULL);
 
1462     double number(JSValueToNumber(context, value, &exception));
 
1463     CYThrow(context, exception);
 
1467 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
 
1468     return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
 
1471 template <typename Type_>
 
1472 NSString *CYCastNSString(apr_pool_t *pool, Type_ value) {
 
1473     return CYPoolRelease(pool, CYCopyNSString(value));
 
1476 bool CYCastBool(JSContextRef context, JSValueRef value) {
 
1477     return JSValueToBoolean(context, value);
 
1480 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
 
1484     switch (JSType type = JSValueGetType(context, value)) {
 
1485         case kJSTypeUndefined:
 
1486             object = [WebUndefined undefined];
 
1494         case kJSTypeBoolean:
 
1496             object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
 
1499             object = [[NSNumber alloc] initWithBoolean:value];
 
1505             object = CYCopyNSNumber(context, value);
 
1510             object = CYCopyNSString(context, value);
 
1515             // XXX: this might could be more efficient
 
1516             object = CYCastNSObject(pool, context, (JSObjectRef) value);
 
1521             @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
 
1528         return CYPoolRelease(pool, object);
 
1530         return [object retain];
 
1533 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1534     return CYNSObject(pool, context, value, true);
 
1537 id CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1538     return CYNSObject(pool, context, value, false);
 
1541 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
 
1543     size_t size(JSPropertyNameArrayGetCount(names));
 
1544     NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
 
1545     for (size_t index(0); index != size; ++index)
 
1546         [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
 
1550 void CYThrow(JSContextRef context, JSValueRef value) {
 
1553     @throw CYCastNSObject(NULL, context, value);
 
1556 JSValueRef CYJSNull(JSContextRef context) {
 
1557     return JSValueMakeNull(context);
 
1560 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
 
1561     return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
 
1564 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
 
1565     return CYCastJSValue(context, CYJSString(value));
 
1568 JSValueRef CYCastJSValue(JSContextRef context, id value) {
 
1570         return CYJSNull(context);
 
1571     else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
 
1572         return [value cy$JSValueInContext:context];
 
1574         return CYMakeInstance(context, value, false);
 
1577 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
 
1578     JSValueRef exception(NULL);
 
1579     JSObjectRef object(JSValueToObject(context, value, &exception));
 
1580     CYThrow(context, exception);
 
1584 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
 
1585     if (exception == NULL)
 
1587     *exception = CYCastJSValue(context, error);
 
1590 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
 
1591     JSValueRef exception(NULL);
 
1592     JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
 
1593     CYThrow(context, exception);
 
1597 bool CYIsCallable(JSContextRef context, JSValueRef value) {
 
1598     // XXX: this isn't actually correct
 
1599     return value != NULL && JSValueIsObject(context, value);
 
1602 @implementation CYJSObject
 
1604 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
 
1605     if ((self = [super init]) != nil) {
 
1608         JSValueProtect(context_, object_);
 
1613     JSValueUnprotect(context_, object_);
 
1617 - (NSObject *) cy$toJSON:(NSString *)key {
 
1618     JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
 
1619     if (!CYIsCallable(context_, toJSON))
 
1620         return [super cy$toJSON:key];
 
1622         JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
 
1623         JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
 
1624         // XXX: do I really want an NSNull here?!
 
1625         return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1629 - (NSString *) cy$toCYON {
 
1630     JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
 
1631     if (!CYIsCallable(context_, toCYON)) super:
 
1632         return [super cy$toCYON];
 
1633     else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
 
1634         return CYCastNSString(NULL, CYJSString(context_, value));
 
1638 - (NSUInteger) count {
 
1639     JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
 
1640     size_t size(JSPropertyNameArrayGetCount(names));
 
1641     JSPropertyNameArrayRelease(names);
 
1645 - (id) objectForKey:(id)key {
 
1646     JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
 
1647     if (JSValueIsUndefined(context_, value))
 
1649     return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1652 - (NSEnumerator *) keyEnumerator {
 
1653     JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
 
1654     NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
 
1655     JSPropertyNameArrayRelease(names);
 
1659 - (void) setObject:(id)object forKey:(id)key {
 
1660     CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
 
1663 - (void) removeObjectForKey:(id)key {
 
1664     JSValueRef exception(NULL);
 
1665     (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
 
1666     CYThrow(context_, exception);
 
1671 @implementation CYJSArray
 
1673 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
 
1674     if ((self = [super init]) != nil) {
 
1677         JSValueProtect(context_, object_);
 
1682     JSValueUnprotect(context_, object_);
 
1686 - (NSUInteger) count {
 
1687     return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
 
1690 - (id) objectAtIndex:(NSUInteger)index {
 
1691     size_t bounds([self count]);
 
1692     if (index >= bounds)
 
1693         @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
 
1694     JSValueRef exception(NULL);
 
1695     JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
 
1696     CYThrow(context_, exception);
 
1697     return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1700 - (void) addObject:(id)object {
 
1701     JSValueRef exception(NULL);
 
1702     JSValueRef arguments[1];
 
1703     arguments[0] = CYCastJSValue(context_, object);
 
1704     JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
 
1705     CYThrow(context_, exception);
 
1708 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
 
1709     size_t bounds([self count] + 1);
 
1710     if (index >= bounds)
 
1711         @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
 
1712     JSValueRef exception(NULL);
 
1713     JSValueRef arguments[3];
 
1714     arguments[0] = CYCastJSValue(context_, index);
 
1715     arguments[1] = CYCastJSValue(context_, 0);
 
1716     arguments[2] = CYCastJSValue(context_, object);
 
1717     JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
 
1718     CYThrow(context_, exception);
 
1721 - (void) removeLastObject {
 
1722     JSValueRef exception(NULL);
 
1723     JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
 
1724     CYThrow(context_, exception);
 
1727 - (void) removeObjectAtIndex:(NSUInteger)index {
 
1728     size_t bounds([self count]);
 
1729     if (index >= bounds)
 
1730         @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
 
1731     JSValueRef exception(NULL);
 
1732     JSValueRef arguments[2];
 
1733     arguments[0] = CYCastJSValue(context_, index);
 
1734     arguments[1] = CYCastJSValue(context_, 1);
 
1735     JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
 
1736     CYThrow(context_, exception);
 
1739 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
 
1740     size_t bounds([self count]);
 
1741     if (index >= bounds)
 
1742         @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
 
1743     CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
 
1748 NSString *CYCopyNSCYON(id value) {
 
1754         Class _class(object_getClass(value));
 
1755         SEL sel(@selector(cy$toCYON));
 
1757         if (Method toCYON = class_getInstanceMethod(_class, sel))
 
1758             string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
 
1759         else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
 
1760             if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
 
1761                 string = [value cy$toCYON];
 
1764             if (value == NSZombie_)
 
1765                 string = @"_NSZombie_";
 
1766             else if (_class == NSZombie_)
 
1767                 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
 
1768             // XXX: frowny /in/ the pants
 
1769             else if (value == NSMessageBuilder_ || value == Object_)
 
1772                 string = [NSString stringWithFormat:@"%@", value];
 
1775         // XXX: frowny pants
 
1777             string = @"undefined";
 
1780     return [string retain];
 
1783 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
 
1784     if (JSValueIsNull(context, value))
 
1785         return [@"null" retain];
 
1789             return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
 
1794 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
 
1795     return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
 
1798 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
 
1799     if (NSString *json = CYCopyNSCYON(context, value, exception)) {
 
1800         const char *string(CYPoolCString(pool, json));
 
1806 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
 
1810     JSObjectRef object_;
 
1818         // XXX: delete object_? ;(
 
1821     static CYInternal *Get(id self) {
 
1822         CYInternal *internal(NULL);
 
1823         if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
 
1824             // XXX: do something epic? ;P
 
1830     static CYInternal *Set(id self) {
 
1831         CYInternal *internal(NULL);
 
1832         if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
 
1833             if (internal == NULL) {
 
1834                 internal = new CYInternal();
 
1835                 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
 
1838             // XXX: do something epic? ;P
 
1844     bool HasProperty(JSContextRef context, JSStringRef name) {
 
1845         if (object_ == NULL)
 
1847         return JSObjectHasProperty(context, object_, name);
 
1850     JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
 
1851         if (object_ == NULL)
 
1853         return CYGetProperty(context, object_, name);
 
1856     void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
 
1857         if (object_ == NULL)
 
1858             object_ = JSObjectMake(context, NULL, NULL);
 
1859         CYSetProperty(context, object_, name, value);
 
1863 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
 
1864     Selector_privateData *internal(new Selector_privateData(sel));
 
1865     return JSObjectMake(context, Selector_, internal);
 
1868 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
 
1869     Pointer *internal(new Pointer(pointer, context, owner, type));
 
1870     return JSObjectMake(context, Pointer_, internal);
 
1873 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
 
1874     Functor_privateData *internal(new Functor_privateData(type, function));
 
1875     return JSObjectMake(context, Functor_, internal);
 
1878 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
 
1880         // XXX: this could be much more efficient
 
1881         const char *string([CYCastNSString(NULL, value) UTF8String]);
 
1884         size_t size(JSStringGetMaximumUTF8CStringSize(value));
 
1885         char *string(new(pool) char[size]);
 
1886         JSStringGetUTF8CString(value, string, size);
 
1891 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1892     return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
 
1895 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
 
1896     return CYGetOffset(CYPoolCString(pool, value), index);
 
1899 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
 
1900     switch (JSValueGetType(context, value)) {
 
1903         /*case kJSTypeString:
 
1904             return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
 
1906             if (JSValueIsObjectOfClass(context, value, Pointer_)) {
 
1907                 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
 
1908                 return internal->value_;
 
1911             double number(CYCastDouble(context, value));
 
1912             if (std::isnan(number))
 
1913                 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
 
1914             return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
 
1918 template <typename Type_>
 
1919 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
 
1920     return reinterpret_cast<Type_>(CYCastPointer_(context, value));
 
1923 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
 
1924     if (JSValueIsObjectOfClass(context, value, Selector_)) {
 
1925         Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
 
1926         return reinterpret_cast<SEL>(internal->value_);
 
1928         return CYCastPointer<SEL>(context, value);
 
1931 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
 
1932     switch (type->primitive) {
 
1933         case sig::boolean_P:
 
1934             *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
 
1937 #define CYPoolFFI_(primitive, native) \
 
1938         case sig::primitive ## _P: \
 
1939             *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
 
1942         CYPoolFFI_(uchar, unsigned char)
 
1943         CYPoolFFI_(char, char)
 
1944         CYPoolFFI_(ushort, unsigned short)
 
1945         CYPoolFFI_(short, short)
 
1946         CYPoolFFI_(ulong, unsigned long)
 
1947         CYPoolFFI_(long, long)
 
1948         CYPoolFFI_(uint, unsigned int)
 
1949         CYPoolFFI_(int, int)
 
1950         CYPoolFFI_(ulonglong, unsigned long long)
 
1951         CYPoolFFI_(longlong, long long)
 
1952         CYPoolFFI_(float, float)
 
1953         CYPoolFFI_(double, double)
 
1956         case sig::typename_P:
 
1957             *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
 
1960         case sig::selector_P:
 
1961             *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
 
1964         case sig::pointer_P:
 
1965             *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
 
1969             *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
 
1972         case sig::struct_P: {
 
1973             uint8_t *base(reinterpret_cast<uint8_t *>(data));
 
1974             JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
 
1975             for (size_t index(0); index != type->data.signature.count; ++index) {
 
1976                 sig::Element *element(&type->data.signature.elements[index]);
 
1977                 ffi_type *field(ffi->elements[index]);
 
1980                 if (aggregate == NULL)
 
1983                     rhs = CYGetProperty(context, aggregate, index);
 
1984                     if (JSValueIsUndefined(context, rhs)) {
 
1985                         if (element->name != NULL)
 
1986                             rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
 
1989                         if (JSValueIsUndefined(context, rhs)) undefined:
 
1990                             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
 
1994                 CYPoolFFI(pool, context, element->type, field, base, rhs);
 
1996                 base += field->size;
 
2004             NSLog(@"CYPoolFFI(%c)\n", type->primitive);
 
2009 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
 
2012     switch (type->primitive) {
 
2013         case sig::boolean_P:
 
2014             value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
 
2017 #define CYFromFFI_(primitive, native) \
 
2018         case sig::primitive ## _P: \
 
2019             value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
 
2022         CYFromFFI_(uchar, unsigned char)
 
2023         CYFromFFI_(char, char)
 
2024         CYFromFFI_(ushort, unsigned short)
 
2025         CYFromFFI_(short, short)
 
2026         CYFromFFI_(ulong, unsigned long)
 
2027         CYFromFFI_(long, long)
 
2028         CYFromFFI_(uint, unsigned int)
 
2029         CYFromFFI_(int, int)
 
2030         CYFromFFI_(ulonglong, unsigned long long)
 
2031         CYFromFFI_(longlong, long long)
 
2032         CYFromFFI_(float, float)
 
2033         CYFromFFI_(double, double)
 
2035         case sig::object_P: {
 
2036             if (id object = *reinterpret_cast<id *>(data)) {
 
2037                 value = CYCastJSValue(context, object);
 
2043         case sig::typename_P:
 
2044             value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
 
2047         case sig::selector_P:
 
2048             if (SEL sel = *reinterpret_cast<SEL *>(data))
 
2049                 value = CYMakeSelector(context, sel);
 
2053         case sig::pointer_P:
 
2054             if (void *pointer = *reinterpret_cast<void **>(data))
 
2055                 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
 
2060             if (char *utf8 = *reinterpret_cast<char **>(data))
 
2061                 value = CYCastJSValue(context, utf8);
 
2066             value = CYMakeStruct(context, data, type, ffi, owner);
 
2070             value = CYJSUndefined(context);
 
2074             value = CYJSNull(context);
 
2078             NSLog(@"CYFromFFI(%c)\n", type->primitive);
 
2085 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
 
2086     if (Method method = class_getInstanceMethod(_class, selector)) {
 
2090         method_getReturnType(method, type, sizeof(type));
 
2095     // XXX: possibly use a more "awesome" check?
 
2099 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
 
2101         return method_getTypeEncoding(method);
 
2102     else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
 
2103         return CYPoolCString(pool, type);
 
2108 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
 
2109     Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
 
2111     JSContextRef context(internal->context_);
 
2113     size_t count(internal->cif_.nargs);
 
2114     JSValueRef values[count];
 
2116     for (size_t index(0); index != count; ++index)
 
2117         values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
 
2119     JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
 
2120     CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
 
2123 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
 
2124     Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
 
2126     JSContextRef context(internal->context_);
 
2128     size_t count(internal->cif_.nargs);
 
2129     JSValueRef values[count];
 
2131     for (size_t index(0); index != count; ++index)
 
2132         values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
 
2134     JSObjectRef _this(CYCastJSObject(context, values[0]));
 
2136     JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
 
2137     CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
 
2140 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
 
2141     // XXX: in case of exceptions this will leak
 
2142     // XXX: in point of fact, this may /need/ to leak :(
 
2143     Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
 
2145     ffi_closure *closure((ffi_closure *) _syscall(mmap(
 
2146         NULL, sizeof(ffi_closure),
 
2147         PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
 
2151     ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
 
2152     _assert(status == FFI_OK);
 
2154     _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
 
2156     internal->value_ = closure;
 
2161 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
 
2162     Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
 
2163     return JSObjectMake(context, Functor_, internal);
 
2166 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
 
2167     JSValueRef exception(NULL);
 
2168     bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
 
2169     CYThrow(context, exception);
 
2172         JSObjectRef function(CYCastJSObject(context, value));
 
2173         return CYMakeFunctor(context, function, type);
 
2175         void (*function)()(CYCastPointer<void (*)()>(context, value));
 
2176         return CYMakeFunctor(context, function, type);
 
2180 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
 
2181     Message_privateData *internal(new Message_privateData(sel, type, imp));
 
2182     return JSObjectMake(context, Message_, internal);
 
2185 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
 
2186     JSObjectRef function(CYCastJSObject(context, value));
 
2187     Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
 
2188     return reinterpret_cast<IMP>(internal->GetValue());
 
2191 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
 
2192     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2193     Class _class(internal->GetValue());
 
2196     const char *name(CYPoolCString(pool, property));
 
2198     if (SEL sel = sel_getUid(name))
 
2199         if (class_getInstanceMethod(_class, sel) != NULL)
 
2205 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2206     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2207     Class _class(internal->GetValue());
 
2210     const char *name(CYPoolCString(pool, property));
 
2212     if (SEL sel = sel_getUid(name))
 
2213         if (Method method = class_getInstanceMethod(_class, sel))
 
2214             return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
 
2219 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2220     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2221     Class _class(internal->GetValue());
 
2224     const char *name(CYPoolCString(pool, property));
 
2226     SEL sel(sel_registerName(name));
 
2228     Method method(class_getInstanceMethod(_class, sel));
 
2233     if (JSValueIsObjectOfClass(context, value, Message_)) {
 
2234         Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
 
2235         type = sig::Unparse(pool, &message->signature_);
 
2236         imp = reinterpret_cast<IMP>(message->GetValue());
 
2238         type = CYPoolTypeEncoding(pool, _class, sel, method);
 
2239         imp = CYMakeMessage(context, value, type);
 
2243         method_setImplementation(method, imp);
 
2245         class_replaceMethod(_class, sel, imp, type);
 
2251 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2252     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2253     Class _class(internal->GetValue());
 
2256     const char *name(CYPoolCString(pool, property));
 
2258     if (SEL sel = sel_getUid(name))
 
2259         if (Method method = class_getInstanceMethod(_class, sel)) {
 
2260             objc_method_list list = {NULL, 1, {method}};
 
2261             class_removeMethods(_class, &list);
 
2269 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2270     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2271     Class _class(internal->GetValue());
 
2274     Method *data(class_copyMethodList(_class, &size));
 
2275     for (size_t i(0); i != size; ++i)
 
2276         JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
 
2280 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
 
2281     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2282     id self(internal->GetValue());
 
2284     if (JSStringIsEqualToUTF8CString(property, "$cyi"))
 
2288     NSString *name(CYCastNSString(pool, property));
 
2290     if (CYInternal *internal = CYInternal::Get(self))
 
2291         if (internal->HasProperty(context, property))
 
2294     Class _class(object_getClass(self));
 
2297         // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
 
2298         if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
 
2299             if ([self cy$hasProperty:name])
 
2301     } CYPoolCatch(false)
 
2303     const char *string(CYPoolCString(pool, name));
 
2305     if (class_getProperty(_class, string) != NULL)
 
2308     if (SEL sel = sel_getUid(string))
 
2309         if (CYImplements(self, _class, sel, true))
 
2315 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2316     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2317     id self(internal->GetValue());
 
2319     if (JSStringIsEqualToUTF8CString(property, "$cyi"))
 
2320         return Internal::Make(context, self, object);
 
2324         NSString *name(CYCastNSString(pool, property));
 
2326         if (CYInternal *internal = CYInternal::Get(self))
 
2327             if (JSValueRef value = internal->GetProperty(context, property))
 
2331             if (NSObject *data = [self cy$getProperty:name])
 
2332                 return CYCastJSValue(context, data);
 
2335         const char *string(CYPoolCString(pool, name));
 
2336         Class _class(object_getClass(self));
 
2339         if (objc_property_t property = class_getProperty(_class, string)) {
 
2340             PropertyAttributes attributes(property);
 
2341             SEL sel(sel_registerName(attributes.Getter()));
 
2342             return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
 
2346         if (SEL sel = sel_getUid(string))
 
2347             if (CYImplements(self, _class, sel, true))
 
2348                 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
 
2354 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2355     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2356     id self(internal->GetValue());
 
2361         NSString *name(CYCastNSString(pool, property));
 
2362         NSString *data(CYCastNSObject(pool, context, value));
 
2365             if ([self cy$setProperty:name to:data])
 
2369         const char *string(CYPoolCString(pool, name));
 
2370         Class _class(object_getClass(self));
 
2373         if (objc_property_t property = class_getProperty(_class, string)) {
 
2374             PropertyAttributes attributes(property);
 
2375             if (const char *setter = attributes.Setter()) {
 
2376                 SEL sel(sel_registerName(setter));
 
2377                 JSValueRef arguments[1] = {value};
 
2378                 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
 
2384         size_t length(strlen(string));
 
2386         char set[length + 5];
 
2392         if (string[0] != '\0') {
 
2393             set[3] = toupper(string[0]);
 
2394             memcpy(set + 4, string + 1, length - 1);
 
2397         set[length + 3] = ':';
 
2398         set[length + 4] = '\0';
 
2400         if (SEL sel = sel_getUid(set))
 
2401             if (CYImplements(self, _class, sel, false)) {
 
2402                 JSValueRef arguments[1] = {value};
 
2403                 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
 
2406         if (CYInternal *internal = CYInternal::Set(self)) {
 
2407             internal->SetProperty(context, property, value);
 
2415 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2416     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2417     id self(internal->GetValue());
 
2421             NSString *name(CYCastNSString(NULL, property));
 
2422             return [self cy$deleteProperty:name];
 
2427 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2428     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2429     id self(internal->GetValue());
 
2432     Class _class(object_getClass(self));
 
2436         objc_property_t *data(class_copyPropertyList(_class, &size));
 
2437         for (size_t i(0); i != size; ++i)
 
2438             JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
 
2443 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2445         Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2446         JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
 
2451 static bool CYIsClass(id self) {
 
2452     // XXX: this is a lame object_isClass
 
2453     return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
 
2456 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
 
2457     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
 
2458     Class _class(internal->GetValue());
 
2459     if (!CYIsClass(_class))
 
2462     if (JSValueIsObjectOfClass(context, instance, Instance_)) {
 
2463         Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
 
2464         // XXX: this isn't always safe
 
2466             return [linternal->GetValue() isKindOfClass:_class];
 
2473 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
 
2474     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2477     id self(internal->GetValue());
 
2478     const char *name(CYPoolCString(pool, property));
 
2480     if (object_getInstanceVariable(self, name, NULL) != NULL)
 
2486 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2487     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2491         id self(internal->GetValue());
 
2492         const char *name(CYPoolCString(pool, property));
 
2494         if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
 
2495             Type_privateData type(pool, ivar_getTypeEncoding(ivar));
 
2496             return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
 
2503 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2504     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2508         id self(internal->GetValue());
 
2509         const char *name(CYPoolCString(pool, property));
 
2511         if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
 
2512             Type_privateData type(pool, ivar_getTypeEncoding(ivar));
 
2513             CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
 
2521 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
 
2522     if (Class super = class_getSuperclass(_class))
 
2523         Internal_getPropertyNames_(super, names);
 
2526     Ivar *data(class_copyIvarList(_class, &size));
 
2527     for (size_t i(0); i != size; ++i)
 
2528         JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
 
2532 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2533     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2536     id self(internal->GetValue());
 
2537     Class _class(object_getClass(self));
 
2539     Internal_getPropertyNames_(_class, names);
 
2542 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2543     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2544     return internal->GetOwner();
 
2547 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
 
2548     Type_privateData *typical(internal->type_);
 
2549     sig::Type *type(typical->type_);
 
2553     const char *name(CYPoolCString(pool, property));
 
2554     size_t length(strlen(name));
 
2555     double number(CYCastDouble(name, length));
 
2557     size_t count(type->data.signature.count);
 
2559     if (std::isnan(number)) {
 
2560         if (property == NULL)
 
2563         sig::Element *elements(type->data.signature.elements);
 
2565         for (size_t local(0); local != count; ++local) {
 
2566             sig::Element *element(&elements[local]);
 
2567             if (element->name != NULL && strcmp(name, element->name) == 0) {
 
2575         index = static_cast<ssize_t>(number);
 
2576         if (index != number || index < 0 || static_cast<size_t>(index) >= count)
 
2581     ffi_type **elements(typical->GetFFI()->elements);
 
2583     base = reinterpret_cast<uint8_t *>(internal->value_);
 
2584     for (ssize_t local(0); local != index; ++local)
 
2585         base += elements[local]->size;
 
2590 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
 
2591     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
2592     Type_privateData *typical(internal->type_);
 
2594     ffi_type *ffi(typical->GetFFI());
 
2596     uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
 
2597     base += ffi->size * index;
 
2599     JSObjectRef owner(internal->GetOwner() ?: object);
 
2602         return CYFromFFI(context, typical->type_, ffi, base, false, owner);
 
2606 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2608     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
2609     Type_privateData *typical(internal->type_);
 
2611     if (typical->type_ == NULL)
 
2615     if (!CYGetOffset(pool, property, offset))
 
2618     return Pointer_getIndex(context, object, offset, exception);
 
2621 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2622     return Pointer_getIndex(context, object, 0, exception);
 
2625 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
 
2626     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
2627     Type_privateData *typical(internal->type_);
 
2629     ffi_type *ffi(typical->GetFFI());
 
2631     uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
 
2632     base += ffi->size * index;
 
2635         CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
 
2640 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2642     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
2643     Type_privateData *typical(internal->type_);
 
2645     if (typical->type_ == NULL)
 
2649     if (!CYGetOffset(pool, property, offset))
 
2652     return Pointer_setIndex(context, object, offset, value, exception);
 
2655 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2656     return Pointer_setIndex(context, object, 0, value, exception);
 
2659 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2660     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
 
2661     Type_privateData *typical(internal->type_);
 
2662     return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
 
2665 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2667     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
2668     Type_privateData *typical(internal->type_);
 
2673     if (!Index_(pool, internal, property, index, base))
 
2676     JSObjectRef owner(internal->GetOwner() ?: object);
 
2679         return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
 
2683 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2685     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
2686     Type_privateData *typical(internal->type_);
 
2691     if (!Index_(pool, internal, property, index, base))
 
2695         CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
 
2700 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2701     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
2702     Type_privateData *typical(internal->type_);
 
2703     sig::Type *type(typical->type_);
 
2708     size_t count(type->data.signature.count);
 
2709     sig::Element *elements(type->data.signature.elements);
 
2713     for (size_t index(0); index != count; ++index) {
 
2715         name = elements[index].name;
 
2718             sprintf(number, "%lu", index);
 
2722         JSPropertyNameAccumulatorAddName(names, CYJSString(name));
 
2726 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)()) {
 
2728         if (setups + count != signature->count - 1)
 
2729             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
 
2731         size_t size(setups + count);
 
2733         memcpy(values, setup, sizeof(void *) * setups);
 
2735         for (size_t index(setups); index != size; ++index) {
 
2736             sig::Element *element(&signature->elements[index + 1]);
 
2737             ffi_type *ffi(cif->arg_types[index]);
 
2739             values[index] = new(pool) uint8_t[ffi->size];
 
2740             CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
 
2743         uint8_t value[cif->rtype->size];
 
2744         ffi_call(cif, function, value, values);
 
2746         return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
 
2750 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2753         NSString *name(CYCastNSString(pool, property));
 
2754         if (Class _class = NSClassFromString(name))
 
2755             return CYMakeInstance(context, _class, true);
 
2760 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2761     size_t size(objc_getClassList(NULL, 0));
 
2762     Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
 
2765     size_t writ(objc_getClassList(data, size));
 
2768         if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
 
2774     for (size_t i(0); i != writ; ++i)
 
2775         JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
 
2781 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2782     const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
 
2786         const char *name(CYPoolCString(pool, property));
 
2788         const char **data(objc_copyClassNamesForImage(internal, &size));
 
2790         for (size_t i(0); i != size; ++i)
 
2791             if (strcmp(name, data[i]) == 0) {
 
2792                 if (Class _class = objc_getClass(name)) {
 
2793                     value = CYMakeInstance(context, _class, true);
 
2805 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2806     const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
 
2808     const char **data(objc_copyClassNamesForImage(internal, &size));
 
2809     for (size_t i(0); i != size; ++i)
 
2810         JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
 
2814 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2817         const char *name(CYPoolCString(pool, property));
 
2819         const char **data(objc_copyImageNames(&size));
 
2820         for (size_t i(0); i != size; ++i)
 
2821             if (strcmp(name, data[i]) == 0) {
 
2830         JSObjectRef value(JSObjectMake(context, NULL, NULL));
 
2831         CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
 
2836 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2838     const char **data(objc_copyImageNames(&size));
 
2839     for (size_t i(0); i != size; ++i)
 
2840         JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
 
2844 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2847         NSString *name(CYCastNSString(pool, property));
 
2848         if (Protocol *protocol = NSProtocolFromString(name))
 
2849             return CYMakeInstance(context, protocol, true);
 
2854 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2856     Protocol **data(objc_copyProtocolList(&size));
 
2857     for (size_t i(0); i != size; ++i)
 
2858         JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
 
2862 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
 
2863     Type_privateData *internal(new Type_privateData(NULL, type));
 
2864     return JSObjectMake(context, Type_privateData::Class_, internal);
 
2867 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
 
2868     Type_privateData *internal(new Type_privateData(type));
 
2869     return JSObjectMake(context, Type_privateData::Class_, internal);
 
2872 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2873     if (JSStringIsEqualToUTF8CString(property, "nil"))
 
2874         return Instance::Make(context, nil);
 
2878         NSString *name(CYCastNSString(pool, property));
 
2879         if (Class _class = NSClassFromString(name))
 
2880             return CYMakeInstance(context, _class, true);
 
2881         if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
 
2882             switch ([[entry objectAtIndex:0] intValue]) {
 
2884                     return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
 
2886                     return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
 
2888                     // XXX: this is horrendously inefficient
 
2889                     sig::Signature signature;
 
2890                     sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
 
2892                     sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
 
2893                     return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
 
2895         if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
 
2896             switch ([[entry objectAtIndex:0] intValue]) {
 
2897                 // XXX: implement case 0
 
2899                     return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
 
2905 static bool stret(ffi_type *ffi_type) {
 
2906     return ffi_type->type == FFI_TYPE_STRUCT && (
 
2907         ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
 
2908         struct_forward_array[ffi_type->size] != 0
 
2913     int *_NSGetArgc(void);
 
2914     char ***_NSGetArgv(void);
 
2917 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2922             NSLog(@"%s", CYCastCString(context, arguments[0]));
 
2923         return CYJSUndefined(context);
 
2927 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
 
2930     Class _class(object_getClass(self));
 
2931     if (Method method = class_getInstanceMethod(_class, _cmd))
 
2932         type = method_getTypeEncoding(method);
 
2936                 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
 
2938                     @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
 
2939                 type = CYPoolCString(pool, [method _typeString]);
 
2948     sig::Signature signature;
 
2949     sig::Parse(pool, &signature, type, &Structor_);
 
2952     sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
 
2954     void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
 
2955     return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
 
2958 static size_t Nonce_(0);
 
2960 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2962     sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
 
2963     return CYCastJSValue(context, name);
 
2966 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2976             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
 
2978         if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
 
2979             Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
 
2980             self = internal->GetValue();
 
2981             uninitialized = internal->IsUninitialized();
 
2983                 internal->value_ = nil;
 
2985             self = CYCastNSObject(pool, context, arguments[0]);
 
2986             uninitialized = false;
 
2990             return CYJSNull(context);
 
2992         _cmd = CYCastSEL(context, arguments[1]);
 
2995     return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
 
2998 /* Hook: objc_registerClassPair {{{ */
 
2999 // XXX: replace this with associated objects
 
3001 MSHook(void, CYDealloc, id self, SEL sel) {
 
3002     CYInternal *internal;
 
3003     object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
 
3004     if (internal != NULL)
 
3006     _CYDealloc(self, sel);
 
3009 MSHook(void, objc_registerClassPair, Class _class) {
 
3010     Class super(class_getSuperclass(_class));
 
3011     if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
 
3012         class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
 
3013         MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
 
3016     _objc_registerClassPair(_class);
 
3019 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3022             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
 
3024         Class _class(CYCastNSObject(pool, context, arguments[0]));
 
3025         $objc_registerClassPair(_class);
 
3026         return CYJSUndefined(context);
 
3031 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3032     JSGarbageCollect(context);
 
3033     return CYJSUndefined(context);
 
3036 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3037     JSValueRef setup[count + 2];
 
3040     memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
 
3041     return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
 
3044 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3046     Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
 
3048     // XXX: handle Instance::Uninitialized?
 
3049     id self(CYCastNSObject(pool, context, _this));
 
3053     setup[1] = &internal->sel_;
 
3055     return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
 
3058 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3060     Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
 
3061     return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
 
3064 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3067             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
 
3068         const char *name(CYCastCString(context, arguments[0]));
 
3069         return CYMakeSelector(context, sel_registerName(name));
 
3073 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3076             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
 
3078         void *value(CYCastPointer<void *>(context, arguments[0]));
 
3079         const char *type(CYCastCString(context, arguments[1]));
 
3083         sig::Signature signature;
 
3084         sig::Parse(pool, &signature, type, &Structor_);
 
3086         return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
 
3090 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3093             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
 
3094         const char *type(CYCastCString(context, arguments[0]));
 
3095         return CYMakeType(context, type);
 
3099 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3100     Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
 
3105         if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
 
3106             type.primitive = sig::pointer_P;
 
3107             type.data.data.size = 0;
 
3109             size_t index(CYGetIndex(NULL, property));
 
3110             if (index == _not(size_t))
 
3112             type.primitive = sig::array_P;
 
3113             type.data.data.size = index;
 
3119         type.data.data.type = internal->type_;
 
3121         return CYMakeType(context, &type);
 
3125 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3126     Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
 
3130             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
 
3131         sig::Type *type(internal->type_);
 
3132         ffi_type *ffi(internal->GetFFI());
 
3134         uint8_t value[ffi->size];
 
3136         CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
 
3137         return CYFromFFI(context, type, ffi, value);
 
3141 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3144             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
 
3145         Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
 
3147         sig::Type *type(internal->type_);
 
3150         if (type->primitive != sig::array_P)
 
3153             size = type->data.data.size;
 
3154             type = type->data.data.type;
 
3157         void *value(malloc(internal->GetFFI()->size));
 
3158         return CYMakePointer(context, value, type, NULL, NULL);
 
3162 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3165             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
 
3166         id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
 
3167         return Instance::Make(context, self);
 
3171 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3174             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
 
3175         const char *type(CYCastCString(context, arguments[1]));
 
3176         return CYMakeFunctor(context, arguments[0], type);
 
3180 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3181     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
 
3182     return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
 
3185 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3186     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
3187     Type_privateData *typical(internal->GetType());
 
3192     if (typical == NULL) {
 
3196         type = typical->type_;
 
3197         ffi = typical->ffi_;
 
3200     return CYMakePointer(context, &internal->value_, type, ffi, object);
 
3203 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3204     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
3207         return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
 
3211 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3212     return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
 
3215 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3216     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
3218     sprintf(string, "%p", internal->value_);
 
3221         return CYCastJSValue(context, string);
 
3225 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3226     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
3227     return Instance::Make(context, object_getClass(internal->GetValue()));
 
3230 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3231     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
3232     id self(internal->GetValue());
 
3233     if (!CYIsClass(self))
 
3234         return CYJSUndefined(context);
 
3236         return CYGetClassPrototype(context, self);
 
3240 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3241     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
3242     id self(internal->GetValue());
 
3243     if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
 
3244         return CYJSUndefined(context);
 
3245     return Messages::Make(context, self);
 
3248 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3249     if (!JSValueIsObjectOfClass(context, _this, Instance_))
 
3252     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
3256             return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
 
3261 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3262     if (!JSValueIsObjectOfClass(context, _this, Instance_))
 
3265     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
3269             NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
 
3270             // XXX: check for support of cy$toJSON?
 
3271             return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
 
3276 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3277     if (!JSValueIsObjectOfClass(context, _this, Instance_))
 
3280     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
3284             return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
 
3289 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3290     Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
3293         return CYCastJSValue(context, sel_getName(internal->GetValue()));
 
3297 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3298     return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
 
3301 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3302     Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
3303     const char *name(sel_getName(internal->GetValue()));
 
3307             return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
 
3312 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3315             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
 
3317         Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
3318         Class _class(CYCastNSObject(pool, context, arguments[0]));
 
3319         SEL sel(internal->GetValue());
 
3320         Method method(class_getInstanceMethod(_class, sel));
 
3321         const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
 
3322         return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
 
3326 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3328         Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
 
3330         const char *type(sig::Unparse(pool, internal->type_));
 
3332             return CYCastJSValue(context, CYJSString(type));
 
3337 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3339         Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
 
3341         const char *type(sig::Unparse(pool, internal->type_));
 
3343             return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
 
3348 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3349     return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
 
3352 static JSStaticValue CYValue_staticValues[2] = {
 
3353     {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
 
3354     {NULL, NULL, NULL, 0}
 
3357 static JSStaticValue Pointer_staticValues[2] = {
 
3358     {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3359     {NULL, NULL, NULL, 0}
 
3362 static JSStaticFunction Pointer_staticFunctions[4] = {
 
3363     {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3364     {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3365     {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3369 static JSStaticFunction Struct_staticFunctions[2] = {
 
3370     {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3374 static JSStaticFunction Functor_staticFunctions[4] = {
 
3375     {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3376     {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3377     {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3381 static JSStaticValue Instance_staticValues[5] = {
 
3382     {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3383     {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3384     {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3385     {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3386     {NULL, NULL, NULL, 0}
 
3389 static JSStaticFunction Instance_staticFunctions[5] = {
 
3390     {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3391     {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3392     {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3393     {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3397 static JSStaticFunction Internal_staticFunctions[2] = {
 
3398     {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3402 static JSStaticFunction Selector_staticFunctions[5] = {
 
3403     {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3404     {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3405     {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3406     {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3410 static JSStaticFunction Type_staticFunctions[4] = {
 
3411     {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3412     {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3413     {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3417 void CYSetArgs(int argc, const char *argv[]) {
 
3418     JSContextRef context(CYGetJSContext());
 
3419     JSValueRef args[argc];
 
3420     for (int i(0); i != argc; ++i)
 
3421         args[i] = CYCastJSValue(context, argv[i]);
 
3422     JSValueRef exception(NULL);
 
3423     JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
 
3424     CYThrow(context, exception);
 
3425     CYSetProperty(context, System_, CYJSString("args"), array);
 
3428 JSObjectRef CYGetGlobalObject(JSContextRef context) {
 
3429     return JSContextGetGlobalObject(context);
 
3432 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
 
3433     JSContextRef context(CYGetJSContext());
 
3434     JSValueRef exception(NULL), result;
 
3437         result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
 
3438     } catch (const char *error) {
 
3442     if (exception != NULL) { error:
 
3447     if (JSValueIsUndefined(context, result))
 
3453         json = CYPoolCCYON(pool, context, result, &exception);
 
3454     } catch (const char *error) {
 
3458     if (exception != NULL)
 
3461     CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
 
3465 static apr_pool_t *Pool_;
 
3469     const char * volatile data_;
 
3472 // XXX: this is "tre lame"
 
3473 @interface CYClient_ : NSObject {
 
3476 - (void) execute:(NSValue *)value;
 
3480 @implementation CYClient_
 
3482 - (void) execute:(NSValue *)value {
 
3483     CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
 
3484     const char *data(execute->data_);
 
3485     execute->data_ = NULL;
 
3486     execute->data_ = CYExecute(execute->pool_, data);
 
3495     apr_thread_t *thread_;
 
3497     CYClient(int socket) :
 
3503         _syscall(close(socket_));
 
3506     void Handle() { _pooled
 
3507         CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
 
3511             if (!CYRecvAll(socket_, &size, sizeof(size)))
 
3515             char *data(new(pool) char[size + 1]);
 
3516             if (!CYRecvAll(socket_, data, size))
 
3520             CYDriver driver("");
 
3521             cy::parser parser(driver);
 
3523             driver.data_ = data;
 
3524             driver.size_ = size;
 
3527             if (parser.parse() != 0 || !driver.errors_.empty()) {
 
3529                 size = _not(size_t);
 
3531                 CYContext context(driver.pool_);
 
3532                 driver.program_->Replace(context);
 
3533                 std::ostringstream str;
 
3535                 out << *driver.program_;
 
3536                 std::string code(str.str());
 
3537                 CYExecute_ execute = {pool, code.c_str()};
 
3538                 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
 
3539                 json = execute.data_;
 
3540                 size = json == NULL ? _not(size_t) : strlen(json);
 
3543             if (!CYSendAll(socket_, &size, sizeof(size)))
 
3546                 if (!CYSendAll(socket_, json, size))
 
3552 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
 
3553     CYClient *client(reinterpret_cast<CYClient *>(data));
 
3559 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
 
3560     CYClient *client(new(pool) CYClient(socket));
 
3561     apr_threadattr_t *attr;
 
3562     _aprcall(apr_threadattr_create(&attr, client->pool_));
 
3563     _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
 
3566 MSInitialize { _pooled
 
3567     _aprcall(apr_initialize());
 
3568     _aprcall(apr_pool_create(&Pool_, NULL));
 
3570     Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
 
3571     Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
 
3573     Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
 
3576     NSCFBoolean_ = objc_getClass("NSCFBoolean");
 
3577     NSCFType_ = objc_getClass("NSCFType");
 
3580     NSArray_ = objc_getClass("NSArray");
 
3581     NSDictionary_ = objc_getClass("NSDictonary");
 
3582     NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
 
3583     NSZombie_ = objc_getClass("_NSZombie_");
 
3584     Object_ = objc_getClass("Object");
 
3587 JSGlobalContextRef CYGetJSContext() {
 
3588     if (Context_ == NULL) {
 
3589         JSClassDefinition definition;
 
3591         definition = kJSClassDefinitionEmpty;
 
3592         definition.className = "Functor";
 
3593         definition.staticFunctions = Functor_staticFunctions;
 
3594         definition.callAsFunction = &Functor_callAsFunction;
 
3595         definition.finalize = &Finalize;
 
3596         Functor_ = JSClassCreate(&definition);
 
3598         definition = kJSClassDefinitionEmpty;
 
3599         definition.className = "Instance";
 
3600         definition.staticValues = Instance_staticValues;
 
3601         definition.staticFunctions = Instance_staticFunctions;
 
3602         definition.hasProperty = &Instance_hasProperty;
 
3603         definition.getProperty = &Instance_getProperty;
 
3604         definition.setProperty = &Instance_setProperty;
 
3605         definition.deleteProperty = &Instance_deleteProperty;
 
3606         definition.getPropertyNames = &Instance_getPropertyNames;
 
3607         definition.callAsConstructor = &Instance_callAsConstructor;
 
3608         definition.hasInstance = &Instance_hasInstance;
 
3609         definition.finalize = &Finalize;
 
3610         Instance_ = JSClassCreate(&definition);
 
3612         definition = kJSClassDefinitionEmpty;
 
3613         definition.className = "Internal";
 
3614         definition.staticFunctions = Internal_staticFunctions;
 
3615         definition.hasProperty = &Internal_hasProperty;
 
3616         definition.getProperty = &Internal_getProperty;
 
3617         definition.setProperty = &Internal_setProperty;
 
3618         definition.getPropertyNames = &Internal_getPropertyNames;
 
3619         definition.finalize = &Finalize;
 
3620         Internal_ = JSClassCreate(&definition);
 
3622         definition = kJSClassDefinitionEmpty;
 
3623         definition.className = "Message";
 
3624         definition.staticFunctions = Functor_staticFunctions;
 
3625         definition.callAsFunction = &Message_callAsFunction;
 
3626         definition.finalize = &Finalize;
 
3627         Message_ = JSClassCreate(&definition);
 
3629         definition = kJSClassDefinitionEmpty;
 
3630         definition.className = "Messages";
 
3631         definition.hasProperty = &Messages_hasProperty;
 
3632         definition.getProperty = &Messages_getProperty;
 
3633         definition.setProperty = &Messages_setProperty;
 
3635         definition.deleteProperty = &Messages_deleteProperty;
 
3637         definition.getPropertyNames = &Messages_getPropertyNames;
 
3638         definition.finalize = &Finalize;
 
3639         Messages_ = JSClassCreate(&definition);
 
3641         definition = kJSClassDefinitionEmpty;
 
3642         definition.className = "NSArrayPrototype";
 
3643         //definition.hasProperty = &NSArrayPrototype_hasProperty;
 
3644         //definition.getProperty = &NSArrayPrototype_getProperty;
 
3645         //definition.setProperty = &NSArrayPrototype_setProperty;
 
3646         //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
 
3647         //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
 
3648         NSArrayPrototype_ = JSClassCreate(&definition);
 
3650         definition = kJSClassDefinitionEmpty;
 
3651         definition.className = "Pointer";
 
3652         definition.staticValues = Pointer_staticValues;
 
3653         definition.staticFunctions = Pointer_staticFunctions;
 
3654         definition.getProperty = &Pointer_getProperty;
 
3655         definition.setProperty = &Pointer_setProperty;
 
3656         definition.finalize = &Finalize;
 
3657         Pointer_ = JSClassCreate(&definition);
 
3659         definition = kJSClassDefinitionEmpty;
 
3660         definition.className = "Selector";
 
3661         definition.staticValues = CYValue_staticValues;
 
3662         definition.staticFunctions = Selector_staticFunctions;
 
3663         definition.callAsFunction = &Selector_callAsFunction;
 
3664         definition.finalize = &Finalize;
 
3665         Selector_ = JSClassCreate(&definition);
 
3667         definition = kJSClassDefinitionEmpty;
 
3668         definition.className = "Struct";
 
3669         definition.staticFunctions = Struct_staticFunctions;
 
3670         definition.getProperty = &Struct_getProperty;
 
3671         definition.setProperty = &Struct_setProperty;
 
3672         definition.getPropertyNames = &Struct_getPropertyNames;
 
3673         definition.finalize = &Finalize;
 
3674         Struct_ = JSClassCreate(&definition);
 
3676         definition = kJSClassDefinitionEmpty;
 
3677         definition.className = "Type";
 
3678         definition.staticFunctions = Type_staticFunctions;
 
3679         definition.getProperty = &Type_getProperty;
 
3680         definition.callAsFunction = &Type_callAsFunction;
 
3681         definition.callAsConstructor = &Type_callAsConstructor;
 
3682         definition.finalize = &Finalize;
 
3683         Type_privateData::Class_ = JSClassCreate(&definition);
 
3685         definition = kJSClassDefinitionEmpty;
 
3686         definition.className = "Runtime";
 
3687         definition.getProperty = &Runtime_getProperty;
 
3688         Runtime_ = JSClassCreate(&definition);
 
3690         definition = kJSClassDefinitionEmpty;
 
3691         definition.className = "ObjectiveC::Classes";
 
3692         definition.getProperty = &ObjectiveC_Classes_getProperty;
 
3693         definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
 
3694         ObjectiveC_Classes_ = JSClassCreate(&definition);
 
3696         definition = kJSClassDefinitionEmpty;
 
3697         definition.className = "ObjectiveC::Images";
 
3698         definition.getProperty = &ObjectiveC_Images_getProperty;
 
3699         definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
 
3700         ObjectiveC_Images_ = JSClassCreate(&definition);
 
3702         definition = kJSClassDefinitionEmpty;
 
3703         definition.className = "ObjectiveC::Image::Classes";
 
3704         definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
 
3705         definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
 
3706         ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
 
3708         definition = kJSClassDefinitionEmpty;
 
3709         definition.className = "ObjectiveC::Protocols";
 
3710         definition.getProperty = &ObjectiveC_Protocols_getProperty;
 
3711         definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
 
3712         ObjectiveC_Protocols_ = JSClassCreate(&definition);
 
3714         definition = kJSClassDefinitionEmpty;
 
3715         //definition.getProperty = &Global_getProperty;
 
3716         JSClassRef Global(JSClassCreate(&definition));
 
3718         JSGlobalContextRef context(JSGlobalContextCreate(Global));
 
3721         JSObjectRef global(CYGetGlobalObject(context));
 
3723         JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
 
3724         ObjectiveC_ = JSObjectMake(context, NULL, NULL);
 
3725         CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
 
3727         CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
 
3728         CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
 
3729         CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
 
3731         Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
 
3732         Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
 
3733         String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
 
3735         length_ = JSStringCreateWithUTF8CString("length");
 
3736         message_ = JSStringCreateWithUTF8CString("message");
 
3737         name_ = JSStringCreateWithUTF8CString("name");
 
3738         prototype_ = JSStringCreateWithUTF8CString("prototype");
 
3739         toCYON_ = JSStringCreateWithUTF8CString("toCYON");
 
3740         toJSON_ = JSStringCreateWithUTF8CString("toJSON");
 
3742         JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
 
3743         Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
 
3745         Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
 
3746         Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
 
3747         Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
 
3748         Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
 
3750         JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
 
3751         JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
 
3752         JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
 
3753         JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
 
3755         Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
 
3757         JSValueRef function(CYGetProperty(context, Function_, prototype_));
 
3758         JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
 
3759         JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
 
3760         JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
 
3762         CYSetProperty(context, global, CYJSString("Functor"), Functor);
 
3763         CYSetProperty(context, global, CYJSString("Instance"), Instance);
 
3764         CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
 
3765         CYSetProperty(context, global, CYJSString("Selector"), Selector);
 
3766         CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
 
3768         MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
 
3771         class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
 
3774         JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
 
3775         CYSetProperty(context, global, CYJSString("Cycript"), cycript);
 
3776         CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
 
3778         CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
 
3779         CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
 
3780         CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
 
3782         System_ = JSObjectMake(context, NULL, NULL);
 
3783         CYSetProperty(context, global, CYJSString("system"), System_);
 
3784         CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
 
3785         //CYSetProperty(context, System_, CYJSString("global"), global);
 
3787         CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
 
3789         Result_ = JSStringCreateWithUTF8CString("_");
 
3791         JSValueProtect(context, Array_);
 
3792         JSValueProtect(context, Function_);
 
3793         JSValueProtect(context, String_);
 
3795         JSValueProtect(context, Instance_prototype_);
 
3796         JSValueProtect(context, Object_prototype_);
 
3798         JSValueProtect(context, Array_prototype_);
 
3799         JSValueProtect(context, Array_pop_);
 
3800         JSValueProtect(context, Array_push_);
 
3801         JSValueProtect(context, Array_splice_);