1 /* Cycript - Remove 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.
 
  42 #include <substrate.h>
 
  43 #include "cycript.hpp"
 
  45 #include "sig/parse.hpp"
 
  46 #include "sig/ffi_type.hpp"
 
  48 #include "Pooling.hpp"
 
  51 #include <CoreFoundation/CoreFoundation.h>
 
  52 #include <CoreFoundation/CFLogUtilities.h>
 
  54 #include <WebKit/WebScriptObject.h>
 
  59 #include <ext/stdio_filebuf.h>
 
  67 #include "Cycript.tab.hh"
 
  69 #include <apr-1/apr_thread_proc.h>
 
  74 #define _assert(test) do { \
 
  76         @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
 
  79 #define _trace() do { \
 
  80     CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
 
  85     NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
 
  87 #define CYPoolCatch(value) \
 
  88     @catch (NSException *error) { \
 
  89         _saved = [error retain]; \
 
  95             [_saved autorelease]; \
 
  99 void CYThrow(JSContextRef context, JSValueRef value);
 
 101 /* JavaScript Properties {{{ */
 
 102 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
 
 103     JSValueRef exception(NULL);
 
 104     JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
 
 105     CYThrow(context, exception);
 
 109 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
 
 110     JSValueRef exception(NULL);
 
 111     JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
 
 112     CYThrow(context, exception);
 
 116 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
 
 117     JSValueRef exception(NULL);
 
 118     JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
 
 119     CYThrow(context, exception);
 
 122 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
 
 123     JSValueRef exception(NULL);
 
 124     JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
 
 125     CYThrow(context, exception);
 
 128 /* JavaScript Strings {{{ */
 
 129 JSStringRef CYCopyJSString(id value) {
 
 130     // XXX: this definition scares me; is anyone using this?!
 
 131     return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
 
 134 JSStringRef CYCopyJSString(const char *value) {
 
 135     return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
 
 138 JSStringRef CYCopyJSString(JSStringRef value) {
 
 139     return value == NULL ? NULL : JSStringRetain(value);
 
 142 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
 
 143     if (JSValueIsNull(context, value))
 
 145     JSValueRef exception(NULL);
 
 146     JSStringRef string(JSValueToStringCopy(context, value, &exception));
 
 147     CYThrow(context, exception);
 
 157             JSStringRelease(string_);
 
 161     CYJSString(const CYJSString &rhs) :
 
 162         string_(CYCopyJSString(rhs.string_))
 
 166     template <typename Arg0_>
 
 167     CYJSString(Arg0_ arg0) :
 
 168         string_(CYCopyJSString(arg0))
 
 172     template <typename Arg0_, typename Arg1_>
 
 173     CYJSString(Arg0_ arg0, Arg1_ arg1) :
 
 174         string_(CYCopyJSString(arg0, arg1))
 
 178     CYJSString &operator =(const CYJSString &rhs) {
 
 180         string_ = CYCopyJSString(rhs.string_);
 
 193     operator JSStringRef() const {
 
 198 CFStringRef CYCopyCFString(JSStringRef value) {
 
 199     return JSStringCopyCFString(kCFAllocatorDefault, value);
 
 202 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
 
 203     return CYCopyCFString(CYJSString(context, value));
 
 208 static JSGlobalContextRef Context_;
 
 209 static JSObjectRef System_;
 
 210 static JSObjectRef ObjectiveC_;
 
 212 static JSClassRef Functor_;
 
 213 static JSClassRef Instance_;
 
 214 static JSClassRef Internal_;
 
 215 static JSClassRef Message_;
 
 216 static JSClassRef Messages_;
 
 217 static JSClassRef NSArrayPrototype_;
 
 218 static JSClassRef Pointer_;
 
 219 static JSClassRef Runtime_;
 
 220 static JSClassRef Selector_;
 
 221 static JSClassRef Struct_;
 
 222 static JSClassRef Type_;
 
 224 static JSClassRef ObjectiveC_Classes_;
 
 225 static JSClassRef ObjectiveC_Image_Classes_;
 
 226 static JSClassRef ObjectiveC_Images_;
 
 227 static JSClassRef ObjectiveC_Protocols_;
 
 229 static JSObjectRef Array_;
 
 230 static JSObjectRef Function_;
 
 231 static JSObjectRef String_;
 
 233 static JSStringRef Result_;
 
 235 static JSStringRef length_;
 
 236 static JSStringRef message_;
 
 237 static JSStringRef name_;
 
 238 static JSStringRef prototype_;
 
 239 static JSStringRef toCYON_;
 
 240 static JSStringRef toJSON_;
 
 242 static JSObjectRef Instance_prototype_;
 
 243 static JSObjectRef Object_prototype_;
 
 245 static JSObjectRef Array_prototype_;
 
 246 static JSObjectRef Array_pop_;
 
 247 static JSObjectRef Array_push_;
 
 248 static JSObjectRef Array_splice_;
 
 250 static Class NSArray_;
 
 251 static Class NSCFBoolean_;
 
 252 static Class NSCFType_;
 
 253 static Class NSDictionary_;
 
 254 static Class NSMessageBuilder_;
 
 255 static Class NSZombie_;
 
 256 static Class Object_;
 
 258 static NSArray *Bridge_;
 
 260 static void Finalize(JSObjectRef object) {
 
 261     delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
 
 264 class Type_privateData;
 
 274     CYValue(void *value) :
 
 279     CYValue(const CYValue &rhs) :
 
 284     virtual Type_privateData *GetType() const {
 
 289 struct Selector_privateData :
 
 292     Selector_privateData(SEL value) :
 
 297     SEL GetValue() const {
 
 298         return reinterpret_cast<SEL>(value_);
 
 301     virtual Type_privateData *GetType() const;
 
 304 // XXX: trick this out with associated objects!
 
 305 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
 
 307         return Instance_prototype_;
 
 309     // XXX: I need to think through multi-context
 
 310     typedef std::map<Class, JSValueRef> CacheMap;
 
 311     static CacheMap cache_;
 
 313     JSValueRef &value(cache_[self]);
 
 317     JSClassRef _class(NULL);
 
 318     JSValueRef prototype;
 
 320     if (self == NSArray_)
 
 321         prototype = Array_prototype_;
 
 322     else if (self == NSDictionary_)
 
 323         prototype = Object_prototype_;
 
 325         prototype = CYGetClassPrototype(context, class_getSuperclass(self));
 
 327     JSObjectRef object(JSObjectMake(context, _class, NULL));
 
 328     JSObjectSetPrototype(context, object, prototype);
 
 330     JSValueProtect(context, object);
 
 340         Transient     = (1 << 0),
 
 341         Uninitialized = (1 << 1),
 
 346     Instance(id value, Flags flags) :
 
 352     virtual ~Instance() {
 
 353         if ((flags_ & Transient) == 0)
 
 354             // XXX: does this handle background threads correctly?
 
 355             [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
 
 358     static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
 
 359         JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
 
 360         JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object == nil ? nil : object_getClass(object)));
 
 364     id GetValue() const {
 
 365         return reinterpret_cast<id>(value_);
 
 368     bool IsUninitialized() const {
 
 369         return (flags_ & Uninitialized) != 0;
 
 372     virtual Type_privateData *GetType() const;
 
 378     Messages(Class value) :
 
 383     static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
 
 384         JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
 
 385         if (_class == NSArray_)
 
 387         if (Class super = class_getSuperclass(_class))
 
 388             JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
 
 390             JSObjectSetPrototype(context, value, Array_prototype_);*/
 
 394     Class GetValue() const {
 
 395         return reinterpret_cast<Class>(value_);
 
 403     JSContextRef context_;
 
 407     CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
 
 412         JSValueProtect(context_, owner_);
 
 416         JSValueUnprotect(context_, owner_);
 
 419     JSObjectRef GetOwner() const {
 
 427     Internal(id value, JSContextRef context, JSObjectRef owner) :
 
 428         CYOwned(value, context, owner)
 
 432     static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
 
 433         return JSObjectMake(context, Internal_, new Internal(object, context, owner));
 
 436     id GetValue() const {
 
 437         return reinterpret_cast<id>(value_);
 
 443 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
 
 445 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
 
 446     lhs.name = apr_pstrdup(pool, rhs.name);
 
 447     if (rhs.type == NULL)
 
 450         lhs.type = new(pool) Type;
 
 451         Copy(pool, *lhs.type, *rhs.type);
 
 453     lhs.offset = rhs.offset;
 
 456 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
 
 457     size_t count(rhs.count);
 
 459     lhs.elements = new(pool) Element[count];
 
 460     for (size_t index(0); index != count; ++index)
 
 461         Copy(pool, lhs.elements[index], rhs.elements[index]);
 
 464 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
 
 465     lhs.primitive = rhs.primitive;
 
 466     lhs.name = apr_pstrdup(pool, rhs.name);
 
 467     lhs.flags = rhs.flags;
 
 469     if (sig::IsAggregate(rhs.primitive))
 
 470         Copy(pool, lhs.data.signature, rhs.data.signature);
 
 472         if (rhs.data.data.type != NULL) {
 
 473             lhs.data.data.type = new(pool) Type;
 
 474             Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
 
 477         lhs.data.data.size = rhs.data.data.size;
 
 481 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
 
 483     lhs.alignment = rhs.alignment;
 
 485     if (rhs.elements == NULL)
 
 489         while (rhs.elements[count] != NULL)
 
 492         lhs.elements = new(pool) ffi_type *[count + 1];
 
 493         lhs.elements[count] = NULL;
 
 495         for (size_t index(0); index != count; ++index) {
 
 496             // XXX: if these are libffi native then you can just take them
 
 497             ffi_type *ffi(new(pool) ffi_type);
 
 498             lhs.elements[index] = ffi;
 
 499             sig::Copy(pool, *ffi, *rhs.elements[index]);
 
 506 struct CStringMapLess :
 
 507     std::binary_function<const char *, const char *, bool>
 
 509     _finline bool operator ()(const char *lhs, const char *rhs) const {
 
 510         return strcmp(lhs, rhs) < 0;
 
 514 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
 
 519         if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
 
 520             switch ([[entry objectAtIndex:0] intValue]) {
 
 522                     sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
 
 526                     sig::Signature signature;
 
 527                     sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
 
 528                     type = signature.elements[0].type;
 
 534 struct Type_privateData :
 
 537     static Type_privateData *Object;
 
 538     static Type_privateData *Selector;
 
 543     void Set(sig::Type *type) {
 
 544         type_ = new(pool_) sig::Type;
 
 545         sig::Copy(pool_, *type_, *type);
 
 548     Type_privateData(apr_pool_t *pool, const char *type) :
 
 554         sig::Signature signature;
 
 555         sig::Parse(pool_, &signature, type, &Structor_);
 
 556         type_ = signature.elements[0].type;
 
 559     Type_privateData(sig::Type *type) :
 
 566     Type_privateData(sig::Type *type, ffi_type *ffi) {
 
 567         ffi_ = new(pool_) ffi_type;
 
 568         sig::Copy(pool_, *ffi_, *ffi);
 
 574             ffi_ = new(pool_) ffi_type;
 
 576             sig::Element element;
 
 578             element.type = type_;
 
 581             sig::Signature signature;
 
 582             signature.elements = &element;
 
 586             sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
 
 594 Type_privateData *Type_privateData::Object;
 
 595 Type_privateData *Type_privateData::Selector;
 
 597 Type_privateData *Instance::GetType() const {
 
 598     return Type_privateData::Object;
 
 601 Type_privateData *Selector_privateData::GetType() const {
 
 602     return Type_privateData::Selector;
 
 608     Type_privateData *type_;
 
 610     Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
 
 611         CYOwned(value, context, owner),
 
 612         type_(new(pool_) Type_privateData(type))
 
 617 struct Struct_privateData :
 
 620     Type_privateData *type_;
 
 622     Struct_privateData(JSContextRef context, JSObjectRef owner) :
 
 623         CYOwned(NULL, context, owner)
 
 628 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
 
 629 static TypeMap Types_;
 
 631 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
 
 632     Struct_privateData *internal(new Struct_privateData(context, owner));
 
 633     apr_pool_t *pool(internal->pool_);
 
 634     Type_privateData *typical(new(pool) Type_privateData(type, ffi));
 
 635     internal->type_ = typical;
 
 638         internal->value_ = data;
 
 640         size_t size(typical->GetFFI()->size);
 
 641         void *copy(apr_palloc(internal->pool_, size));
 
 642         memcpy(copy, data, size);
 
 643         internal->value_ = copy;
 
 646     return JSObjectMake(context, Struct_, internal);
 
 649 struct Functor_privateData :
 
 652     sig::Signature signature_;
 
 656     Functor_privateData(const char *type, void (*value)()) :
 
 657         CYValue(reinterpret_cast<void *>(value))
 
 659         sig::Parse(pool_, &signature_, type, &Structor_);
 
 660         sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
 
 663     void (*GetValue())() const {
 
 664         return reinterpret_cast<void (*)()>(value_);
 
 668 struct Closure_privateData :
 
 671     JSContextRef context_;
 
 672     JSObjectRef function_;
 
 674     Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
 
 675         Functor_privateData(type, NULL),
 
 679         JSValueProtect(context_, function_);
 
 682     virtual ~Closure_privateData() {
 
 683         JSValueUnprotect(context_, function_);
 
 687 struct Message_privateData :
 
 692     Message_privateData(SEL sel, const char *type, IMP value = NULL) :
 
 693         Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
 
 699 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
 
 700     Instance::Flags flags;
 
 703         flags = Instance::Transient;
 
 705         flags = Instance::None;
 
 706         object = [object retain];
 
 709     return Instance::Make(context, object, flags);
 
 712 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
 
 714         return [value UTF8String];
 
 716         size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
 
 717         char *string(new(pool) char[size]);
 
 718         if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
 
 719             @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
 
 724 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
 
 725     return JSValueMakeBoolean(context, value);
 
 728 JSValueRef CYCastJSValue(JSContextRef context, double value) {
 
 729     return JSValueMakeNumber(context, value);
 
 732 #define CYCastJSValue_(Type_) \
 
 733     JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
 
 734         return JSValueMakeNumber(context, static_cast<double>(value)); \
 
 738 CYCastJSValue_(unsigned int)
 
 739 CYCastJSValue_(long int)
 
 740 CYCastJSValue_(long unsigned int)
 
 741 CYCastJSValue_(long long int)
 
 742 CYCastJSValue_(long long unsigned int)
 
 744 JSValueRef CYJSUndefined(JSContextRef context) {
 
 745     return JSValueMakeUndefined(context);
 
 748 size_t CYGetIndex(const char *value) {
 
 749     if (value[0] != '0') {
 
 751         size_t index(strtoul(value, &end, 10));
 
 752         if (value + strlen(value) == end)
 
 754     } else if (value[1] == '\0')
 
 759 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
 
 760     return CYGetIndex(CYPoolCString(pool, value));
 
 763 bool CYGetOffset(const char *value, ssize_t &index) {
 
 764     if (value[0] != '0') {
 
 766         index = strtol(value, &end, 10);
 
 767         if (value + strlen(value) == end)
 
 769     } else if (value[1] == '\0') {
 
 777 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
 
 778     return CYGetOffset(CYPoolCString(pool, value), index);
 
 781 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
 
 783 @interface NSMethodSignature (Cycript)
 
 784 - (NSString *) _typeString;
 
 787 @interface NSObject (Cycript)
 
 789 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 
 790 - (JSType) cy$JSType;
 
 792 - (NSObject *) cy$toJSON:(NSString *)key;
 
 793 - (NSString *) cy$toCYON;
 
 794 - (NSString *) cy$toKey;
 
 796 - (bool) cy$hasProperty:(NSString *)name;
 
 797 - (NSObject *) cy$getProperty:(NSString *)name;
 
 798 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
 
 799 - (bool) cy$deleteProperty:(NSString *)name;
 
 804 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 
 807 @interface NSString (Cycript)
 
 808 - (void *) cy$symbol;
 
 811 struct PropertyAttributes {
 
 816     const char *variable;
 
 829     PropertyAttributes(objc_property_t property) :
 
 841         name = property_getName(property);
 
 842         const char *attributes(property_getAttributes(property));
 
 844         for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
 
 846                 case 'R': readonly = true; break;
 
 847                 case 'C': copy = true; break;
 
 848                 case '&': retain = true; break;
 
 849                 case 'N': nonatomic = true; break;
 
 850                 case 'G': getter_ = token + 1; break;
 
 851                 case 'S': setter_ = token + 1; break;
 
 852                 case 'V': variable = token + 1; break;
 
 856         /*if (variable == NULL) {
 
 857             variable = property_getName(property);
 
 858             size_t size(strlen(variable));
 
 859             char *name(new(pool_) char[size + 2]);
 
 861             memcpy(name + 1, variable, size);
 
 862             name[size + 1] = '\0';
 
 867     const char *Getter() {
 
 869             getter_ = apr_pstrdup(pool_, name);
 
 873     const char *Setter() {
 
 874         if (setter_ == NULL && !readonly) {
 
 875             size_t length(strlen(name));
 
 877             char *temp(new(pool_) char[length + 5]);
 
 883                 temp[3] = toupper(name[0]);
 
 884                 memcpy(temp + 4, name + 1, length - 1);
 
 887             temp[length + 3] = ':';
 
 888             temp[length + 4] = '\0';
 
 897 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
 
 898     return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
 
 901 /* Bridge: NSArray {{{ */
 
 902 @implementation NSArray (Cycript)
 
 904 - (NSString *) cy$toCYON {
 
 905     NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
 
 906     [json appendString:@"["];
 
 909     for (id object in self) {
 
 911             [json appendString:@","];
 
 914         if (object == nil || [object cy$JSType] != kJSTypeUndefined)
 
 915             [json appendString:CYPoolNSCYON(NULL, object)];
 
 917             [json appendString:@","];
 
 922     [json appendString:@"]"];
 
 926 - (bool) cy$hasProperty:(NSString *)name {
 
 927     if ([name isEqualToString:@"length"])
 
 930     size_t index(CYGetIndex(NULL, name));
 
 931     if (index == _not(size_t) || index >= [self count])
 
 932         return [super cy$hasProperty:name];
 
 937 - (NSObject *) cy$getProperty:(NSString *)name {
 
 938     if ([name isEqualToString:@"length"])
 
 939         return [NSNumber numberWithUnsignedInteger:[self count]];
 
 941     size_t index(CYGetIndex(NULL, name));
 
 942     if (index == _not(size_t) || index >= [self count])
 
 943         return [super cy$getProperty:name];
 
 945         return [self objectAtIndex:index];
 
 950 /* Bridge: NSDictionary {{{ */
 
 951 @implementation NSDictionary (Cycript)
 
 953 - (NSString *) cy$toCYON {
 
 954     NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
 
 955     [json appendString:@"{"];
 
 958     for (id key in self) {
 
 960             [json appendString:@","];
 
 963         [json appendString:[key cy$toKey]];
 
 964         [json appendString:@":"];
 
 965         NSObject *object([self objectForKey:key]);
 
 966         [json appendString:CYPoolNSCYON(NULL, object)];
 
 969     [json appendString:@"}"];
 
 973 - (bool) cy$hasProperty:(NSString *)name {
 
 974     return [self objectForKey:name] != nil;
 
 977 - (NSObject *) cy$getProperty:(NSString *)name {
 
 978     return [self objectForKey:name];
 
 983 /* Bridge: NSMutableArray {{{ */
 
 984 @implementation NSMutableArray (Cycript)
 
 986 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
 987     if ([name isEqualToString:@"length"]) {
 
 988         // XXX: is this not intelligent?
 
 989         NSUInteger size([(NSNumber *)value unsignedIntegerValue]);
 
 990         NSUInteger count([self count]);
 
 992             [self removeObjectsInRange:NSMakeRange(size, count - size)];
 
 993         else if (size != count) {
 
 994             WebUndefined *undefined([WebUndefined undefined]);
 
 995             for (size_t i(count); i != size; ++i)
 
 996                 [self addObject:undefined];
 
1001     size_t index(CYGetIndex(NULL, name));
 
1002     if (index == _not(size_t))
 
1003         return [super cy$setProperty:name to:value];
 
1005     id object(value ?: [NSNull null]);
 
1007     size_t count([self count]);
 
1009         [self replaceObjectAtIndex:index withObject:object];
 
1011         if (index != count) {
 
1012             WebUndefined *undefined([WebUndefined undefined]);
 
1013             for (size_t i(count); i != index; ++i)
 
1014                 [self addObject:undefined];
 
1017         [self addObject:object];
 
1023 - (bool) cy$deleteProperty:(NSString *)name {
 
1024     size_t index(CYGetIndex(NULL, name));
 
1025     if (index == _not(size_t) || index >= [self count])
 
1026         return [super cy$deleteProperty:name];
 
1027     [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
 
1033 /* Bridge: NSMutableDictionary {{{ */
 
1034 @implementation NSMutableDictionary (Cycript)
 
1036 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
1037     [self setObject:(value ?: [NSNull null]) forKey:name];
 
1041 - (bool) cy$deleteProperty:(NSString *)name {
 
1042     if ([self objectForKey:name] == nil)
 
1045         [self removeObjectForKey:name];
 
1052 /* Bridge: NSNumber {{{ */
 
1053 @implementation NSNumber (Cycript)
 
1055 - (JSType) cy$JSType {
 
1056     // XXX: this just seems stupid
 
1057     return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
 
1060 - (NSObject *) cy$toJSON:(NSString *)key {
 
1064 - (NSString *) cy$toCYON {
 
1065     return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
 
1068 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
1069     return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
 
1074 /* Bridge: NSNull {{{ */
 
1075 @implementation NSNull (Cycript)
 
1077 - (JSType) cy$JSType {
 
1081 - (NSObject *) cy$toJSON:(NSString *)key {
 
1085 - (NSString *) cy$toCYON {
 
1091 /* Bridge: NSObject {{{ */
 
1092 @implementation NSObject (Cycript)
 
1094 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
1095     return CYMakeInstance(context, self, false);
 
1098 - (JSType) cy$JSType {
 
1099     return kJSTypeObject;
 
1102 - (NSObject *) cy$toJSON:(NSString *)key {
 
1103     return [self description];
 
1106 - (NSString *) cy$toCYON {
 
1107     return [[self cy$toJSON:@""] cy$toCYON];
 
1110 - (NSString *) cy$toKey {
 
1111     return [self cy$toCYON];
 
1114 - (bool) cy$hasProperty:(NSString *)name {
 
1118 - (NSObject *) cy$getProperty:(NSString *)name {
 
1122 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
1126 - (bool) cy$deleteProperty:(NSString *)name {
 
1132 /* Bridge: NSProxy {{{ */
 
1133 @implementation NSProxy (Cycript)
 
1135 - (NSObject *) cy$toJSON:(NSString *)key {
 
1136     return [self description];
 
1139 - (NSString *) cy$toCYON {
 
1140     return [[self cy$toJSON:@""] cy$toCYON];
 
1145 /* Bridge: NSString {{{ */
 
1146 @implementation NSString (Cycript)
 
1148 - (JSType) cy$JSType {
 
1149     return kJSTypeString;
 
1152 - (NSObject *) cy$toJSON:(NSString *)key {
 
1156 - (NSString *) cy$toCYON {
 
1157     // XXX: this should use the better code from Output.cpp
 
1158     CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
 
1160     CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
 
1161     CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
 
1162     CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
 
1163     CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
 
1164     CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
 
1166     CFStringInsert(json, 0, CFSTR("\""));
 
1167     CFStringAppend(json, CFSTR("\""));
 
1169     return [reinterpret_cast<const NSString *>(json) autorelease];
 
1172 - (NSString *) cy$toKey {
 
1173     const char *value([self UTF8String]);
 
1174     size_t size(strlen(value));
 
1179     if (DigitRange_[value[0]]) {
 
1180         size_t index(CYGetIndex(NULL, self));
 
1181         if (index == _not(size_t))
 
1184         if (!WordStartRange_[value[0]])
 
1186         for (size_t i(1); i != size; ++i)
 
1187             if (!WordEndRange_[value[i]])
 
1194     return [self cy$toCYON];
 
1197 - (void *) cy$symbol {
 
1199     return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
 
1204 /* Bridge: WebUndefined {{{ */
 
1205 @implementation WebUndefined (Cycript)
 
1207 - (JSType) cy$JSType {
 
1208     return kJSTypeUndefined;
 
1211 - (NSObject *) cy$toJSON:(NSString *)key {
 
1215 - (NSString *) cy$toCYON {
 
1216     return @"undefined";
 
1219 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
1220     return CYJSUndefined(context);
 
1226 @interface CYJSObject : NSMutableDictionary {
 
1227     JSObjectRef object_;
 
1228     JSContextRef context_;
 
1231 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
 
1233 - (NSString *) cy$toJSON:(NSString *)key;
 
1235 - (NSUInteger) count;
 
1236 - (id) objectForKey:(id)key;
 
1237 - (NSEnumerator *) keyEnumerator;
 
1238 - (void) setObject:(id)object forKey:(id)key;
 
1239 - (void) removeObjectForKey:(id)key;
 
1243 @interface CYJSArray : NSMutableArray {
 
1244     JSObjectRef object_;
 
1245     JSContextRef context_;
 
1248 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
 
1250 - (NSUInteger) count;
 
1251 - (id) objectAtIndex:(NSUInteger)index;
 
1253 - (void) addObject:(id)anObject;
 
1254 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
 
1255 - (void) removeLastObject;
 
1256 - (void) removeObjectAtIndex:(NSUInteger)index;
 
1257 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
 
1261 CYRange DigitRange_    (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
 
1262 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
 
1263 CYRange WordEndRange_  (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
 
1268     @catch (id error) { \
 
1269         CYThrow(context, error, exception); \
 
1273 apr_status_t CYPoolRelease_(void *data) {
 
1274     id object(reinterpret_cast<id>(data));
 
1279 id CYPoolRelease(apr_pool_t *pool, id object) {
 
1282     else if (pool == NULL)
 
1283         return [object autorelease];
 
1285         apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
 
1290 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
 
1291     return (CFTypeRef) CYPoolRelease(pool, (id) object);
 
1294 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
 
1295     JSValueRef exception(NULL);
 
1296     bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
 
1297     CYThrow(context, exception);
 
1298     id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
 
1299     return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
 
1302 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
 
1303     if (!JSValueIsObjectOfClass(context, object, Instance_))
 
1304         return CYCastNSObject_(pool, context, object);
 
1306         Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
1307         return internal->GetValue();
 
1311 double CYCastDouble(const char *value, size_t size) {
 
1313     double number(strtod(value, &end));
 
1314     if (end != value + size)
 
1319 double CYCastDouble(const char *value) {
 
1320     return CYCastDouble(value, strlen(value));
 
1323 double CYCastDouble(JSContextRef context, JSValueRef value) {
 
1324     JSValueRef exception(NULL);
 
1325     double number(JSValueToNumber(context, value, &exception));
 
1326     CYThrow(context, exception);
 
1330 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
 
1331     double number(CYCastDouble(context, value));
 
1332     return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
 
1335 CFStringRef CYCopyCFString(const char *value) {
 
1336     return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
 
1339 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
 
1340     return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
 
1343 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
 
1344     return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
 
1347 bool CYCastBool(JSContextRef context, JSValueRef value) {
 
1348     return JSValueToBoolean(context, value);
 
1351 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
 
1355     switch (JSType type = JSValueGetType(context, value)) {
 
1356         case kJSTypeUndefined:
 
1357             object = [WebUndefined undefined];
 
1365         case kJSTypeBoolean:
 
1366             object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
 
1371             object = CYCopyCFNumber(context, value);
 
1376             object = CYCopyCFString(context, value);
 
1381             // XXX: this might could be more efficient
 
1382             object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
 
1387             @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
 
1394         return CYPoolRelease(pool, object);
 
1396         return CFRetain(object);
 
1399 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1400     return CYCFType(pool, context, value, true);
 
1403 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1404     return CYCFType(pool, context, value, false);
 
1407 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
 
1409     size_t size(JSPropertyNameArrayGetCount(names));
 
1410     NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
 
1411     for (size_t index(0); index != size; ++index)
 
1412         [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
 
1416 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1417     return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
 
1420 void CYThrow(JSContextRef context, JSValueRef value) {
 
1423     @throw CYCastNSObject(NULL, context, value);
 
1426 JSValueRef CYJSNull(JSContextRef context) {
 
1427     return JSValueMakeNull(context);
 
1430 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
 
1431     return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
 
1434 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
 
1435     return CYCastJSValue(context, CYJSString(value));
 
1438 JSValueRef CYCastJSValue(JSContextRef context, id value) {
 
1440         return CYJSNull(context);
 
1441     else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
 
1442         return [value cy$JSValueInContext:context];
 
1444         return CYMakeInstance(context, value, false);
 
1447 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
 
1448     JSValueRef exception(NULL);
 
1449     JSObjectRef object(JSValueToObject(context, value, &exception));
 
1450     CYThrow(context, exception);
 
1454 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
 
1455     if (exception == NULL)
 
1457     *exception = CYCastJSValue(context, error);
 
1460 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
 
1461     JSValueRef exception(NULL);
 
1462     JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
 
1463     CYThrow(context, exception);
 
1467 bool CYIsCallable(JSContextRef context, JSValueRef value) {
 
1468     // XXX: this isn't actually correct
 
1469     return value != NULL && JSValueIsObject(context, value);
 
1472 @implementation CYJSObject
 
1474 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
 
1475     if ((self = [super init]) != nil) {
 
1478         JSValueProtect(context_, object_);
 
1483     JSValueUnprotect(context_, object_);
 
1487 - (NSObject *) cy$toJSON:(NSString *)key {
 
1488     JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
 
1489     if (!CYIsCallable(context_, toJSON))
 
1490         return [super cy$toJSON:key];
 
1492         JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
 
1493         JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
 
1494         // XXX: do I really want an NSNull here?!
 
1495         return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1499 - (NSString *) cy$toCYON {
 
1500     JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
 
1501     if (!CYIsCallable(context_, toCYON)) super:
 
1502         return [super cy$toCYON];
 
1503     else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
 
1504         return CYCastNSString(NULL, CYJSString(context_, value));
 
1508 - (NSUInteger) count {
 
1509     JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
 
1510     size_t size(JSPropertyNameArrayGetCount(names));
 
1511     JSPropertyNameArrayRelease(names);
 
1515 - (id) objectForKey:(id)key {
 
1516     JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
 
1517     if (JSValueIsUndefined(context_, value))
 
1519     return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1522 - (NSEnumerator *) keyEnumerator {
 
1523     JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
 
1524     NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
 
1525     JSPropertyNameArrayRelease(names);
 
1529 - (void) setObject:(id)object forKey:(id)key {
 
1530     CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
 
1533 - (void) removeObjectForKey:(id)key {
 
1534     JSValueRef exception(NULL);
 
1535     (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
 
1536     CYThrow(context_, exception);
 
1541 @implementation CYJSArray
 
1543 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
 
1544     if ((self = [super init]) != nil) {
 
1547         JSValueProtect(context_, object_);
 
1552     JSValueUnprotect(context_, object_);
 
1556 - (NSUInteger) count {
 
1557     return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
 
1560 - (id) objectAtIndex:(NSUInteger)index {
 
1561     size_t bounds([self count]);
 
1562     if (index >= bounds)
 
1563         @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
 
1564     JSValueRef exception(NULL);
 
1565     JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
 
1566     CYThrow(context_, exception);
 
1567     return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1570 - (void) addObject:(id)object {
 
1571     JSValueRef exception(NULL);
 
1572     JSValueRef arguments[1];
 
1573     arguments[0] = CYCastJSValue(context_, object);
 
1574     JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
 
1575     CYThrow(context_, exception);
 
1578 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
 
1579     size_t bounds([self count] + 1);
 
1580     if (index >= bounds)
 
1581         @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
 
1582     JSValueRef exception(NULL);
 
1583     JSValueRef arguments[3];
 
1584     arguments[0] = CYCastJSValue(context_, index);
 
1585     arguments[1] = CYCastJSValue(context_, 0);
 
1586     arguments[2] = CYCastJSValue(context_, object);
 
1587     JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
 
1588     CYThrow(context_, exception);
 
1591 - (void) removeLastObject {
 
1592     JSValueRef exception(NULL);
 
1593     JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
 
1594     CYThrow(context_, exception);
 
1597 - (void) removeObjectAtIndex:(NSUInteger)index {
 
1598     size_t bounds([self count]);
 
1599     if (index >= bounds)
 
1600         @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
 
1601     JSValueRef exception(NULL);
 
1602     JSValueRef arguments[2];
 
1603     arguments[0] = CYCastJSValue(context_, index);
 
1604     arguments[1] = CYCastJSValue(context_, 1);
 
1605     JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
 
1606     CYThrow(context_, exception);
 
1609 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
 
1610     size_t bounds([self count]);
 
1611     if (index >= bounds)
 
1612         @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
 
1613     CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
 
1618 NSString *CYCopyNSCYON(id value) {
 
1624         Class _class(object_getClass(value));
 
1625         SEL sel(@selector(cy$toCYON));
 
1627         if (Method toCYON = class_getInstanceMethod(_class, sel))
 
1628             string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
 
1629         else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
 
1630             if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
 
1631                 string = [value cy$toCYON];
 
1634             if (value == NSZombie_)
 
1635                 string = @"_NSZombie_";
 
1636             else if (_class == NSZombie_)
 
1637                 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
 
1638             // XXX: frowny /in/ the pants
 
1639             else if (value == NSMessageBuilder_ || value == Object_)
 
1642                 string = [NSString stringWithFormat:@"%@", value];
 
1645         // XXX: frowny pants
 
1647             string = @"undefined";
 
1650     return [string retain];
 
1653 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
 
1654     if (JSValueIsNull(context, value))
 
1655         return [@"null" retain];
 
1659             return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
 
1664 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
 
1665     return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
 
1668 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
 
1669     if (NSString *json = CYCopyNSCYON(context, value, exception)) {
 
1670         const char *string(CYPoolCString(pool, json));
 
1676 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
 
1680     JSObjectRef object_;
 
1688         // XXX: delete object_? ;(
 
1691     static CYInternal *Get(id self) {
 
1692         CYInternal *internal(NULL);
 
1693         if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
 
1694             // XXX: do something epic? ;P
 
1700     static CYInternal *Set(id self) {
 
1701         CYInternal *internal(NULL);
 
1702         if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
 
1703             if (internal == NULL) {
 
1704                 internal = new CYInternal();
 
1705                 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
 
1708             // XXX: do something epic? ;P
 
1714     bool HasProperty(JSContextRef context, JSStringRef name) {
 
1715         if (object_ == NULL)
 
1717         return JSObjectHasProperty(context, object_, name);
 
1720     JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
 
1721         if (object_ == NULL)
 
1723         return CYGetProperty(context, object_, name);
 
1726     void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
 
1727         if (object_ == NULL)
 
1728             object_ = JSObjectMake(context, NULL, NULL);
 
1729         CYSetProperty(context, object_, name, value);
 
1733 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
 
1734     Selector_privateData *internal(new Selector_privateData(sel));
 
1735     return JSObjectMake(context, Selector_, internal);
 
1738 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
 
1739     Pointer *internal(new Pointer(pointer, context, owner, type));
 
1740     return JSObjectMake(context, Pointer_, internal);
 
1743 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
 
1744     Functor_privateData *internal(new Functor_privateData(type, function));
 
1745     return JSObjectMake(context, Functor_, internal);
 
1748 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
 
1750         const char *string([CYCastNSString(NULL, value) UTF8String]);
 
1753         size_t size(JSStringGetMaximumUTF8CStringSize(value));
 
1754         char *string(new(pool) char[size]);
 
1755         JSStringGetUTF8CString(value, string, size);
 
1760 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1761     return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
 
1764 bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
 
1765     return CYGetOffset(CYPoolCString(pool, value), index);
 
1768 // XXX: this macro is unhygenic
 
1769 #define CYCastCString(context, value) ({ \
 
1771     if (value == NULL) \
 
1773     else if (JSStringRef string = CYCopyJSString(context, value)) { \
 
1774         size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
 
1775         utf8 = reinterpret_cast<char *>(alloca(size)); \
 
1776         JSStringGetUTF8CString(string, utf8, size); \
 
1777         JSStringRelease(string); \
 
1783 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
 
1784     switch (JSValueGetType(context, value)) {
 
1787         /*case kJSTypeString:
 
1788             return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
 
1790             if (JSValueIsObjectOfClass(context, value, Pointer_)) {
 
1791                 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
 
1792                 return internal->value_;
 
1795             double number(CYCastDouble(context, value));
 
1796             if (std::isnan(number))
 
1797                 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
 
1798             return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
 
1802 template <typename Type_>
 
1803 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
 
1804     return reinterpret_cast<Type_>(CYCastPointer_(context, value));
 
1807 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
 
1808     if (JSValueIsObjectOfClass(context, value, Selector_)) {
 
1809         Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
 
1810         return reinterpret_cast<SEL>(internal->value_);
 
1812         return CYCastPointer<SEL>(context, value);
 
1815 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
 
1816     switch (type->primitive) {
 
1817         case sig::boolean_P:
 
1818             *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
 
1821 #define CYPoolFFI_(primitive, native) \
 
1822         case sig::primitive ## _P: \
 
1823             *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
 
1826         CYPoolFFI_(uchar, unsigned char)
 
1827         CYPoolFFI_(char, char)
 
1828         CYPoolFFI_(ushort, unsigned short)
 
1829         CYPoolFFI_(short, short)
 
1830         CYPoolFFI_(ulong, unsigned long)
 
1831         CYPoolFFI_(long, long)
 
1832         CYPoolFFI_(uint, unsigned int)
 
1833         CYPoolFFI_(int, int)
 
1834         CYPoolFFI_(ulonglong, unsigned long long)
 
1835         CYPoolFFI_(longlong, long long)
 
1836         CYPoolFFI_(float, float)
 
1837         CYPoolFFI_(double, double)
 
1840         case sig::typename_P:
 
1841             *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
 
1844         case sig::selector_P:
 
1845             *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
 
1848         case sig::pointer_P:
 
1849             *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
 
1853             *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
 
1856         case sig::struct_P: {
 
1857             uint8_t *base(reinterpret_cast<uint8_t *>(data));
 
1858             JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
 
1859             for (size_t index(0); index != type->data.signature.count; ++index) {
 
1860                 sig::Element *element(&type->data.signature.elements[index]);
 
1861                 ffi_type *field(ffi->elements[index]);
 
1864                 if (aggregate == NULL)
 
1867                     rhs = CYGetProperty(context, aggregate, index);
 
1868                     if (JSValueIsUndefined(context, rhs)) {
 
1869                         if (element->name != NULL)
 
1870                             rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
 
1873                         if (JSValueIsUndefined(context, rhs)) undefined:
 
1874                             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
 
1878                 CYPoolFFI(pool, context, element->type, field, base, rhs);
 
1880                 base += field->size;
 
1888             NSLog(@"CYPoolFFI(%c)\n", type->primitive);
 
1893 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
 
1896     switch (type->primitive) {
 
1897         case sig::boolean_P:
 
1898             value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
 
1901 #define CYFromFFI_(primitive, native) \
 
1902         case sig::primitive ## _P: \
 
1903             value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
 
1906         CYFromFFI_(uchar, unsigned char)
 
1907         CYFromFFI_(char, char)
 
1908         CYFromFFI_(ushort, unsigned short)
 
1909         CYFromFFI_(short, short)
 
1910         CYFromFFI_(ulong, unsigned long)
 
1911         CYFromFFI_(long, long)
 
1912         CYFromFFI_(uint, unsigned int)
 
1913         CYFromFFI_(int, int)
 
1914         CYFromFFI_(ulonglong, unsigned long long)
 
1915         CYFromFFI_(longlong, long long)
 
1916         CYFromFFI_(float, float)
 
1917         CYFromFFI_(double, double)
 
1919         case sig::object_P: {
 
1920             if (id object = *reinterpret_cast<id *>(data)) {
 
1921                 value = CYCastJSValue(context, object);
 
1927         case sig::typename_P:
 
1928             value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
 
1931         case sig::selector_P:
 
1932             if (SEL sel = *reinterpret_cast<SEL *>(data))
 
1933                 value = CYMakeSelector(context, sel);
 
1937         case sig::pointer_P:
 
1938             if (void *pointer = *reinterpret_cast<void **>(data))
 
1939                 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
 
1944             if (char *utf8 = *reinterpret_cast<char **>(data))
 
1945                 value = CYCastJSValue(context, utf8);
 
1950             value = CYMakeStruct(context, data, type, ffi, owner);
 
1954             value = CYJSUndefined(context);
 
1958             value = CYJSNull(context);
 
1962             NSLog(@"CYFromFFI(%c)\n", type->primitive);
 
1969 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
 
1970     if (Method method = class_getInstanceMethod(_class, selector)) {
 
1974         method_getReturnType(method, type, sizeof(type));
 
1979     // XXX: possibly use a more "awesome" check?
 
1983 const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
 
1985         return method_getTypeEncoding(method);
 
1986     else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
 
1987         return CYPoolCString(pool, type);
 
1992 void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
 
1993     Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
 
1995     JSContextRef context(internal->context_);
 
1997     size_t count(internal->cif_.nargs);
 
1998     JSValueRef values[count];
 
2000     for (size_t index(0); index != count; ++index)
 
2001         values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
 
2003     JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
 
2004     CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
 
2007 void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
 
2008     Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
 
2010     JSContextRef context(internal->context_);
 
2012     size_t count(internal->cif_.nargs);
 
2013     JSValueRef values[count];
 
2015     for (size_t index(0); index != count; ++index)
 
2016         values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
 
2018     JSObjectRef _this(CYCastJSObject(context, values[0]));
 
2020     JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
 
2021     CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
 
2024 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
 
2025     // XXX: in case of exceptions this will leak
 
2026     // XXX: in point of fact, this may /need/ to leak :(
 
2027     Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
 
2029     ffi_closure *closure((ffi_closure *) _syscall(mmap(
 
2030         NULL, sizeof(ffi_closure),
 
2031         PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
 
2035     ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
 
2036     _assert(status == FFI_OK);
 
2038     _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
 
2040     internal->value_ = closure;
 
2045 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
 
2046     Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
 
2047     return JSObjectMake(context, Functor_, internal);
 
2050 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
 
2051     JSValueRef exception(NULL);
 
2052     bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
 
2053     CYThrow(context, exception);
 
2056         JSObjectRef function(CYCastJSObject(context, value));
 
2057         return CYMakeFunctor(context, function, type);
 
2059         void (*function)()(CYCastPointer<void (*)()>(context, value));
 
2060         return CYMakeFunctor(context, function, type);
 
2064 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
 
2065     Message_privateData *internal(new Message_privateData(sel, type, imp));
 
2066     return JSObjectMake(context, Message_, internal);
 
2069 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
 
2070     JSObjectRef function(CYCastJSObject(context, value));
 
2071     Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
 
2072     return reinterpret_cast<IMP>(internal->GetValue());
 
2075 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
 
2076     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2077     Class _class(internal->GetValue());
 
2080     const char *name(CYPoolCString(pool, property));
 
2082     if (SEL sel = sel_getUid(name))
 
2083         if (class_getInstanceMethod(_class, sel) != NULL)
 
2089 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2090     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2091     Class _class(internal->GetValue());
 
2094     const char *name(CYPoolCString(pool, property));
 
2096     if (SEL sel = sel_getUid(name))
 
2097         if (Method method = class_getInstanceMethod(_class, sel))
 
2098             return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
 
2103 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2104     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2105     Class _class(internal->GetValue());
 
2108     const char *name(CYPoolCString(pool, property));
 
2110     SEL sel(sel_registerName(name));
 
2112     Method method(class_getInstanceMethod(_class, sel));
 
2117     if (JSValueIsObjectOfClass(context, value, Message_)) {
 
2118         Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
 
2119         type = sig::Unparse(pool, &message->signature_);
 
2120         imp = reinterpret_cast<IMP>(message->GetValue());
 
2122         type = CYPoolTypeEncoding(pool, _class, sel, method);
 
2123         imp = CYMakeMessage(context, value, type);
 
2127         method_setImplementation(method, imp);
 
2129         class_replaceMethod(_class, sel, imp, type);
 
2135 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2136     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2137     Class _class(internal->GetValue());
 
2140     const char *name(CYPoolCString(pool, property));
 
2142     if (SEL sel = sel_getUid(name))
 
2143         if (Method method = class_getInstanceMethod(_class, sel)) {
 
2144             objc_method_list list = {NULL, 1, {method}};
 
2145             class_removeMethods(_class, &list);
 
2153 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2154     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2155     Class _class(internal->GetValue());
 
2158     Method *data(class_copyMethodList(_class, &size));
 
2159     for (size_t i(0); i != size; ++i)
 
2160         JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
 
2164 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
 
2165     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2166     id self(internal->GetValue());
 
2168     if (JSStringIsEqualToUTF8CString(property, "$cyi"))
 
2172     NSString *name(CYCastNSString(pool, property));
 
2174     if (CYInternal *internal = CYInternal::Get(self))
 
2175         if (internal->HasProperty(context, property))
 
2178     Class _class(object_getClass(self));
 
2181         // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
 
2182         if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
 
2183             if ([self cy$hasProperty:name])
 
2185     } CYPoolCatch(false)
 
2187     const char *string(CYPoolCString(pool, name));
 
2189     if (class_getProperty(_class, string) != NULL)
 
2192     if (SEL sel = sel_getUid(string))
 
2193         if (CYImplements(self, _class, sel, true))
 
2199 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2200     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2201     id self(internal->GetValue());
 
2203     if (JSStringIsEqualToUTF8CString(property, "$cyi"))
 
2204         return Internal::Make(context, self, object);
 
2208         NSString *name(CYCastNSString(pool, property));
 
2210         if (CYInternal *internal = CYInternal::Get(self))
 
2211             if (JSValueRef value = internal->GetProperty(context, property))
 
2215             if (NSObject *data = [self cy$getProperty:name])
 
2216                 return CYCastJSValue(context, data);
 
2219         const char *string(CYPoolCString(pool, name));
 
2220         Class _class(object_getClass(self));
 
2222         if (objc_property_t property = class_getProperty(_class, string)) {
 
2223             PropertyAttributes attributes(property);
 
2224             SEL sel(sel_registerName(attributes.Getter()));
 
2225             return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
 
2228         if (SEL sel = sel_getUid(string))
 
2229             if (CYImplements(self, _class, sel, true))
 
2230                 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
 
2236 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2237     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2238     id self(internal->GetValue());
 
2243         NSString *name(CYCastNSString(pool, property));
 
2244         NSString *data(CYCastNSObject(pool, context, value));
 
2247             if ([self cy$setProperty:name to:data])
 
2251         const char *string(CYPoolCString(pool, name));
 
2252         Class _class(object_getClass(self));
 
2254         if (objc_property_t property = class_getProperty(_class, string)) {
 
2255             PropertyAttributes attributes(property);
 
2256             if (const char *setter = attributes.Setter()) {
 
2257                 SEL sel(sel_registerName(setter));
 
2258                 JSValueRef arguments[1] = {value};
 
2259                 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
 
2264         size_t length(strlen(string));
 
2266         char set[length + 5];
 
2272         if (string[0] != '\0') {
 
2273             set[3] = toupper(string[0]);
 
2274             memcpy(set + 4, string + 1, length - 1);
 
2277         set[length + 3] = ':';
 
2278         set[length + 4] = '\0';
 
2280         if (SEL sel = sel_getUid(set))
 
2281             if (CYImplements(self, _class, sel, false)) {
 
2282                 JSValueRef arguments[1] = {value};
 
2283                 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
 
2286         if (CYInternal *internal = CYInternal::Set(self)) {
 
2287             internal->SetProperty(context, property, value);
 
2295 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2296     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2297     id self(internal->GetValue());
 
2301             NSString *name(CYCastNSString(NULL, property));
 
2302             return [self cy$deleteProperty:name];
 
2307 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2308     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2309     id self(internal->GetValue());
 
2312     Class _class(object_getClass(self));
 
2316         objc_property_t *data(class_copyPropertyList(_class, &size));
 
2317         for (size_t i(0); i != size; ++i)
 
2318             JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
 
2323 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2325         Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2326         JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
 
2331 bool CYIsClass(id self) {
 
2332     // XXX: this is a lame object_isClass
 
2333     return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
 
2336 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
 
2337     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
 
2338     Class _class(internal->GetValue());
 
2339     if (!CYIsClass(_class))
 
2342     if (JSValueIsObjectOfClass(context, instance, Instance_)) {
 
2343         Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
 
2344         // XXX: this isn't always safe
 
2346             return [linternal->GetValue() isKindOfClass:_class];
 
2353 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
 
2354     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2357     id self(internal->GetValue());
 
2358     const char *name(CYPoolCString(pool, property));
 
2360     if (object_getInstanceVariable(self, name, NULL) != NULL)
 
2366 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2367     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2371         id self(internal->GetValue());
 
2372         const char *name(CYPoolCString(pool, property));
 
2374         if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
 
2375             Type_privateData type(pool, ivar_getTypeEncoding(ivar));
 
2376             return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
 
2383 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2384     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2388         id self(internal->GetValue());
 
2389         const char *name(CYPoolCString(pool, property));
 
2391         if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
 
2392             Type_privateData type(pool, ivar_getTypeEncoding(ivar));
 
2393             CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
 
2401 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
 
2402     if (Class super = class_getSuperclass(_class))
 
2403         Internal_getPropertyNames_(super, names);
 
2406     Ivar *data(class_copyIvarList(_class, &size));
 
2407     for (size_t i(0); i != size; ++i)
 
2408         JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
 
2412 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2413     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2416     id self(internal->GetValue());
 
2417     Class _class(object_getClass(self));
 
2419     Internal_getPropertyNames_(_class, names);
 
2422 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2423     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2424     return internal->GetOwner();
 
2427 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
 
2428     Type_privateData *typical(internal->type_);
 
2429     sig::Type *type(typical->type_);
 
2433     const char *name(CYPoolCString(pool, property));
 
2434     size_t length(strlen(name));
 
2435     double number(CYCastDouble(name, length));
 
2437     size_t count(type->data.signature.count);
 
2439     if (std::isnan(number)) {
 
2440         if (property == NULL)
 
2443         sig::Element *elements(type->data.signature.elements);
 
2445         for (size_t local(0); local != count; ++local) {
 
2446             sig::Element *element(&elements[local]);
 
2447             if (element->name != NULL && strcmp(name, element->name) == 0) {
 
2455         index = static_cast<ssize_t>(number);
 
2456         if (index != number || index < 0 || static_cast<size_t>(index) >= count)
 
2461     ffi_type **elements(typical->GetFFI()->elements);
 
2463     base = reinterpret_cast<uint8_t *>(internal->value_);
 
2464     for (ssize_t local(0); local != index; ++local)
 
2465         base += elements[local]->size;
 
2470 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
 
2471     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
2472     Type_privateData *typical(internal->type_);
 
2474     ffi_type *ffi(typical->GetFFI());
 
2476     uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
 
2477     base += ffi->size * index;
 
2479     JSObjectRef owner(internal->GetOwner() ?: object);
 
2482         return CYFromFFI(context, typical->type_, ffi, base, false, owner);
 
2486 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2488     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
2489     Type_privateData *typical(internal->type_);
 
2491     if (typical->type_ == NULL)
 
2495     if (!CYGetOffset(pool, property, offset))
 
2498     return Pointer_getIndex(context, object, offset, exception);
 
2501 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2502     return Pointer_getIndex(context, object, 0, exception);
 
2505 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
 
2506     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
2507     Type_privateData *typical(internal->type_);
 
2509     ffi_type *ffi(typical->GetFFI());
 
2511     uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
 
2512     base += ffi->size * index;
 
2515         CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
 
2520 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2522     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
2523     Type_privateData *typical(internal->type_);
 
2525     if (typical->type_ == NULL)
 
2529     if (!CYGetOffset(pool, property, offset))
 
2532     return Pointer_setIndex(context, object, offset, value, exception);
 
2535 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2536     return Pointer_setIndex(context, object, 0, value, exception);
 
2539 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2540     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
 
2541     Type_privateData *typical(internal->type_);
 
2542     return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
 
2545 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2547     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
2548     Type_privateData *typical(internal->type_);
 
2553     if (!Index_(pool, internal, property, index, base))
 
2556     JSObjectRef owner(internal->GetOwner() ?: object);
 
2559         return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
 
2563 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2565     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
2566     Type_privateData *typical(internal->type_);
 
2571     if (!Index_(pool, internal, property, index, base))
 
2575         CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
 
2580 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2581     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
2582     Type_privateData *typical(internal->type_);
 
2583     sig::Type *type(typical->type_);
 
2588     size_t count(type->data.signature.count);
 
2589     sig::Element *elements(type->data.signature.elements);
 
2593     for (size_t index(0); index != count; ++index) {
 
2595         name = elements[index].name;
 
2598             sprintf(number, "%lu", index);
 
2602         JSPropertyNameAccumulatorAddName(names, CYJSString(name));
 
2606 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)()) {
 
2608         if (setups + count != signature->count - 1)
 
2609             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
 
2611         size_t size(setups + count);
 
2613         memcpy(values, setup, sizeof(void *) * setups);
 
2615         for (size_t index(setups); index != size; ++index) {
 
2616             sig::Element *element(&signature->elements[index + 1]);
 
2617             ffi_type *ffi(cif->arg_types[index]);
 
2619             values[index] = new(pool) uint8_t[ffi->size];
 
2620             CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
 
2623         uint8_t value[cif->rtype->size];
 
2624         ffi_call(cif, function, value, values);
 
2626         return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
 
2630 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2633         NSString *name(CYCastNSString(pool, property));
 
2634         if (Class _class = NSClassFromString(name))
 
2635             return CYMakeInstance(context, _class, true);
 
2640 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2641     size_t size(objc_getClassList(NULL, 0));
 
2642     Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
 
2645     size_t writ(objc_getClassList(data, size));
 
2648         if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
 
2654     for (size_t i(0); i != writ; ++i)
 
2655         JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
 
2661 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2662     const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
 
2666         const char *name(CYPoolCString(pool, property));
 
2668         const char **data(objc_copyClassNamesForImage(internal, &size));
 
2670         for (size_t i(0); i != size; ++i)
 
2671             if (strcmp(name, data[i]) == 0) {
 
2672                 if (Class _class = objc_getClass(name)) {
 
2673                     value = CYMakeInstance(context, _class, true);
 
2685 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2686     const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
 
2688     const char **data(objc_copyClassNamesForImage(internal, &size));
 
2689     for (size_t i(0); i != size; ++i)
 
2690         JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
 
2694 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2697         const char *name(CYPoolCString(pool, property));
 
2699         const char **data(objc_copyImageNames(&size));
 
2700         for (size_t i(0); i != size; ++i)
 
2701             if (strcmp(name, data[i]) == 0) {
 
2710         JSObjectRef value(JSObjectMake(context, NULL, NULL));
 
2711         CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
 
2716 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2718     const char **data(objc_copyImageNames(&size));
 
2719     for (size_t i(0); i != size; ++i)
 
2720         JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
 
2724 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2727         NSString *name(CYCastNSString(pool, property));
 
2728         if (Protocol *protocol = NSProtocolFromString(name))
 
2729             return CYMakeInstance(context, protocol, true);
 
2734 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2736     Protocol **data(objc_copyProtocolList(&size));
 
2737     for (size_t i(0); i != size; ++i)
 
2738         JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
 
2742 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2743     if (JSStringIsEqualToUTF8CString(property, "nil"))
 
2744         return Instance::Make(context, nil);
 
2748         NSString *name(CYCastNSString(pool, property));
 
2749         if (Class _class = NSClassFromString(name))
 
2750             return CYMakeInstance(context, _class, true);
 
2751         if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
 
2752             switch ([[entry objectAtIndex:0] intValue]) {
 
2754                     return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
 
2756                     return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
 
2758                     // XXX: this is horrendously inefficient
 
2759                     sig::Signature signature;
 
2760                     sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
 
2762                     sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
 
2763                     return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
 
2769 bool stret(ffi_type *ffi_type) {
 
2770     return ffi_type->type == FFI_TYPE_STRUCT && (
 
2771         ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
 
2772         struct_forward_array[ffi_type->size] != 0
 
2777     int *_NSGetArgc(void);
 
2778     char ***_NSGetArgv(void);
 
2779     int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
 
2782 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2784         NSLog(@"%s", CYCastCString(context, arguments[0]));
 
2785         return CYJSUndefined(context);
 
2789 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
 
2792     Class _class(object_getClass(self));
 
2793     if (Method method = class_getInstanceMethod(_class, _cmd))
 
2794         type = method_getTypeEncoding(method);
 
2798                 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
 
2800                     @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
 
2801                 type = CYPoolCString(pool, [method _typeString]);
 
2810     sig::Signature signature;
 
2811     sig::Parse(pool, &signature, type, &Structor_);
 
2814     sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
 
2816     void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
 
2817     return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
 
2820 static size_t Nonce_(0);
 
2822 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2824     sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
 
2825     return CYCastJSValue(context, name);
 
2828 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2838             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
 
2840         if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
 
2841             Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
 
2842             self = internal->GetValue();
 
2843             uninitialized = internal->IsUninitialized();
 
2845                 internal->value_ = nil;
 
2847             self = CYCastNSObject(pool, context, arguments[0]);
 
2848             uninitialized = false;
 
2852             return CYJSNull(context);
 
2854         _cmd = CYCastSEL(context, arguments[1]);
 
2857     return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
 
2860 /* Hook: objc_registerClassPair {{{ */
 
2861 // XXX: replace this with associated objects
 
2863 MSHook(void, CYDealloc, id self, SEL sel) {
 
2864     CYInternal *internal;
 
2865     object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
 
2866     if (internal != NULL)
 
2868     _CYDealloc(self, sel);
 
2871 MSHook(void, objc_registerClassPair, Class _class) {
 
2872     Class super(class_getSuperclass(_class));
 
2873     if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
 
2874         class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
 
2875         MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
 
2878     _objc_registerClassPair(_class);
 
2881 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2884             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
 
2886         Class _class(CYCastNSObject(pool, context, arguments[0]));
 
2887         $objc_registerClassPair(_class);
 
2888         return CYJSUndefined(context);
 
2893 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2894     JSValueRef setup[count + 2];
 
2897     memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
 
2898     return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
 
2901 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2903     Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
 
2905     // XXX: handle Instance::Uninitialized?
 
2906     id self(CYCastNSObject(pool, context, _this));
 
2910     setup[1] = &internal->sel_;
 
2912     return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
 
2915 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2917     Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
 
2918     return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
 
2921 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2924             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
 
2925         const char *name(CYCastCString(context, arguments[0]));
 
2926         return CYMakeSelector(context, sel_registerName(name));
 
2930 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2933             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
 
2935         void *value(CYCastPointer<void *>(context, arguments[0]));
 
2936         const char *type(CYCastCString(context, arguments[1]));
 
2940         sig::Signature signature;
 
2941         sig::Parse(pool, &signature, type, &Structor_);
 
2943         return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
 
2947 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
 
2948     Type_privateData *internal(new Type_privateData(NULL, type));
 
2949     return JSObjectMake(context, Type_, internal);
 
2952 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2955             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
 
2956         const char *type(CYCastCString(context, arguments[0]));
 
2957         return CYMakeType(context, object, type);
 
2961 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2964             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
 
2965         Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
 
2966         sig::Type *type(internal->type_);
 
2967         ffi_type *ffi(internal->GetFFI());
 
2969         uint8_t value[ffi->size];
 
2971         CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
 
2972         return CYFromFFI(context, type, ffi, value);
 
2976 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2979             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
 
2980         Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
 
2981         size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
 
2983         void *value(malloc(internal->GetFFI()->size * size));
 
2984         return CYMakePointer(context, value, internal->type_, internal->ffi_, NULL);
 
2988 JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2991             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
 
2992         id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
 
2993         return Instance::Make(context, self);
 
2997 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3000             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
 
3001         const char *type(CYCastCString(context, arguments[1]));
 
3002         return CYMakeFunctor(context, arguments[0], type);
 
3006 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3007     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
 
3008     return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
 
3011 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3012     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
3013     Type_privateData *typical(internal->GetType());
 
3018     if (typical == NULL) {
 
3022         type = typical->type_;
 
3023         ffi = typical->ffi_;
 
3026     return CYMakePointer(context, &internal->value_, type, ffi, object);
 
3029 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3030     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
3033         return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
 
3037 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3038     return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
 
3041 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3042     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
3044     sprintf(string, "%p", internal->value_);
 
3047         return CYCastJSValue(context, string);
 
3051 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3052     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
3053     return Instance::Make(context, object_getClass(internal->GetValue()));
 
3056 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3057     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
3058     id self(internal->GetValue());
 
3059     if (!CYIsClass(self))
 
3060         return CYJSUndefined(context);
 
3062         return CYGetClassPrototype(context, self);
 
3066 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3067     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
3068     id self(internal->GetValue());
 
3069     if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
 
3070         return CYJSUndefined(context);
 
3071     return Messages::Make(context, self);
 
3074 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3075     if (!JSValueIsObjectOfClass(context, _this, Instance_))
 
3078     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
3082             return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
 
3087 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3088     if (!JSValueIsObjectOfClass(context, _this, Instance_))
 
3091     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
3095             NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
 
3096             // XXX: check for support of cy$toJSON?
 
3097             return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
 
3102 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3103     if (!JSValueIsObjectOfClass(context, _this, Instance_))
 
3106     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
3110             return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
 
3115 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3116     Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
3119         return CYCastJSValue(context, sel_getName(internal->GetValue()));
 
3123 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3124     return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
 
3127 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3128     Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
3129     const char *name(sel_getName(internal->GetValue()));
 
3133             return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
 
3138 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3141             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
 
3143         Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
3144         Class _class(CYCastNSObject(pool, context, arguments[0]));
 
3145         SEL sel(internal->GetValue());
 
3146         Method method(class_getInstanceMethod(_class, sel));
 
3147         const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
 
3148         return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
 
3152 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3154         Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
 
3156         const char *type(sig::Unparse(pool, internal->type_));
 
3158             return CYCastJSValue(context, CYJSString(type));
 
3163 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3165         Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
 
3167         const char *type(sig::Unparse(pool, internal->type_));
 
3169             return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
 
3174 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3175     return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
 
3178 static JSStaticValue CYValue_staticValues[2] = {
 
3179     {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
 
3180     {NULL, NULL, NULL, 0}
 
3183 static JSStaticValue Pointer_staticValues[2] = {
 
3184     {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3185     {NULL, NULL, NULL, 0}
 
3188 static JSStaticFunction Pointer_staticFunctions[4] = {
 
3189     {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3190     {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3191     {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3195 static JSStaticFunction Struct_staticFunctions[2] = {
 
3196     {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3200 static JSStaticFunction Functor_staticFunctions[4] = {
 
3201     {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3202     {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3203     {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3207 static JSStaticValue Instance_staticValues[5] = {
 
3208     {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3209     {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3210     {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3211     {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3212     {NULL, NULL, NULL, 0}
 
3215 static JSStaticFunction Instance_staticFunctions[5] = {
 
3216     {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3217     {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3218     {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3219     {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3223 static JSStaticFunction Internal_staticFunctions[2] = {
 
3224     {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3228 static JSStaticFunction Selector_staticFunctions[5] = {
 
3229     {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3230     {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3231     {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3232     {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3236 static JSStaticFunction Type_staticFunctions[4] = {
 
3237     {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3238     {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3239     {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3243 CYDriver::CYDriver(const std::string &filename) :
 
3248     filename_(filename),
 
3254 CYDriver::~CYDriver() {
 
3258 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
 
3259     CYDriver::Error error;
 
3260     error.location_ = location;
 
3261     error.message_ = message;
 
3262     driver.errors_.push_back(error);
 
3265 void CYSetArgs(int argc, const char *argv[]) {
 
3266     JSContextRef context(CYGetJSContext());
 
3267     JSValueRef args[argc];
 
3268     for (int i(0); i != argc; ++i)
 
3269         args[i] = CYCastJSValue(context, argv[i]);
 
3270     JSValueRef exception(NULL);
 
3271     JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
 
3272     CYThrow(context, exception);
 
3273     CYSetProperty(context, System_, CYJSString("args"), array);
 
3276 JSObjectRef CYGetGlobalObject(JSContextRef context) {
 
3277     return JSContextGetGlobalObject(context);
 
3280 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
 
3281     JSContextRef context(CYGetJSContext());
 
3282     JSValueRef exception(NULL), result;
 
3285         result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
 
3286     } catch (const char *error) {
 
3290     if (exception != NULL) { error:
 
3295     if (JSValueIsUndefined(context, result))
 
3301         json = CYPoolCCYON(pool, context, result, &exception);
 
3302     } catch (const char *error) {
 
3306     if (exception != NULL)
 
3309     CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
 
3313 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
 
3314     while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
 
3322 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
 
3323     while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
 
3335     const char * volatile data_;
 
3338 // XXX: this is "tre lame"
 
3339 @interface CYClient_ : NSObject {
 
3342 - (void) execute:(NSValue *)value;
 
3346 @implementation CYClient_
 
3348 - (void) execute:(NSValue *)value {
 
3349     CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
 
3350     const char *data(execute->data_);
 
3351     execute->data_ = NULL;
 
3352     execute->data_ = CYExecute(execute->pool_, data);
 
3361     apr_thread_t *thread_;
 
3363     CYClient(int socket) :
 
3369         _syscall(close(socket_));
 
3372     void Handle() { _pooled
 
3373         CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
 
3377             if (!CYRecvAll(socket_, &size, sizeof(size)))
 
3381             char *data(new(pool) char[size + 1]);
 
3382             if (!CYRecvAll(socket_, data, size))
 
3386             CYDriver driver("");
 
3387             cy::parser parser(driver);
 
3389             driver.data_ = data;
 
3390             driver.size_ = size;
 
3393             if (parser.parse() != 0 || !driver.errors_.empty()) {
 
3395                 size = _not(size_t);
 
3397                 std::ostringstream str;
 
3398                 driver.source_->Show(str);
 
3399                 std::string code(str.str());
 
3400                 CYExecute_ execute = {pool, code.c_str()};
 
3401                 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
 
3402                 json = execute.data_;
 
3403                 size = json == NULL ? _not(size_t) : strlen(json);
 
3406             if (!CYSendAll(socket_, &size, sizeof(size)))
 
3409                 if (!CYSendAll(socket_, json, size))
 
3415 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
 
3416     CYClient *client(reinterpret_cast<CYClient *>(data));
 
3422 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
 
3423     CYClient *client(new(pool) CYClient(socket));
 
3424     apr_threadattr_t *attr;
 
3425     _aprcall(apr_threadattr_create(&attr, client->pool_));
 
3426     _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
 
3429 MSInitialize { _pooled
 
3430     _aprcall(apr_initialize());
 
3431     _aprcall(apr_pool_create(&Pool_, NULL));
 
3433     Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
 
3434     Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
 
3436     Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
 
3438     NSArray_ = objc_getClass("NSArray");
 
3439     NSCFBoolean_ = objc_getClass("NSCFBoolean");
 
3440     NSCFType_ = objc_getClass("NSCFType");
 
3441     NSDictionary_ = objc_getClass("NSDictonary");
 
3442     NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
 
3443     NSZombie_ = objc_getClass("_NSZombie_");
 
3444     Object_ = objc_getClass("Object");
 
3447 JSGlobalContextRef CYGetJSContext() {
 
3448     if (Context_ == NULL) {
 
3449         JSClassDefinition definition;
 
3451         definition = kJSClassDefinitionEmpty;
 
3452         definition.className = "Functor";
 
3453         definition.staticFunctions = Functor_staticFunctions;
 
3454         definition.callAsFunction = &Functor_callAsFunction;
 
3455         definition.finalize = &Finalize;
 
3456         Functor_ = JSClassCreate(&definition);
 
3458         definition = kJSClassDefinitionEmpty;
 
3459         definition.className = "Instance";
 
3460         definition.staticValues = Instance_staticValues;
 
3461         definition.staticFunctions = Instance_staticFunctions;
 
3462         definition.hasProperty = &Instance_hasProperty;
 
3463         definition.getProperty = &Instance_getProperty;
 
3464         definition.setProperty = &Instance_setProperty;
 
3465         definition.deleteProperty = &Instance_deleteProperty;
 
3466         definition.getPropertyNames = &Instance_getPropertyNames;
 
3467         definition.callAsConstructor = &Instance_callAsConstructor;
 
3468         definition.hasInstance = &Instance_hasInstance;
 
3469         definition.finalize = &Finalize;
 
3470         Instance_ = JSClassCreate(&definition);
 
3472         definition = kJSClassDefinitionEmpty;
 
3473         definition.className = "Internal";
 
3474         definition.staticFunctions = Internal_staticFunctions;
 
3475         definition.hasProperty = &Internal_hasProperty;
 
3476         definition.getProperty = &Internal_getProperty;
 
3477         definition.setProperty = &Internal_setProperty;
 
3478         definition.getPropertyNames = &Internal_getPropertyNames;
 
3479         definition.finalize = &Finalize;
 
3480         Internal_ = JSClassCreate(&definition);
 
3482         definition = kJSClassDefinitionEmpty;
 
3483         definition.className = "Message";
 
3484         definition.staticFunctions = Functor_staticFunctions;
 
3485         definition.callAsFunction = &Message_callAsFunction;
 
3486         definition.finalize = &Finalize;
 
3487         Message_ = JSClassCreate(&definition);
 
3489         definition = kJSClassDefinitionEmpty;
 
3490         definition.className = "Messages";
 
3491         definition.hasProperty = &Messages_hasProperty;
 
3492         definition.getProperty = &Messages_getProperty;
 
3493         definition.setProperty = &Messages_setProperty;
 
3495         definition.deleteProperty = &Messages_deleteProperty;
 
3497         definition.getPropertyNames = &Messages_getPropertyNames;
 
3498         definition.finalize = &Finalize;
 
3499         Messages_ = JSClassCreate(&definition);
 
3501         definition = kJSClassDefinitionEmpty;
 
3502         definition.className = "NSArrayPrototype";
 
3503         //definition.hasProperty = &NSArrayPrototype_hasProperty;
 
3504         //definition.getProperty = &NSArrayPrototype_getProperty;
 
3505         //definition.setProperty = &NSArrayPrototype_setProperty;
 
3506         //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
 
3507         //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
 
3508         NSArrayPrototype_ = JSClassCreate(&definition);
 
3510         definition = kJSClassDefinitionEmpty;
 
3511         definition.className = "Pointer";
 
3512         definition.staticValues = Pointer_staticValues;
 
3513         definition.staticFunctions = Pointer_staticFunctions;
 
3514         definition.getProperty = &Pointer_getProperty;
 
3515         definition.setProperty = &Pointer_setProperty;
 
3516         definition.finalize = &Finalize;
 
3517         Pointer_ = JSClassCreate(&definition);
 
3519         definition = kJSClassDefinitionEmpty;
 
3520         definition.className = "Selector";
 
3521         definition.staticValues = CYValue_staticValues;
 
3522         definition.staticFunctions = Selector_staticFunctions;
 
3523         definition.callAsFunction = &Selector_callAsFunction;
 
3524         definition.finalize = &Finalize;
 
3525         Selector_ = JSClassCreate(&definition);
 
3527         definition = kJSClassDefinitionEmpty;
 
3528         definition.className = "Struct";
 
3529         definition.staticFunctions = Struct_staticFunctions;
 
3530         definition.getProperty = &Struct_getProperty;
 
3531         definition.setProperty = &Struct_setProperty;
 
3532         definition.getPropertyNames = &Struct_getPropertyNames;
 
3533         definition.finalize = &Finalize;
 
3534         Struct_ = JSClassCreate(&definition);
 
3536         definition = kJSClassDefinitionEmpty;
 
3537         definition.className = "Type";
 
3538         definition.staticFunctions = Type_staticFunctions;
 
3539         //definition.getProperty = &Type_getProperty;
 
3540         definition.callAsFunction = &Type_callAsFunction;
 
3541         definition.callAsConstructor = &Type_callAsConstructor;
 
3542         definition.finalize = &Finalize;
 
3543         Type_ = JSClassCreate(&definition);
 
3545         definition = kJSClassDefinitionEmpty;
 
3546         definition.className = "Runtime";
 
3547         definition.getProperty = &Runtime_getProperty;
 
3548         Runtime_ = JSClassCreate(&definition);
 
3550         definition = kJSClassDefinitionEmpty;
 
3551         definition.className = "ObjectiveC::Classes";
 
3552         definition.getProperty = &ObjectiveC_Classes_getProperty;
 
3553         definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
 
3554         ObjectiveC_Classes_ = JSClassCreate(&definition);
 
3556         definition = kJSClassDefinitionEmpty;
 
3557         definition.className = "ObjectiveC::Images";
 
3558         definition.getProperty = &ObjectiveC_Images_getProperty;
 
3559         definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
 
3560         ObjectiveC_Images_ = JSClassCreate(&definition);
 
3562         definition = kJSClassDefinitionEmpty;
 
3563         definition.className = "ObjectiveC::Image::Classes";
 
3564         definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
 
3565         definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
 
3566         ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
 
3568         definition = kJSClassDefinitionEmpty;
 
3569         definition.className = "ObjectiveC::Protocols";
 
3570         definition.getProperty = &ObjectiveC_Protocols_getProperty;
 
3571         definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
 
3572         ObjectiveC_Protocols_ = JSClassCreate(&definition);
 
3574         definition = kJSClassDefinitionEmpty;
 
3575         //definition.getProperty = &Global_getProperty;
 
3576         JSClassRef Global(JSClassCreate(&definition));
 
3578         JSGlobalContextRef context(JSGlobalContextCreate(Global));
 
3581         JSObjectRef global(CYGetGlobalObject(context));
 
3583         JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
 
3584         ObjectiveC_ = JSObjectMake(context, NULL, NULL);
 
3585         CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
 
3587         CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
 
3588         CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
 
3589         CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
 
3591         Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
 
3592         Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
 
3593         String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
 
3595         length_ = JSStringCreateWithUTF8CString("length");
 
3596         message_ = JSStringCreateWithUTF8CString("message");
 
3597         name_ = JSStringCreateWithUTF8CString("name");
 
3598         prototype_ = JSStringCreateWithUTF8CString("prototype");
 
3599         toCYON_ = JSStringCreateWithUTF8CString("toCYON");
 
3600         toJSON_ = JSStringCreateWithUTF8CString("toJSON");
 
3602         JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
 
3603         Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
 
3605         Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
 
3606         Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
 
3607         Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
 
3608         Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
 
3610         JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
 
3611         JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
 
3612         JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
 
3613         JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
 
3615         Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
 
3617         JSValueRef function(CYGetProperty(context, Function_, prototype_));
 
3618         JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
 
3619         JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
 
3620         JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
 
3622         CYSetProperty(context, global, CYJSString("Functor"), Functor);
 
3623         CYSetProperty(context, global, CYJSString("Instance"), Instance);
 
3624         CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
 
3625         CYSetProperty(context, global, CYJSString("Selector"), Selector);
 
3626         CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
 
3628         MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
 
3630         class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
 
3632         CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
 
3633         CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
 
3634         CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
 
3636         System_ = JSObjectMake(context, NULL, NULL);
 
3637         CYSetProperty(context, global, CYJSString("system"), System_);
 
3638         CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
 
3639         //CYSetProperty(context, System_, CYJSString("global"), global);
 
3641         CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
 
3643         Result_ = JSStringCreateWithUTF8CString("_");
 
3645         JSValueProtect(context, Array_);
 
3646         JSValueProtect(context, Function_);
 
3647         JSValueProtect(context, String_);
 
3649         JSValueProtect(context, Instance_prototype_);
 
3650         JSValueProtect(context, Object_prototype_);
 
3652         JSValueProtect(context, Array_prototype_);
 
3653         JSValueProtect(context, Array_pop_);
 
3654         JSValueProtect(context, Array_push_);
 
3655         JSValueProtect(context, Array_splice_);