1 /* Cycript - Remote Execution Server and Disassembler
 
   2  * Copyright (C) 2009  Jay Freeman (saurik)
 
   5 /* Modified BSD License {{{ */
 
   7  *        Redistribution and use in source and binary
 
   8  * forms, with or without modification, are permitted
 
   9  * provided that the following conditions are met:
 
  11  * 1. Redistributions of source code must retain the
 
  12  *    above copyright notice, this list of conditions
 
  13  *    and the following disclaimer.
 
  14  * 2. Redistributions in binary form must reproduce the
 
  15  *    above copyright notice, this list of conditions
 
  16  *    and the following disclaimer in the documentation
 
  17  *    and/or other materials provided with the
 
  19  * 3. The name of the author may not be used to endorse
 
  20  *    or promote products derived from this software
 
  21  *    without specific prior written permission.
 
  23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
 
  24  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
 
  25  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 
  26  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 
  27  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
 
  28  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 
  29  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 
  30  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 
  31  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 
  32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 
  33  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 
  34  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 
  35  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 
  36  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
  40 #include <substrate.h>
 
  43 #include "cycript.hpp"
 
  45 #include "sig/parse.hpp"
 
  46 #include "sig/ffi_type.hpp"
 
  48 #include "Pooling.hpp"
 
  52 #include <CoreFoundation/CoreFoundation.h>
 
  53 #include <CoreFoundation/CFLogUtilities.h>
 
  54 #include <JavaScriptCore/JSStringRefCF.h>
 
  55 #include <WebKit/WebScriptObject.h>
 
  58 #include <Foundation/Foundation.h>
 
  63 #include <ext/stdio_filebuf.h>
 
  71 #include "Cycript.tab.hh"
 
  73 #include <apr_thread_proc.h>
 
  78 #define _assert(test) do { \
 
  80         @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
 
  83 #define _trace() do { \
 
  84     fprintf(stderr, "_trace():%u\n", __LINE__); \
 
  89     NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
 
  91 #define CYPoolCatch(value) \
 
  92     @catch (NSException *error) { \
 
  93         _saved = [error retain]; \
 
  99             [_saved autorelease]; \
 
 104 #define class_getSuperclass GSObjCSuper
 
 105 #define object_getClass GSObjCClass
 
 108 void CYThrow(JSContextRef context, JSValueRef value);
 
 110 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception);
 
 111 JSStringRef CYCopyJSString(const char *value);
 
 113 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value);
 
 115 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)());
 
 116 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
 
 118 /* JavaScript Properties {{{ */
 
 119 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
 
 120     JSValueRef exception(NULL);
 
 121     JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
 
 122     CYThrow(context, exception);
 
 126 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
 
 127     JSValueRef exception(NULL);
 
 128     JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
 
 129     CYThrow(context, exception);
 
 133 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
 
 134     JSValueRef exception(NULL);
 
 135     JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
 
 136     CYThrow(context, exception);
 
 139 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
 
 140     JSValueRef exception(NULL);
 
 141     JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
 
 142     CYThrow(context, exception);
 
 145 /* JavaScript Strings {{{ */
 
 146 JSStringRef CYCopyJSString(const char *value) {
 
 147     return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
 
 150 JSStringRef CYCopyJSString(JSStringRef value) {
 
 151     return value == NULL ? NULL : JSStringRetain(value);
 
 154 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
 
 155     if (JSValueIsNull(context, value))
 
 157     JSValueRef exception(NULL);
 
 158     JSStringRef string(JSValueToStringCopy(context, value, &exception));
 
 159     CYThrow(context, exception);
 
 169             JSStringRelease(string_);
 
 173     CYJSString(const CYJSString &rhs) :
 
 174         string_(CYCopyJSString(rhs.string_))
 
 178     template <typename Arg0_>
 
 179     CYJSString(Arg0_ arg0) :
 
 180         string_(CYCopyJSString(arg0))
 
 184     template <typename Arg0_, typename Arg1_>
 
 185     CYJSString(Arg0_ arg0, Arg1_ arg1) :
 
 186         string_(CYCopyJSString(arg0, arg1))
 
 190     CYJSString &operator =(const CYJSString &rhs) {
 
 192         string_ = CYCopyJSString(rhs.string_);
 
 205     operator JSStringRef() const {
 
 211 // XXX: this macro is unhygenic
 
 212 #define CYCastCString_(string) ({ \
 
 214     if (string == NULL) \
 
 217         size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
 
 218         utf8 = reinterpret_cast<char *>(alloca(size)); \
 
 219         JSStringGetUTF8CString(string, utf8, size); \
 
 224 // XXX: this macro is unhygenic
 
 225 #define CYCastCString(context, value) ({ \
 
 229     else if (JSStringRef string = CYCopyJSString(context, value)) { \
 
 230         utf8 = CYCastCString_(string); \
 
 231         JSStringRelease(string); \
 
 237 /* Objective-C Strings {{{ */
 
 238 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
 
 240         return [value UTF8String];
 
 242         size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
 
 243         char *string(new(pool) char[size]);
 
 244         if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
 
 245             @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
 
 250 JSStringRef CYCopyJSString_(NSString *value) {
 
 252     return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
 
 255     return CYCopyJSString(CYPoolCString(pool, value));
 
 259 JSStringRef CYCopyJSString(id value) {
 
 262     // XXX: this definition scares me; is anyone using this?!
 
 263     NSString *string([value description]);
 
 264     return CYCopyJSString_(string);
 
 268 CFStringRef CYCopyCFString(JSStringRef value) {
 
 269     return JSStringCopyCFString(kCFAllocatorDefault, value);
 
 272 CFStringRef CYCopyCFString(const char *value) {
 
 273     return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
 
 276 template <typename Type_>
 
 277 NSString *CYCopyNSString(Type_ value) {
 
 278     return (NSString *) CYCopyCFString(value);
 
 281 NSString *CYCopyNSString(const char *value) {
 
 282     return [NSString stringWithUTF8String:value];
 
 285 NSString *CYCopyNSString(JSStringRef value) {
 
 286     return CYCopyNSString(CYCastCString_(value));
 
 290 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
 
 291     return CYCopyNSString(CYJSString(context, value));
 
 295 static JSGlobalContextRef Context_;
 
 296 static JSObjectRef System_;
 
 297 static JSObjectRef ObjectiveC_;
 
 299 static JSClassRef Functor_;
 
 300 static JSClassRef Instance_;
 
 301 static JSClassRef Internal_;
 
 302 static JSClassRef Message_;
 
 303 static JSClassRef Messages_;
 
 304 static JSClassRef NSArrayPrototype_;
 
 305 static JSClassRef Pointer_;
 
 306 static JSClassRef Runtime_;
 
 307 static JSClassRef Selector_;
 
 308 static JSClassRef Struct_;
 
 310 static JSClassRef ObjectiveC_Classes_;
 
 311 static JSClassRef ObjectiveC_Image_Classes_;
 
 312 static JSClassRef ObjectiveC_Images_;
 
 313 static JSClassRef ObjectiveC_Protocols_;
 
 315 static JSObjectRef Array_;
 
 316 static JSObjectRef Function_;
 
 317 static JSObjectRef String_;
 
 319 static JSStringRef Result_;
 
 321 static JSStringRef length_;
 
 322 static JSStringRef message_;
 
 323 static JSStringRef name_;
 
 324 static JSStringRef prototype_;
 
 325 static JSStringRef toCYON_;
 
 326 static JSStringRef toJSON_;
 
 328 static JSObjectRef Instance_prototype_;
 
 329 static JSObjectRef Object_prototype_;
 
 331 static JSObjectRef Array_prototype_;
 
 332 static JSObjectRef Array_pop_;
 
 333 static JSObjectRef Array_push_;
 
 334 static JSObjectRef Array_splice_;
 
 337 static Class NSCFBoolean_;
 
 338 static Class NSCFType_;
 
 341 static Class NSArray_;
 
 342 static Class NSDictionary_;
 
 343 static Class NSMessageBuilder_;
 
 344 static Class NSZombie_;
 
 345 static Class Object_;
 
 347 static NSArray *Bridge_;
 
 349 static void Finalize(JSObjectRef object) {
 
 350     delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
 
 353 class Type_privateData;
 
 363     CYValue(const void *value) :
 
 364         value_(const_cast<void *>(value))
 
 368     CYValue(const CYValue &rhs) :
 
 373     virtual Type_privateData *GetType() const {
 
 378 struct Selector_privateData :
 
 381     Selector_privateData(SEL value) :
 
 386     SEL GetValue() const {
 
 387         return reinterpret_cast<SEL>(value_);
 
 390     virtual Type_privateData *GetType() const;
 
 393 // XXX: trick this out with associated objects!
 
 394 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
 
 396         return Instance_prototype_;
 
 398     // XXX: I need to think through multi-context
 
 399     typedef std::map<id, JSValueRef> CacheMap;
 
 400     static CacheMap cache_;
 
 402     JSValueRef &value(cache_[self]);
 
 406     JSClassRef _class(NULL);
 
 407     JSValueRef prototype;
 
 409     if (self == NSArray_)
 
 410         prototype = Array_prototype_;
 
 411     else if (self == NSDictionary_)
 
 412         prototype = Object_prototype_;
 
 414         prototype = CYGetClassPrototype(context, class_getSuperclass(self));
 
 416     JSObjectRef object(JSObjectMake(context, _class, NULL));
 
 417     JSObjectSetPrototype(context, object, prototype);
 
 419     JSValueProtect(context, object);
 
 429         Transient     = (1 << 0),
 
 430         Uninitialized = (1 << 1),
 
 435     Instance(id value, Flags flags) :
 
 441     virtual ~Instance() {
 
 442         if ((flags_ & Transient) == 0)
 
 443             // XXX: does this handle background threads correctly?
 
 444             // XXX: this simply does not work on the console because I'm stupid
 
 445             [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
 
 448     static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
 
 449         JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
 
 450         JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
 
 454     id GetValue() const {
 
 455         return reinterpret_cast<id>(value_);
 
 458     bool IsUninitialized() const {
 
 459         return (flags_ & Uninitialized) != 0;
 
 462     virtual Type_privateData *GetType() const;
 
 468     Messages(Class value) :
 
 473     static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
 
 474         JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
 
 475         if (_class == NSArray_)
 
 477         if (Class super = class_getSuperclass(_class))
 
 478             JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
 
 480             JSObjectSetPrototype(context, value, Array_prototype_);*/
 
 484     Class GetValue() const {
 
 485         return reinterpret_cast<Class>(value_);
 
 493     JSContextRef context_;
 
 497     CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
 
 502         JSValueProtect(context_, owner_);
 
 506         JSValueUnprotect(context_, owner_);
 
 509     JSObjectRef GetOwner() const {
 
 517     Internal(id value, JSContextRef context, JSObjectRef owner) :
 
 518         CYOwned(value, context, owner)
 
 522     static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
 
 523         return JSObjectMake(context, Internal_, new Internal(object, context, owner));
 
 526     id GetValue() const {
 
 527         return reinterpret_cast<id>(value_);
 
 533 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
 
 535 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
 
 536     lhs.name = apr_pstrdup(pool, rhs.name);
 
 537     if (rhs.type == NULL)
 
 540         lhs.type = new(pool) Type;
 
 541         Copy(pool, *lhs.type, *rhs.type);
 
 543     lhs.offset = rhs.offset;
 
 546 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
 
 547     size_t count(rhs.count);
 
 549     lhs.elements = new(pool) Element[count];
 
 550     for (size_t index(0); index != count; ++index)
 
 551         Copy(pool, lhs.elements[index], rhs.elements[index]);
 
 554 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
 
 555     lhs.primitive = rhs.primitive;
 
 556     lhs.name = apr_pstrdup(pool, rhs.name);
 
 557     lhs.flags = rhs.flags;
 
 559     if (sig::IsAggregate(rhs.primitive))
 
 560         Copy(pool, lhs.data.signature, rhs.data.signature);
 
 562         sig::Type *&lht(lhs.data.data.type);
 
 563         sig::Type *&rht(rhs.data.data.type);
 
 568             lht = new(pool) Type;
 
 569             Copy(pool, *lht, *rht);
 
 572         lhs.data.data.size = rhs.data.data.size;
 
 576 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
 
 578     lhs.alignment = rhs.alignment;
 
 580     if (rhs.elements == NULL)
 
 584         while (rhs.elements[count] != NULL)
 
 587         lhs.elements = new(pool) ffi_type *[count + 1];
 
 588         lhs.elements[count] = NULL;
 
 590         for (size_t index(0); index != count; ++index) {
 
 591             // XXX: if these are libffi native then you can just take them
 
 592             ffi_type *ffi(new(pool) ffi_type);
 
 593             lhs.elements[index] = ffi;
 
 594             sig::Copy(pool, *ffi, *rhs.elements[index]);
 
 601 struct CStringMapLess :
 
 602     std::binary_function<const char *, const char *, bool>
 
 604     _finline bool operator ()(const char *lhs, const char *rhs) const {
 
 605         return strcmp(lhs, rhs) < 0;
 
 609 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
 
 614         if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
 
 615             switch ([[entry objectAtIndex:0] intValue]) {
 
 617                     sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
 
 621                     sig::Signature signature;
 
 622                     sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
 
 623                     type = signature.elements[0].type;
 
 629 struct Type_privateData :
 
 632     static Type_privateData *Object;
 
 633     static Type_privateData *Selector;
 
 635     static JSClassRef Class_;
 
 640     void Set(sig::Type *type) {
 
 641         type_ = new(pool_) sig::Type;
 
 642         sig::Copy(pool_, *type_, *type);
 
 645     Type_privateData(apr_pool_t *pool, const char *type) :
 
 651         sig::Signature signature;
 
 652         sig::Parse(pool_, &signature, type, &Structor_);
 
 653         type_ = signature.elements[0].type;
 
 656     Type_privateData(sig::Type *type) :
 
 663     Type_privateData(sig::Type *type, ffi_type *ffi) {
 
 664         ffi_ = new(pool_) ffi_type;
 
 665         sig::Copy(pool_, *ffi_, *ffi);
 
 671             ffi_ = new(pool_) ffi_type;
 
 673             sig::Element element;
 
 675             element.type = type_;
 
 678             sig::Signature signature;
 
 679             signature.elements = &element;
 
 683             sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
 
 691 JSClassRef Type_privateData::Class_;
 
 692 Type_privateData *Type_privateData::Object;
 
 693 Type_privateData *Type_privateData::Selector;
 
 695 Type_privateData *Instance::GetType() const {
 
 696     return Type_privateData::Object;
 
 699 Type_privateData *Selector_privateData::GetType() const {
 
 700     return Type_privateData::Selector;
 
 706     Type_privateData *type_;
 
 708     Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
 
 709         CYOwned(value, context, owner),
 
 710         type_(new(pool_) Type_privateData(type))
 
 715 struct Struct_privateData :
 
 718     Type_privateData *type_;
 
 720     Struct_privateData(JSContextRef context, JSObjectRef owner) :
 
 721         CYOwned(NULL, context, owner)
 
 726 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
 
 727 static TypeMap Types_;
 
 729 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
 
 730     Struct_privateData *internal(new Struct_privateData(context, owner));
 
 731     apr_pool_t *pool(internal->pool_);
 
 732     Type_privateData *typical(new(pool) Type_privateData(type, ffi));
 
 733     internal->type_ = typical;
 
 736         internal->value_ = data;
 
 738         size_t size(typical->GetFFI()->size);
 
 739         void *copy(apr_palloc(internal->pool_, size));
 
 740         memcpy(copy, data, size);
 
 741         internal->value_ = copy;
 
 744     return JSObjectMake(context, Struct_, internal);
 
 747 struct Functor_privateData :
 
 750     sig::Signature signature_;
 
 754     Functor_privateData(const char *type, void (*value)()) :
 
 755         CYValue(reinterpret_cast<void *>(value))
 
 757         sig::Parse(pool_, &signature_, type, &Structor_);
 
 758         sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
 
 761     void (*GetValue())() const {
 
 762         return reinterpret_cast<void (*)()>(value_);
 
 766 struct Closure_privateData :
 
 769     JSContextRef context_;
 
 770     JSObjectRef function_;
 
 772     Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
 
 773         Functor_privateData(type, NULL),
 
 777         JSValueProtect(context_, function_);
 
 780     virtual ~Closure_privateData() {
 
 781         JSValueUnprotect(context_, function_);
 
 785 struct Message_privateData :
 
 790     Message_privateData(SEL sel, const char *type, IMP value = NULL) :
 
 791         Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
 
 797 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
 
 798     Instance::Flags flags;
 
 801         flags = Instance::Transient;
 
 803         flags = Instance::None;
 
 804         object = [object retain];
 
 807     return Instance::Make(context, object, flags);
 
 810 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
 
 811     return JSValueMakeBoolean(context, value);
 
 814 JSValueRef CYCastJSValue(JSContextRef context, double value) {
 
 815     return JSValueMakeNumber(context, value);
 
 818 #define CYCastJSValue_(Type_) \
 
 819     JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
 
 820         return JSValueMakeNumber(context, static_cast<double>(value)); \
 
 824 CYCastJSValue_(unsigned int)
 
 825 CYCastJSValue_(long int)
 
 826 CYCastJSValue_(long unsigned int)
 
 827 CYCastJSValue_(long long int)
 
 828 CYCastJSValue_(long long unsigned int)
 
 830 JSValueRef CYJSUndefined(JSContextRef context) {
 
 831     return JSValueMakeUndefined(context);
 
 834 size_t CYGetIndex(const char *value) {
 
 835     if (value[0] != '0') {
 
 837         size_t index(strtoul(value, &end, 10));
 
 838         if (value + strlen(value) == end)
 
 840     } else if (value[1] == '\0')
 
 846 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value);
 
 848 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
 
 849     return CYGetIndex(CYPoolCString(pool, value));
 
 852 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
 
 853     return CYGetIndex(CYPoolCString(pool, value));
 
 856 bool CYGetOffset(const char *value, ssize_t &index) {
 
 857     if (value[0] != '0') {
 
 859         index = strtol(value, &end, 10);
 
 860         if (value + strlen(value) == end)
 
 862     } else if (value[1] == '\0') {
 
 870 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
 
 871     return CYGetOffset(CYPoolCString(pool, value), index);
 
 874 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
 
 876 @interface NSMethodSignature (Cycript)
 
 877 - (NSString *) _typeString;
 
 880 @interface NSObject (Cycript)
 
 882 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 
 883 - (JSType) cy$JSType;
 
 885 - (NSObject *) cy$toJSON:(NSString *)key;
 
 886 - (NSString *) cy$toCYON;
 
 887 - (NSString *) cy$toKey;
 
 889 - (bool) cy$hasProperty:(NSString *)name;
 
 890 - (NSObject *) cy$getProperty:(NSString *)name;
 
 891 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
 
 892 - (bool) cy$deleteProperty:(NSString *)name;
 
 897 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 
 900 @interface NSString (Cycript)
 
 901 - (void *) cy$symbol;
 
 905 struct PropertyAttributes {
 
 910     const char *variable;
 
 923     PropertyAttributes(objc_property_t property) :
 
 935         name = property_getName(property);
 
 936         const char *attributes(property_getAttributes(property));
 
 938         for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
 
 940                 case 'R': readonly = true; break;
 
 941                 case 'C': copy = true; break;
 
 942                 case '&': retain = true; break;
 
 943                 case 'N': nonatomic = true; break;
 
 944                 case 'G': getter_ = token + 1; break;
 
 945                 case 'S': setter_ = token + 1; break;
 
 946                 case 'V': variable = token + 1; break;
 
 950         /*if (variable == NULL) {
 
 951             variable = property_getName(property);
 
 952             size_t size(strlen(variable));
 
 953             char *name(new(pool_) char[size + 2]);
 
 955             memcpy(name + 1, variable, size);
 
 956             name[size + 1] = '\0';
 
 961     const char *Getter() {
 
 963             getter_ = apr_pstrdup(pool_, name);
 
 967     const char *Setter() {
 
 968         if (setter_ == NULL && !readonly) {
 
 969             size_t length(strlen(name));
 
 971             char *temp(new(pool_) char[length + 5]);
 
 977                 temp[3] = toupper(name[0]);
 
 978                 memcpy(temp + 4, name + 1, length - 1);
 
 981             temp[length + 3] = ':';
 
 982             temp[length + 4] = '\0';
 
 993 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
 
 994     return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
 
 999 @interface CYWebUndefined : NSObject {
 
1002 + (CYWebUndefined *) undefined;
 
1006 @implementation CYWebUndefined
 
1008 + (CYWebUndefined *) undefined {
 
1009     static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
 
1015 #define WebUndefined CYWebUndefined
 
1018 /* Bridge: NSArray {{{ */
 
1019 @implementation NSArray (Cycript)
 
1021 - (NSString *) cy$toCYON {
 
1022     NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
 
1023     [json appendString:@"["];
 
1027     for (id object in self) {
 
1030     for (size_t index(0), count([self count]); index != count; ++index) {
 
1031         object = [self objectAtIndex:index];
 
1034             [json appendString:@","];
 
1037         if (object == nil || [object cy$JSType] != kJSTypeUndefined)
 
1038             [json appendString:CYPoolNSCYON(NULL, object)];
 
1040             [json appendString:@","];
 
1045     [json appendString:@"]"];
 
1049 - (bool) cy$hasProperty:(NSString *)name {
 
1050     if ([name isEqualToString:@"length"])
 
1053     size_t index(CYGetIndex(NULL, name));
 
1054     if (index == _not(size_t) || index >= [self count])
 
1055         return [super cy$hasProperty:name];
 
1060 - (NSObject *) cy$getProperty:(NSString *)name {
 
1061     if ([name isEqualToString:@"length"]) {
 
1062         NSUInteger count([self count]);
 
1064         return [NSNumber numberWithUnsignedInteger:count];
 
1066         return [NSNumber numberWithUnsignedInt:count];
 
1070     size_t index(CYGetIndex(NULL, name));
 
1071     if (index == _not(size_t) || index >= [self count])
 
1072         return [super cy$getProperty:name];
 
1074         return [self objectAtIndex:index];
 
1079 /* Bridge: NSDictionary {{{ */
 
1080 @implementation NSDictionary (Cycript)
 
1082 - (NSString *) cy$toCYON {
 
1083     NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
 
1084     [json appendString:@"{"];
 
1088     for (id key in self) {
 
1090     NSEnumerator *keys([self keyEnumerator]);
 
1091     while (id key = [keys nextObject]) {
 
1094             [json appendString:@","];
 
1097         [json appendString:[key cy$toKey]];
 
1098         [json appendString:@":"];
 
1099         NSObject *object([self objectForKey:key]);
 
1100         [json appendString:CYPoolNSCYON(NULL, object)];
 
1103     [json appendString:@"}"];
 
1107 - (bool) cy$hasProperty:(NSString *)name {
 
1108     return [self objectForKey:name] != nil;
 
1111 - (NSObject *) cy$getProperty:(NSString *)name {
 
1112     return [self objectForKey:name];
 
1117 /* Bridge: NSMutableArray {{{ */
 
1118 @implementation NSMutableArray (Cycript)
 
1120 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
1121     if ([name isEqualToString:@"length"]) {
 
1122         // XXX: is this not intelligent?
 
1123         NSNumber *number(reinterpret_cast<NSNumber *>(value));
 
1125         NSUInteger size([number unsignedIntegerValue]);
 
1127         NSUInteger size([number unsignedIntValue]);
 
1129         NSUInteger count([self count]);
 
1131             [self removeObjectsInRange:NSMakeRange(size, count - size)];
 
1132         else if (size != count) {
 
1133             WebUndefined *undefined([WebUndefined undefined]);
 
1134             for (size_t i(count); i != size; ++i)
 
1135                 [self addObject:undefined];
 
1140     size_t index(CYGetIndex(NULL, name));
 
1141     if (index == _not(size_t))
 
1142         return [super cy$setProperty:name to:value];
 
1144     id object(value ?: [NSNull null]);
 
1146     size_t count([self count]);
 
1148         [self replaceObjectAtIndex:index withObject:object];
 
1150         if (index != count) {
 
1151             WebUndefined *undefined([WebUndefined undefined]);
 
1152             for (size_t i(count); i != index; ++i)
 
1153                 [self addObject:undefined];
 
1156         [self addObject:object];
 
1162 - (bool) cy$deleteProperty:(NSString *)name {
 
1163     size_t index(CYGetIndex(NULL, name));
 
1164     if (index == _not(size_t) || index >= [self count])
 
1165         return [super cy$deleteProperty:name];
 
1166     [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
 
1172 /* Bridge: NSMutableDictionary {{{ */
 
1173 @implementation NSMutableDictionary (Cycript)
 
1175 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
1176     [self setObject:(value ?: [NSNull null]) forKey:name];
 
1180 - (bool) cy$deleteProperty:(NSString *)name {
 
1181     if ([self objectForKey:name] == nil)
 
1184         [self removeObjectForKey:name];
 
1191 /* Bridge: NSNumber {{{ */
 
1192 @implementation NSNumber (Cycript)
 
1194 - (JSType) cy$JSType {
 
1196     // XXX: this just seems stupid
 
1197     if ([self class] == NSCFBoolean_)
 
1198         return kJSTypeBoolean;
 
1200     return kJSTypeNumber;
 
1203 - (NSObject *) cy$toJSON:(NSString *)key {
 
1207 - (NSString *) cy$toCYON {
 
1208     return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
 
1211 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
1212     return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
 
1217 /* Bridge: NSNull {{{ */
 
1218 @implementation NSNull (Cycript)
 
1220 - (JSType) cy$JSType {
 
1224 - (NSObject *) cy$toJSON:(NSString *)key {
 
1228 - (NSString *) cy$toCYON {
 
1234 /* Bridge: NSObject {{{ */
 
1235 @implementation NSObject (Cycript)
 
1237 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
1238     return CYMakeInstance(context, self, false);
 
1241 - (JSType) cy$JSType {
 
1242     return kJSTypeObject;
 
1245 - (NSObject *) cy$toJSON:(NSString *)key {
 
1246     return [self description];
 
1249 - (NSString *) cy$toCYON {
 
1250     return [[self cy$toJSON:@""] cy$toCYON];
 
1253 - (NSString *) cy$toKey {
 
1254     return [self cy$toCYON];
 
1257 - (bool) cy$hasProperty:(NSString *)name {
 
1261 - (NSObject *) cy$getProperty:(NSString *)name {
 
1265 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
1269 - (bool) cy$deleteProperty:(NSString *)name {
 
1275 /* Bridge: NSProxy {{{ */
 
1276 @implementation NSProxy (Cycript)
 
1278 - (NSObject *) cy$toJSON:(NSString *)key {
 
1279     return [self description];
 
1282 - (NSString *) cy$toCYON {
 
1283     return [[self cy$toJSON:@""] cy$toCYON];
 
1288 /* Bridge: NSString {{{ */
 
1289 @implementation NSString (Cycript)
 
1291 - (JSType) cy$JSType {
 
1292     return kJSTypeString;
 
1295 - (NSObject *) cy$toJSON:(NSString *)key {
 
1299 - (NSString *) cy$toCYON {
 
1300     // XXX: this should use the better code from Output.cpp
 
1302     NSMutableString *json([self mutableCopy]);
 
1304     [json replaceOccurrencesOfString:@"\\" withString:@"\\\\" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
 
1305     [json replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
 
1306     [json replaceOccurrencesOfString:@"\t" withString:@"\\t" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
 
1307     [json replaceOccurrencesOfString:@"\r" withString:@"\\r" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
 
1308     [json replaceOccurrencesOfString:@"\n" withString:@"\\n" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
 
1310     [json appendString:@"\""];
 
1311     [json insertString:@"\"" atIndex:0];
 
1316 - (NSString *) cy$toKey {
 
1317     const char *value([self UTF8String]);
 
1318     size_t size(strlen(value));
 
1323     if (DigitRange_[value[0]]) {
 
1324         size_t index(CYGetIndex(NULL, self));
 
1325         if (index == _not(size_t))
 
1328         if (!WordStartRange_[value[0]])
 
1330         for (size_t i(1); i != size; ++i)
 
1331             if (!WordEndRange_[value[i]])
 
1338     return [self cy$toCYON];
 
1341 - (void *) cy$symbol {
 
1343     return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
 
1348 /* Bridge: WebUndefined {{{ */
 
1349 @implementation WebUndefined (Cycript)
 
1351 - (JSType) cy$JSType {
 
1352     return kJSTypeUndefined;
 
1355 - (NSObject *) cy$toJSON:(NSString *)key {
 
1359 - (NSString *) cy$toCYON {
 
1360     return @"undefined";
 
1363 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
1364     return CYJSUndefined(context);
 
1370 /* Bridge: CYJSObject {{{ */
 
1371 @interface CYJSObject : NSMutableDictionary {
 
1372     JSObjectRef object_;
 
1373     JSContextRef context_;
 
1376 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
 
1378 - (NSObject *) cy$toJSON:(NSString *)key;
 
1380 - (NSUInteger) count;
 
1381 - (id) objectForKey:(id)key;
 
1382 - (NSEnumerator *) keyEnumerator;
 
1383 - (void) setObject:(id)object forKey:(id)key;
 
1384 - (void) removeObjectForKey:(id)key;
 
1388 /* Bridge: CYJSArray {{{ */
 
1389 @interface CYJSArray : NSMutableArray {
 
1390     JSObjectRef object_;
 
1391     JSContextRef context_;
 
1394 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
 
1396 - (NSUInteger) count;
 
1397 - (id) objectAtIndex:(NSUInteger)index;
 
1399 - (void) addObject:(id)anObject;
 
1400 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
 
1401 - (void) removeLastObject;
 
1402 - (void) removeObjectAtIndex:(NSUInteger)index;
 
1403 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
 
1411     @catch (id error) { \
 
1412         CYThrow(context, error, exception); \
 
1416 apr_status_t CYPoolRelease_(void *data) {
 
1417     id object(reinterpret_cast<id>(data));
 
1422 id CYPoolRelease_(apr_pool_t *pool, id object) {
 
1425     else if (pool == NULL)
 
1426         return [object autorelease];
 
1428         apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
 
1433 template <typename Type_>
 
1434 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
 
1435     return (Type_) CYPoolRelease_(pool, (id) object);
 
1438 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
 
1439     JSValueRef exception(NULL);
 
1440     bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
 
1441     CYThrow(context, exception);
 
1442     id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
 
1443     return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
 
1446 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
 
1447     if (!JSValueIsObjectOfClass(context, object, Instance_))
 
1448         return CYCastNSObject_(pool, context, object);
 
1450         Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
1451         return internal->GetValue();
 
1455 double CYCastDouble(const char *value, size_t size) {
 
1457     double number(strtod(value, &end));
 
1458     if (end != value + size)
 
1463 double CYCastDouble(const char *value) {
 
1464     return CYCastDouble(value, strlen(value));
 
1467 double CYCastDouble(JSContextRef context, JSValueRef value) {
 
1468     JSValueRef exception(NULL);
 
1469     double number(JSValueToNumber(context, value, &exception));
 
1470     CYThrow(context, exception);
 
1474 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
 
1475     return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
 
1478 template <typename Type_>
 
1479 NSString *CYCastNSString(apr_pool_t *pool, Type_ value) {
 
1480     return CYPoolRelease(pool, CYCopyNSString(value));
 
1483 bool CYCastBool(JSContextRef context, JSValueRef value) {
 
1484     return JSValueToBoolean(context, value);
 
1487 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
 
1491     switch (JSType type = JSValueGetType(context, value)) {
 
1492         case kJSTypeUndefined:
 
1493             object = [WebUndefined undefined];
 
1501         case kJSTypeBoolean:
 
1503             object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
 
1506             object = [[NSNumber alloc] initWithBool:CYCastBool(context, value)];
 
1512             object = CYCopyNSNumber(context, value);
 
1517             object = CYCopyNSString(context, value);
 
1522             // XXX: this might could be more efficient
 
1523             object = CYCastNSObject(pool, context, (JSObjectRef) value);
 
1528             @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
 
1535         return CYPoolRelease(pool, object);
 
1537         return [object retain];
 
1540 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1541     return CYNSObject(pool, context, value, true);
 
1544 id CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1545     return CYNSObject(pool, context, value, false);
 
1548 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
 
1550     size_t size(JSPropertyNameArrayGetCount(names));
 
1551     NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
 
1552     for (size_t index(0); index != size; ++index)
 
1553         [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
 
1557 void CYThrow(JSContextRef context, JSValueRef value) {
 
1560     @throw CYCastNSObject(NULL, context, value);
 
1563 JSValueRef CYJSNull(JSContextRef context) {
 
1564     return JSValueMakeNull(context);
 
1567 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
 
1568     return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
 
1571 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
 
1572     return CYCastJSValue(context, CYJSString(value));
 
1575 JSValueRef CYCastJSValue(JSContextRef context, id value) {
 
1577         return CYJSNull(context);
 
1578     else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
 
1579         return [value cy$JSValueInContext:context];
 
1581         return CYMakeInstance(context, value, false);
 
1584 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
 
1585     JSValueRef exception(NULL);
 
1586     JSObjectRef object(JSValueToObject(context, value, &exception));
 
1587     CYThrow(context, exception);
 
1591 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
 
1592     if (exception == NULL)
 
1594     *exception = CYCastJSValue(context, error);
 
1597 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
 
1598     JSValueRef exception(NULL);
 
1599     JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
 
1600     CYThrow(context, exception);
 
1604 bool CYIsCallable(JSContextRef context, JSValueRef value) {
 
1605     // XXX: this isn't actually correct
 
1606     return value != NULL && JSValueIsObject(context, value);
 
1609 @implementation CYJSObject
 
1611 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
 
1612     if ((self = [super init]) != nil) {
 
1615         JSValueProtect(context_, object_);
 
1620     JSValueUnprotect(context_, object_);
 
1624 - (NSObject *) cy$toJSON:(NSString *)key {
 
1625     JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
 
1626     if (!CYIsCallable(context_, toJSON))
 
1627         return [super cy$toJSON:key];
 
1629         JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
 
1630         JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
 
1631         // XXX: do I really want an NSNull here?!
 
1632         return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1636 - (NSString *) cy$toCYON {
 
1637     JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
 
1638     if (!CYIsCallable(context_, toCYON)) super:
 
1639         return [super cy$toCYON];
 
1640     else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
 
1641         return CYCastNSString(NULL, CYJSString(context_, value));
 
1645 - (NSUInteger) count {
 
1646     JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
 
1647     size_t size(JSPropertyNameArrayGetCount(names));
 
1648     JSPropertyNameArrayRelease(names);
 
1652 - (id) objectForKey:(id)key {
 
1653     JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
 
1654     if (JSValueIsUndefined(context_, value))
 
1656     return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1659 - (NSEnumerator *) keyEnumerator {
 
1660     JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
 
1661     NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
 
1662     JSPropertyNameArrayRelease(names);
 
1666 - (void) setObject:(id)object forKey:(id)key {
 
1667     CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
 
1670 - (void) removeObjectForKey:(id)key {
 
1671     JSValueRef exception(NULL);
 
1672     (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
 
1673     CYThrow(context_, exception);
 
1678 @implementation CYJSArray
 
1680 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
 
1681     if ((self = [super init]) != nil) {
 
1684         JSValueProtect(context_, object_);
 
1689     JSValueUnprotect(context_, object_);
 
1693 - (NSUInteger) count {
 
1694     return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
 
1697 - (id) objectAtIndex:(NSUInteger)index {
 
1698     size_t bounds([self count]);
 
1699     if (index >= bounds)
 
1700         @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
 
1701     JSValueRef exception(NULL);
 
1702     JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
 
1703     CYThrow(context_, exception);
 
1704     return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1707 - (void) addObject:(id)object {
 
1708     JSValueRef exception(NULL);
 
1709     JSValueRef arguments[1];
 
1710     arguments[0] = CYCastJSValue(context_, object);
 
1711     JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
 
1712     CYThrow(context_, exception);
 
1715 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
 
1716     size_t bounds([self count] + 1);
 
1717     if (index >= bounds)
 
1718         @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
 
1719     JSValueRef exception(NULL);
 
1720     JSValueRef arguments[3];
 
1721     arguments[0] = CYCastJSValue(context_, index);
 
1722     arguments[1] = CYCastJSValue(context_, 0);
 
1723     arguments[2] = CYCastJSValue(context_, object);
 
1724     JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
 
1725     CYThrow(context_, exception);
 
1728 - (void) removeLastObject {
 
1729     JSValueRef exception(NULL);
 
1730     JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
 
1731     CYThrow(context_, exception);
 
1734 - (void) removeObjectAtIndex:(NSUInteger)index {
 
1735     size_t bounds([self count]);
 
1736     if (index >= bounds)
 
1737         @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
 
1738     JSValueRef exception(NULL);
 
1739     JSValueRef arguments[2];
 
1740     arguments[0] = CYCastJSValue(context_, index);
 
1741     arguments[1] = CYCastJSValue(context_, 1);
 
1742     JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
 
1743     CYThrow(context_, exception);
 
1746 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
 
1747     size_t bounds([self count]);
 
1748     if (index >= bounds)
 
1749         @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
 
1750     CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
 
1755 NSString *CYCopyNSCYON(id value) {
 
1761         Class _class(object_getClass(value));
 
1762         SEL sel(@selector(cy$toCYON));
 
1764         if (Method toCYON = class_getInstanceMethod(_class, sel))
 
1765             string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
 
1766         else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
 
1767             if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
 
1768                 string = [value cy$toCYON];
 
1771             if (value == NSZombie_)
 
1772                 string = @"_NSZombie_";
 
1773             else if (_class == NSZombie_)
 
1774                 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
 
1775             // XXX: frowny /in/ the pants
 
1776             else if (value == NSMessageBuilder_ || value == Object_)
 
1779                 string = [NSString stringWithFormat:@"%@", value];
 
1782         // XXX: frowny pants
 
1784             string = @"undefined";
 
1787     return [string retain];
 
1790 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
 
1791     if (JSValueIsNull(context, value))
 
1792         return [@"null" retain];
 
1796             return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
 
1801 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
 
1802     return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
 
1805 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
 
1806     if (NSString *json = CYCopyNSCYON(context, value, exception)) {
 
1807         const char *string(CYPoolCString(pool, json));
 
1813 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
 
1817     JSObjectRef object_;
 
1825         // XXX: delete object_? ;(
 
1828     static CYInternal *Get(id self) {
 
1829         CYInternal *internal(NULL);
 
1830         if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
 
1831             // XXX: do something epic? ;P
 
1837     static CYInternal *Set(id self) {
 
1838         CYInternal *internal(NULL);
 
1839         if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
 
1840             if (internal == NULL) {
 
1841                 internal = new CYInternal();
 
1842                 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
 
1845             // XXX: do something epic? ;P
 
1851     bool HasProperty(JSContextRef context, JSStringRef name) {
 
1852         if (object_ == NULL)
 
1854         return JSObjectHasProperty(context, object_, name);
 
1857     JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
 
1858         if (object_ == NULL)
 
1860         return CYGetProperty(context, object_, name);
 
1863     void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
 
1864         if (object_ == NULL)
 
1865             object_ = JSObjectMake(context, NULL, NULL);
 
1866         CYSetProperty(context, object_, name, value);
 
1870 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
 
1871     Selector_privateData *internal(new Selector_privateData(sel));
 
1872     return JSObjectMake(context, Selector_, internal);
 
1875 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
 
1876     Pointer *internal(new Pointer(pointer, context, owner, type));
 
1877     return JSObjectMake(context, Pointer_, internal);
 
1880 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
 
1881     Functor_privateData *internal(new Functor_privateData(type, function));
 
1882     return JSObjectMake(context, Functor_, internal);
 
1885 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
 
1887         // XXX: this could be much more efficient
 
1888         const char *string([CYCastNSString(NULL, value) UTF8String]);
 
1891         size_t size(JSStringGetMaximumUTF8CStringSize(value));
 
1892         char *string(new(pool) char[size]);
 
1893         JSStringGetUTF8CString(value, string, size);
 
1898 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1899     return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
 
1902 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
 
1903     return CYGetOffset(CYPoolCString(pool, value), index);
 
1906 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
 
1907     switch (JSValueGetType(context, value)) {
 
1910         /*case kJSTypeString:
 
1911             return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
 
1913             if (JSValueIsObjectOfClass(context, value, Pointer_)) {
 
1914                 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
 
1915                 return internal->value_;
 
1918             double number(CYCastDouble(context, value));
 
1919             if (std::isnan(number))
 
1920                 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
 
1921             return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
 
1925 template <typename Type_>
 
1926 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
 
1927     return reinterpret_cast<Type_>(CYCastPointer_(context, value));
 
1930 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
 
1931     if (JSValueIsObjectOfClass(context, value, Selector_)) {
 
1932         Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
 
1933         return reinterpret_cast<SEL>(internal->value_);
 
1935         return CYCastPointer<SEL>(context, value);
 
1938 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
 
1939     switch (type->primitive) {
 
1940         case sig::boolean_P:
 
1941             *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
 
1944 #define CYPoolFFI_(primitive, native) \
 
1945         case sig::primitive ## _P: \
 
1946             *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
 
1949         CYPoolFFI_(uchar, unsigned char)
 
1950         CYPoolFFI_(char, char)
 
1951         CYPoolFFI_(ushort, unsigned short)
 
1952         CYPoolFFI_(short, short)
 
1953         CYPoolFFI_(ulong, unsigned long)
 
1954         CYPoolFFI_(long, long)
 
1955         CYPoolFFI_(uint, unsigned int)
 
1956         CYPoolFFI_(int, int)
 
1957         CYPoolFFI_(ulonglong, unsigned long long)
 
1958         CYPoolFFI_(longlong, long long)
 
1959         CYPoolFFI_(float, float)
 
1960         CYPoolFFI_(double, double)
 
1963         case sig::typename_P:
 
1964             *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
 
1967         case sig::selector_P:
 
1968             *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
 
1971         case sig::pointer_P:
 
1972             *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
 
1976             *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
 
1979         case sig::struct_P: {
 
1980             uint8_t *base(reinterpret_cast<uint8_t *>(data));
 
1981             JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
 
1982             for (size_t index(0); index != type->data.signature.count; ++index) {
 
1983                 sig::Element *element(&type->data.signature.elements[index]);
 
1984                 ffi_type *field(ffi->elements[index]);
 
1987                 if (aggregate == NULL)
 
1990                     rhs = CYGetProperty(context, aggregate, index);
 
1991                     if (JSValueIsUndefined(context, rhs)) {
 
1992                         if (element->name != NULL)
 
1993                             rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
 
1996                         if (JSValueIsUndefined(context, rhs)) undefined:
 
1997                             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
 
2001                 CYPoolFFI(pool, context, element->type, field, base, rhs);
 
2003                 base += field->size;
 
2011             NSLog(@"CYPoolFFI(%c)\n", type->primitive);
 
2016 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
 
2019     switch (type->primitive) {
 
2020         case sig::boolean_P:
 
2021             value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
 
2024 #define CYFromFFI_(primitive, native) \
 
2025         case sig::primitive ## _P: \
 
2026             value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
 
2029         CYFromFFI_(uchar, unsigned char)
 
2030         CYFromFFI_(char, char)
 
2031         CYFromFFI_(ushort, unsigned short)
 
2032         CYFromFFI_(short, short)
 
2033         CYFromFFI_(ulong, unsigned long)
 
2034         CYFromFFI_(long, long)
 
2035         CYFromFFI_(uint, unsigned int)
 
2036         CYFromFFI_(int, int)
 
2037         CYFromFFI_(ulonglong, unsigned long long)
 
2038         CYFromFFI_(longlong, long long)
 
2039         CYFromFFI_(float, float)
 
2040         CYFromFFI_(double, double)
 
2042         case sig::object_P: {
 
2043             if (id object = *reinterpret_cast<id *>(data)) {
 
2044                 value = CYCastJSValue(context, object);
 
2050         case sig::typename_P:
 
2051             value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
 
2054         case sig::selector_P:
 
2055             if (SEL sel = *reinterpret_cast<SEL *>(data))
 
2056                 value = CYMakeSelector(context, sel);
 
2060         case sig::pointer_P:
 
2061             if (void *pointer = *reinterpret_cast<void **>(data))
 
2062                 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
 
2067             if (char *utf8 = *reinterpret_cast<char **>(data))
 
2068                 value = CYCastJSValue(context, utf8);
 
2073             value = CYMakeStruct(context, data, type, ffi, owner);
 
2077             value = CYJSUndefined(context);
 
2081             value = CYJSNull(context);
 
2085             NSLog(@"CYFromFFI(%c)\n", type->primitive);
 
2092 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
 
2093     if (Method method = class_getInstanceMethod(_class, selector)) {
 
2097         method_getReturnType(method, type, sizeof(type));
 
2102     // XXX: possibly use a more "awesome" check?
 
2106 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
 
2108         return method_getTypeEncoding(method);
 
2109     else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
 
2110         return CYPoolCString(pool, type);
 
2115 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
 
2116     Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
 
2118     JSContextRef context(internal->context_);
 
2120     size_t count(internal->cif_.nargs);
 
2121     JSValueRef values[count];
 
2123     for (size_t index(0); index != count; ++index)
 
2124         values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
 
2126     JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
 
2127     CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
 
2130 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
 
2131     Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
 
2133     JSContextRef context(internal->context_);
 
2135     size_t count(internal->cif_.nargs);
 
2136     JSValueRef values[count];
 
2138     for (size_t index(0); index != count; ++index)
 
2139         values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
 
2141     JSObjectRef _this(CYCastJSObject(context, values[0]));
 
2143     JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
 
2144     CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
 
2147 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
 
2148     // XXX: in case of exceptions this will leak
 
2149     // XXX: in point of fact, this may /need/ to leak :(
 
2150     Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
 
2152     ffi_closure *closure((ffi_closure *) _syscall(mmap(
 
2153         NULL, sizeof(ffi_closure),
 
2154         PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
 
2158     ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
 
2159     _assert(status == FFI_OK);
 
2161     _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
 
2163     internal->value_ = closure;
 
2168 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
 
2169     Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
 
2170     return JSObjectMake(context, Functor_, internal);
 
2173 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
 
2174     JSValueRef exception(NULL);
 
2175     bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
 
2176     CYThrow(context, exception);
 
2179         JSObjectRef function(CYCastJSObject(context, value));
 
2180         return CYMakeFunctor(context, function, type);
 
2182         void (*function)()(CYCastPointer<void (*)()>(context, value));
 
2183         return CYMakeFunctor(context, function, type);
 
2187 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
 
2188     Message_privateData *internal(new Message_privateData(sel, type, imp));
 
2189     return JSObjectMake(context, Message_, internal);
 
2192 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
 
2193     JSObjectRef function(CYCastJSObject(context, value));
 
2194     Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
 
2195     return reinterpret_cast<IMP>(internal->GetValue());
 
2198 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
 
2199     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2200     Class _class(internal->GetValue());
 
2203     const char *name(CYPoolCString(pool, property));
 
2205     if (SEL sel = sel_getUid(name))
 
2206         if (class_getInstanceMethod(_class, sel) != NULL)
 
2212 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2213     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2214     Class _class(internal->GetValue());
 
2217     const char *name(CYPoolCString(pool, property));
 
2219     if (SEL sel = sel_getUid(name))
 
2220         if (Method method = class_getInstanceMethod(_class, sel))
 
2221             return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
 
2226 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2227     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2228     Class _class(internal->GetValue());
 
2231     const char *name(CYPoolCString(pool, property));
 
2233     SEL sel(sel_registerName(name));
 
2235     Method method(class_getInstanceMethod(_class, sel));
 
2240     if (JSValueIsObjectOfClass(context, value, Message_)) {
 
2241         Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
 
2242         type = sig::Unparse(pool, &message->signature_);
 
2243         imp = reinterpret_cast<IMP>(message->GetValue());
 
2245         type = CYPoolTypeEncoding(pool, _class, sel, method);
 
2246         imp = CYMakeMessage(context, value, type);
 
2250         method_setImplementation(method, imp);
 
2252         class_replaceMethod(_class, sel, imp, type);
 
2258 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2259     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2260     Class _class(internal->GetValue());
 
2263     const char *name(CYPoolCString(pool, property));
 
2265     if (SEL sel = sel_getUid(name))
 
2266         if (Method method = class_getInstanceMethod(_class, sel)) {
 
2267             objc_method_list list = {NULL, 1, {method}};
 
2268             class_removeMethods(_class, &list);
 
2276 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2277     Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
 
2278     Class _class(internal->GetValue());
 
2281     Method *data(class_copyMethodList(_class, &size));
 
2282     for (size_t i(0); i != size; ++i)
 
2283         JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
 
2287 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
 
2288     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2289     id self(internal->GetValue());
 
2291     if (JSStringIsEqualToUTF8CString(property, "$cyi"))
 
2295     NSString *name(CYCastNSString(pool, property));
 
2297     if (CYInternal *internal = CYInternal::Get(self))
 
2298         if (internal->HasProperty(context, property))
 
2301     Class _class(object_getClass(self));
 
2304         // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
 
2305         if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
 
2306             if ([self cy$hasProperty:name])
 
2308     } CYPoolCatch(false)
 
2310     const char *string(CYPoolCString(pool, name));
 
2312     if (class_getProperty(_class, string) != NULL)
 
2315     if (SEL sel = sel_getUid(string))
 
2316         if (CYImplements(self, _class, sel, true))
 
2322 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2323     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2324     id self(internal->GetValue());
 
2326     if (JSStringIsEqualToUTF8CString(property, "$cyi"))
 
2327         return Internal::Make(context, self, object);
 
2331         NSString *name(CYCastNSString(pool, property));
 
2333         if (CYInternal *internal = CYInternal::Get(self))
 
2334             if (JSValueRef value = internal->GetProperty(context, property))
 
2338             if (NSObject *data = [self cy$getProperty:name])
 
2339                 return CYCastJSValue(context, data);
 
2342         const char *string(CYPoolCString(pool, name));
 
2343         Class _class(object_getClass(self));
 
2346         if (objc_property_t property = class_getProperty(_class, string)) {
 
2347             PropertyAttributes attributes(property);
 
2348             SEL sel(sel_registerName(attributes.Getter()));
 
2349             return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
 
2353         if (SEL sel = sel_getUid(string))
 
2354             if (CYImplements(self, _class, sel, true))
 
2355                 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
 
2361 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2362     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2363     id self(internal->GetValue());
 
2368         NSString *name(CYCastNSString(pool, property));
 
2369         NSString *data(CYCastNSObject(pool, context, value));
 
2372             if ([self cy$setProperty:name to:data])
 
2376         const char *string(CYPoolCString(pool, name));
 
2377         Class _class(object_getClass(self));
 
2380         if (objc_property_t property = class_getProperty(_class, string)) {
 
2381             PropertyAttributes attributes(property);
 
2382             if (const char *setter = attributes.Setter()) {
 
2383                 SEL sel(sel_registerName(setter));
 
2384                 JSValueRef arguments[1] = {value};
 
2385                 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
 
2391         size_t length(strlen(string));
 
2393         char set[length + 5];
 
2399         if (string[0] != '\0') {
 
2400             set[3] = toupper(string[0]);
 
2401             memcpy(set + 4, string + 1, length - 1);
 
2404         set[length + 3] = ':';
 
2405         set[length + 4] = '\0';
 
2407         if (SEL sel = sel_getUid(set))
 
2408             if (CYImplements(self, _class, sel, false)) {
 
2409                 JSValueRef arguments[1] = {value};
 
2410                 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
 
2413         if (CYInternal *internal = CYInternal::Set(self)) {
 
2414             internal->SetProperty(context, property, value);
 
2422 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2423     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2424     id self(internal->GetValue());
 
2428             NSString *name(CYCastNSString(NULL, property));
 
2429             return [self cy$deleteProperty:name];
 
2434 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2435     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2436     id self(internal->GetValue());
 
2439     Class _class(object_getClass(self));
 
2443         objc_property_t *data(class_copyPropertyList(_class, &size));
 
2444         for (size_t i(0); i != size; ++i)
 
2445             JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
 
2450 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2452         Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
2453         JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
 
2458 static bool CYIsClass(id self) {
 
2459     // XXX: this is a lame object_isClass
 
2460     return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
 
2463 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
 
2464     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
 
2465     Class _class(internal->GetValue());
 
2466     if (!CYIsClass(_class))
 
2469     if (JSValueIsObjectOfClass(context, instance, Instance_)) {
 
2470         Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
 
2471         // XXX: this isn't always safe
 
2473             return [linternal->GetValue() isKindOfClass:_class];
 
2480 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
 
2481     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2484     id self(internal->GetValue());
 
2485     const char *name(CYPoolCString(pool, property));
 
2487     if (object_getInstanceVariable(self, name, NULL) != NULL)
 
2493 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2494     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2498         id self(internal->GetValue());
 
2499         const char *name(CYPoolCString(pool, property));
 
2501         if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
 
2502             Type_privateData type(pool, ivar_getTypeEncoding(ivar));
 
2503             return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
 
2510 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2511     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2515         id self(internal->GetValue());
 
2516         const char *name(CYPoolCString(pool, property));
 
2518         if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
 
2519             Type_privateData type(pool, ivar_getTypeEncoding(ivar));
 
2520             CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
 
2528 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
 
2529     if (Class super = class_getSuperclass(_class))
 
2530         Internal_getPropertyNames_(super, names);
 
2533     Ivar *data(class_copyIvarList(_class, &size));
 
2534     for (size_t i(0); i != size; ++i)
 
2535         JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
 
2539 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2540     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2543     id self(internal->GetValue());
 
2544     Class _class(object_getClass(self));
 
2546     Internal_getPropertyNames_(_class, names);
 
2549 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2550     Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
 
2551     return internal->GetOwner();
 
2554 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
 
2555     Type_privateData *typical(internal->type_);
 
2556     sig::Type *type(typical->type_);
 
2560     const char *name(CYPoolCString(pool, property));
 
2561     size_t length(strlen(name));
 
2562     double number(CYCastDouble(name, length));
 
2564     size_t count(type->data.signature.count);
 
2566     if (std::isnan(number)) {
 
2567         if (property == NULL)
 
2570         sig::Element *elements(type->data.signature.elements);
 
2572         for (size_t local(0); local != count; ++local) {
 
2573             sig::Element *element(&elements[local]);
 
2574             if (element->name != NULL && strcmp(name, element->name) == 0) {
 
2582         index = static_cast<ssize_t>(number);
 
2583         if (index != number || index < 0 || static_cast<size_t>(index) >= count)
 
2588     ffi_type **elements(typical->GetFFI()->elements);
 
2590     base = reinterpret_cast<uint8_t *>(internal->value_);
 
2591     for (ssize_t local(0); local != index; ++local)
 
2592         base += elements[local]->size;
 
2597 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
 
2598     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
2599     Type_privateData *typical(internal->type_);
 
2601     ffi_type *ffi(typical->GetFFI());
 
2603     uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
 
2604     base += ffi->size * index;
 
2606     JSObjectRef owner(internal->GetOwner() ?: object);
 
2609         return CYFromFFI(context, typical->type_, ffi, base, false, owner);
 
2613 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2615     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
2616     Type_privateData *typical(internal->type_);
 
2618     if (typical->type_ == NULL)
 
2622     if (!CYGetOffset(pool, property, offset))
 
2625     return Pointer_getIndex(context, object, offset, exception);
 
2628 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2629     return Pointer_getIndex(context, object, 0, exception);
 
2632 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
 
2633     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
2634     Type_privateData *typical(internal->type_);
 
2636     ffi_type *ffi(typical->GetFFI());
 
2638     uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
 
2639     base += ffi->size * index;
 
2642         CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
 
2647 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2649     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
2650     Type_privateData *typical(internal->type_);
 
2652     if (typical->type_ == NULL)
 
2656     if (!CYGetOffset(pool, property, offset))
 
2659     return Pointer_setIndex(context, object, offset, value, exception);
 
2662 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2663     return Pointer_setIndex(context, object, 0, value, exception);
 
2666 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2667     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
 
2668     Type_privateData *typical(internal->type_);
 
2669     return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
 
2672 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2674     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
2675     Type_privateData *typical(internal->type_);
 
2680     if (!Index_(pool, internal, property, index, base))
 
2683     JSObjectRef owner(internal->GetOwner() ?: object);
 
2686         return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
 
2690 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
2692     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
2693     Type_privateData *typical(internal->type_);
 
2698     if (!Index_(pool, internal, property, index, base))
 
2702         CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
 
2707 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2708     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
2709     Type_privateData *typical(internal->type_);
 
2710     sig::Type *type(typical->type_);
 
2715     size_t count(type->data.signature.count);
 
2716     sig::Element *elements(type->data.signature.elements);
 
2720     for (size_t index(0); index != count; ++index) {
 
2722         name = elements[index].name;
 
2725             sprintf(number, "%lu", index);
 
2729         JSPropertyNameAccumulatorAddName(names, CYJSString(name));
 
2733 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)()) {
 
2735         if (setups + count != signature->count - 1)
 
2736             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
 
2738         size_t size(setups + count);
 
2740         memcpy(values, setup, sizeof(void *) * setups);
 
2742         for (size_t index(setups); index != size; ++index) {
 
2743             sig::Element *element(&signature->elements[index + 1]);
 
2744             ffi_type *ffi(cif->arg_types[index]);
 
2746             values[index] = new(pool) uint8_t[ffi->size];
 
2747             CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
 
2750         uint8_t value[cif->rtype->size];
 
2751         ffi_call(cif, function, value, values);
 
2753         return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
 
2757 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2760         NSString *name(CYCastNSString(pool, property));
 
2761         if (Class _class = NSClassFromString(name))
 
2762             return CYMakeInstance(context, _class, true);
 
2767 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2768     size_t size(objc_getClassList(NULL, 0));
 
2769     Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
 
2772     size_t writ(objc_getClassList(data, size));
 
2775         if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
 
2781     for (size_t i(0); i != writ; ++i)
 
2782         JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
 
2788 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2789     const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
 
2793         const char *name(CYPoolCString(pool, property));
 
2795         const char **data(objc_copyClassNamesForImage(internal, &size));
 
2797         for (size_t i(0); i != size; ++i)
 
2798             if (strcmp(name, data[i]) == 0) {
 
2799                 if (Class _class = objc_getClass(name)) {
 
2800                     value = CYMakeInstance(context, _class, true);
 
2812 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2813     const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
 
2815     const char **data(objc_copyClassNamesForImage(internal, &size));
 
2816     for (size_t i(0); i != size; ++i)
 
2817         JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
 
2821 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2824         const char *name(CYPoolCString(pool, property));
 
2826         const char **data(objc_copyImageNames(&size));
 
2827         for (size_t i(0); i != size; ++i)
 
2828             if (strcmp(name, data[i]) == 0) {
 
2837         JSObjectRef value(JSObjectMake(context, NULL, NULL));
 
2838         CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
 
2843 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2845     const char **data(objc_copyImageNames(&size));
 
2846     for (size_t i(0); i != size; ++i)
 
2847         JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
 
2851 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2854         NSString *name(CYCastNSString(pool, property));
 
2855         if (Protocol *protocol = NSProtocolFromString(name))
 
2856             return CYMakeInstance(context, protocol, true);
 
2861 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
2863     Protocol **data(objc_copyProtocolList(&size));
 
2864     for (size_t i(0); i != size; ++i)
 
2865         JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
 
2869 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
 
2870     Type_privateData *internal(new Type_privateData(NULL, type));
 
2871     return JSObjectMake(context, Type_privateData::Class_, internal);
 
2874 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
 
2875     Type_privateData *internal(new Type_privateData(type));
 
2876     return JSObjectMake(context, Type_privateData::Class_, internal);
 
2879 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2880     if (JSStringIsEqualToUTF8CString(property, "nil"))
 
2881         return Instance::Make(context, nil);
 
2885         NSString *name(CYCastNSString(pool, property));
 
2886         if (Class _class = NSClassFromString(name))
 
2887             return CYMakeInstance(context, _class, true);
 
2888         if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
 
2889             switch ([[entry objectAtIndex:0] intValue]) {
 
2891                     return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
 
2893                     return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
 
2895                     // XXX: this is horrendously inefficient
 
2896                     sig::Signature signature;
 
2897                     sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
 
2899                     sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
 
2900                     return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
 
2902         if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
 
2903             switch ([[entry objectAtIndex:0] intValue]) {
 
2904                 // XXX: implement case 0
 
2906                     return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
 
2912 static bool stret(ffi_type *ffi_type) {
 
2913     return ffi_type->type == FFI_TYPE_STRUCT && (
 
2914         ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
 
2915         struct_forward_array[ffi_type->size] != 0
 
2920     int *_NSGetArgc(void);
 
2921     char ***_NSGetArgv(void);
 
2924 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2929             NSLog(@"%s", CYCastCString(context, arguments[0]));
 
2930         return CYJSUndefined(context);
 
2934 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
 
2937     Class _class(object_getClass(self));
 
2938     if (Method method = class_getInstanceMethod(_class, _cmd))
 
2939         type = method_getTypeEncoding(method);
 
2943                 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
 
2945                     @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
 
2946                 type = CYPoolCString(pool, [method _typeString]);
 
2955     sig::Signature signature;
 
2956     sig::Parse(pool, &signature, type, &Structor_);
 
2959     sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
 
2961     void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
 
2962     return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
 
2965 static size_t Nonce_(0);
 
2967 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2969     sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
 
2970     return CYCastJSValue(context, name);
 
2973 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2983             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
 
2985         if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
 
2986             Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
 
2987             self = internal->GetValue();
 
2988             uninitialized = internal->IsUninitialized();
 
2990                 internal->value_ = nil;
 
2992             self = CYCastNSObject(pool, context, arguments[0]);
 
2993             uninitialized = false;
 
2997             return CYJSNull(context);
 
2999         _cmd = CYCastSEL(context, arguments[1]);
 
3002     return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
 
3005 /* Hook: objc_registerClassPair {{{ */
 
3006 // XXX: replace this with associated objects
 
3008 MSHook(void, CYDealloc, id self, SEL sel) {
 
3009     CYInternal *internal;
 
3010     object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
 
3011     if (internal != NULL)
 
3013     _CYDealloc(self, sel);
 
3016 MSHook(void, objc_registerClassPair, Class _class) {
 
3017     Class super(class_getSuperclass(_class));
 
3018     if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
 
3019         class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
 
3020         MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
 
3023     _objc_registerClassPair(_class);
 
3026 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3029             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
 
3031         Class _class(CYCastNSObject(pool, context, arguments[0]));
 
3032         $objc_registerClassPair(_class);
 
3033         return CYJSUndefined(context);
 
3038 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3039     JSGarbageCollect(context);
 
3040     return CYJSUndefined(context);
 
3043 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3044     JSValueRef setup[count + 2];
 
3047     memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
 
3048     return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
 
3051 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3053     Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
 
3055     // XXX: handle Instance::Uninitialized?
 
3056     id self(CYCastNSObject(pool, context, _this));
 
3060     setup[1] = &internal->sel_;
 
3062     return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
 
3065 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3067     Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
 
3068     return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
 
3071 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3074             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
 
3075         const char *name(CYCastCString(context, arguments[0]));
 
3076         return CYMakeSelector(context, sel_registerName(name));
 
3080 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3083             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
 
3085         void *value(CYCastPointer<void *>(context, arguments[0]));
 
3086         const char *type(CYCastCString(context, arguments[1]));
 
3090         sig::Signature signature;
 
3091         sig::Parse(pool, &signature, type, &Structor_);
 
3093         return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
 
3097 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3100             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
 
3101         const char *type(CYCastCString(context, arguments[0]));
 
3102         return CYMakeType(context, type);
 
3106 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3107     Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
 
3112         if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
 
3113             type.primitive = sig::pointer_P;
 
3114             type.data.data.size = 0;
 
3116             size_t index(CYGetIndex(NULL, property));
 
3117             if (index == _not(size_t))
 
3119             type.primitive = sig::array_P;
 
3120             type.data.data.size = index;
 
3126         type.data.data.type = internal->type_;
 
3128         return CYMakeType(context, &type);
 
3132 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3133     Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
 
3137             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
 
3138         sig::Type *type(internal->type_);
 
3139         ffi_type *ffi(internal->GetFFI());
 
3141         uint8_t value[ffi->size];
 
3143         CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
 
3144         return CYFromFFI(context, type, ffi, value);
 
3148 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3151             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
 
3152         Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
 
3154         sig::Type *type(internal->type_);
 
3157         if (type->primitive != sig::array_P)
 
3160             size = type->data.data.size;
 
3161             type = type->data.data.type;
 
3164         void *value(malloc(internal->GetFFI()->size));
 
3165         return CYMakePointer(context, value, type, NULL, NULL);
 
3169 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3172             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
 
3173         id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
 
3174         return Instance::Make(context, self);
 
3178 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3181             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
 
3182         const char *type(CYCastCString(context, arguments[1]));
 
3183         return CYMakeFunctor(context, arguments[0], type);
 
3187 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3188     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
 
3189     return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
 
3192 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3193     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
3194     Type_privateData *typical(internal->GetType());
 
3199     if (typical == NULL) {
 
3203         type = typical->type_;
 
3204         ffi = typical->ffi_;
 
3207     return CYMakePointer(context, &internal->value_, type, ffi, object);
 
3210 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3211     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
3214         return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
 
3218 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3219     return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
 
3222 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3223     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
3225     sprintf(string, "%p", internal->value_);
 
3228         return CYCastJSValue(context, string);
 
3232 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3233     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
3234     return Instance::Make(context, object_getClass(internal->GetValue()));
 
3237 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3238     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
3239     id self(internal->GetValue());
 
3240     if (!CYIsClass(self))
 
3241         return CYJSUndefined(context);
 
3243         return CYGetClassPrototype(context, self);
 
3247 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
3248     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
3249     id self(internal->GetValue());
 
3250     if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
 
3251         return CYJSUndefined(context);
 
3252     return Messages::Make(context, self);
 
3255 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3256     if (!JSValueIsObjectOfClass(context, _this, Instance_))
 
3259     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
3263             return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
 
3268 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3269     if (!JSValueIsObjectOfClass(context, _this, Instance_))
 
3272     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
3276             NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
 
3277             // XXX: check for support of cy$toJSON?
 
3278             return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
 
3283 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3284     if (!JSValueIsObjectOfClass(context, _this, Instance_))
 
3287     Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
3291             return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
 
3296 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3297     Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
3300         return CYCastJSValue(context, sel_getName(internal->GetValue()));
 
3304 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3305     return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
 
3308 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3309     Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
3310     const char *name(sel_getName(internal->GetValue()));
 
3314             return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
 
3319 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3322             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
 
3324         Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
3325         Class _class(CYCastNSObject(pool, context, arguments[0]));
 
3326         SEL sel(internal->GetValue());
 
3327         Method method(class_getInstanceMethod(_class, sel));
 
3328         const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
 
3329         return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
 
3333 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3335         Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
 
3337         const char *type(sig::Unparse(pool, internal->type_));
 
3339             return CYCastJSValue(context, CYJSString(type));
 
3344 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3346         Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
 
3348         const char *type(sig::Unparse(pool, internal->type_));
 
3350             return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
 
3355 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
3356     return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
 
3359 static JSStaticValue CYValue_staticValues[2] = {
 
3360     {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
 
3361     {NULL, NULL, NULL, 0}
 
3364 static JSStaticValue Pointer_staticValues[2] = {
 
3365     {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3366     {NULL, NULL, NULL, 0}
 
3369 static JSStaticFunction Pointer_staticFunctions[4] = {
 
3370     {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3371     {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3372     {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3376 static JSStaticFunction Struct_staticFunctions[2] = {
 
3377     {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3381 static JSStaticFunction Functor_staticFunctions[4] = {
 
3382     {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3383     {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3384     {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3388 static JSStaticValue Instance_staticValues[5] = {
 
3389     {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3390     {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3391     {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3392     {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3393     {NULL, NULL, NULL, 0}
 
3396 static JSStaticFunction Instance_staticFunctions[5] = {
 
3397     {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3398     {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3399     {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3400     {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3404 static JSStaticFunction Internal_staticFunctions[2] = {
 
3405     {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3409 static JSStaticFunction Selector_staticFunctions[5] = {
 
3410     {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3411     {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3412     {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3413     {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3417 static JSStaticFunction Type_staticFunctions[4] = {
 
3418     {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3419     {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3420     {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
3424 void CYSetArgs(int argc, const char *argv[]) {
 
3425     JSContextRef context(CYGetJSContext());
 
3426     JSValueRef args[argc];
 
3427     for (int i(0); i != argc; ++i)
 
3428         args[i] = CYCastJSValue(context, argv[i]);
 
3429     JSValueRef exception(NULL);
 
3430     JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
 
3431     CYThrow(context, exception);
 
3432     CYSetProperty(context, System_, CYJSString("args"), array);
 
3435 JSObjectRef CYGetGlobalObject(JSContextRef context) {
 
3436     return JSContextGetGlobalObject(context);
 
3439 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
 
3440     JSContextRef context(CYGetJSContext());
 
3441     JSValueRef exception(NULL), result;
 
3444         result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
 
3445     } catch (const char *error) {
 
3449     if (exception != NULL) { error:
 
3454     if (JSValueIsUndefined(context, result))
 
3460         json = CYPoolCCYON(pool, context, result, &exception);
 
3461     } catch (const char *error) {
 
3465     if (exception != NULL)
 
3468     CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
 
3472 static apr_pool_t *Pool_;
 
3476     const char * volatile data_;
 
3479 // XXX: this is "tre lame"
 
3480 @interface CYClient_ : NSObject {
 
3483 - (void) execute:(NSValue *)value;
 
3487 @implementation CYClient_
 
3489 - (void) execute:(NSValue *)value {
 
3490     CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
 
3491     const char *data(execute->data_);
 
3492     execute->data_ = NULL;
 
3493     execute->data_ = CYExecute(execute->pool_, data);
 
3502     apr_thread_t *thread_;
 
3504     CYClient(int socket) :
 
3510         _syscall(close(socket_));
 
3513     void Handle() { _pooled
 
3514         CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
 
3518             if (!CYRecvAll(socket_, &size, sizeof(size)))
 
3522             char *data(new(pool) char[size + 1]);
 
3523             if (!CYRecvAll(socket_, data, size))
 
3527             CYDriver driver("");
 
3528             cy::parser parser(driver);
 
3530             driver.data_ = data;
 
3531             driver.size_ = size;
 
3534             if (parser.parse() != 0 || !driver.errors_.empty()) {
 
3536                 size = _not(size_t);
 
3538                 CYContext context(driver.pool_);
 
3539                 driver.program_->Replace(context);
 
3540                 std::ostringstream str;
 
3542                 out << *driver.program_;
 
3543                 std::string code(str.str());
 
3544                 CYExecute_ execute = {pool, code.c_str()};
 
3545                 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
 
3546                 json = execute.data_;
 
3547                 size = json == NULL ? _not(size_t) : strlen(json);
 
3550             if (!CYSendAll(socket_, &size, sizeof(size)))
 
3553                 if (!CYSendAll(socket_, json, size))
 
3559 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
 
3560     CYClient *client(reinterpret_cast<CYClient *>(data));
 
3566 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
 
3567     CYClient *client(new(pool) CYClient(socket));
 
3568     apr_threadattr_t *attr;
 
3569     _aprcall(apr_threadattr_create(&attr, client->pool_));
 
3570     _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
 
3573 MSInitialize { _pooled
 
3574     _aprcall(apr_initialize());
 
3575     _aprcall(apr_pool_create(&Pool_, NULL));
 
3577     Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
 
3578     Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
 
3580     Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
 
3583     NSCFBoolean_ = objc_getClass("NSCFBoolean");
 
3584     NSCFType_ = objc_getClass("NSCFType");
 
3587     NSArray_ = objc_getClass("NSArray");
 
3588     NSDictionary_ = objc_getClass("NSDictonary");
 
3589     NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
 
3590     NSZombie_ = objc_getClass("_NSZombie_");
 
3591     Object_ = objc_getClass("Object");
 
3594 JSGlobalContextRef CYGetJSContext() {
 
3595     if (Context_ == NULL) {
 
3596         JSClassDefinition definition;
 
3598         definition = kJSClassDefinitionEmpty;
 
3599         definition.className = "Functor";
 
3600         definition.staticFunctions = Functor_staticFunctions;
 
3601         definition.callAsFunction = &Functor_callAsFunction;
 
3602         definition.finalize = &Finalize;
 
3603         Functor_ = JSClassCreate(&definition);
 
3605         definition = kJSClassDefinitionEmpty;
 
3606         definition.className = "Instance";
 
3607         definition.staticValues = Instance_staticValues;
 
3608         definition.staticFunctions = Instance_staticFunctions;
 
3609         definition.hasProperty = &Instance_hasProperty;
 
3610         definition.getProperty = &Instance_getProperty;
 
3611         definition.setProperty = &Instance_setProperty;
 
3612         definition.deleteProperty = &Instance_deleteProperty;
 
3613         definition.getPropertyNames = &Instance_getPropertyNames;
 
3614         definition.callAsConstructor = &Instance_callAsConstructor;
 
3615         definition.hasInstance = &Instance_hasInstance;
 
3616         definition.finalize = &Finalize;
 
3617         Instance_ = JSClassCreate(&definition);
 
3619         definition = kJSClassDefinitionEmpty;
 
3620         definition.className = "Internal";
 
3621         definition.staticFunctions = Internal_staticFunctions;
 
3622         definition.hasProperty = &Internal_hasProperty;
 
3623         definition.getProperty = &Internal_getProperty;
 
3624         definition.setProperty = &Internal_setProperty;
 
3625         definition.getPropertyNames = &Internal_getPropertyNames;
 
3626         definition.finalize = &Finalize;
 
3627         Internal_ = JSClassCreate(&definition);
 
3629         definition = kJSClassDefinitionEmpty;
 
3630         definition.className = "Message";
 
3631         definition.staticFunctions = Functor_staticFunctions;
 
3632         definition.callAsFunction = &Message_callAsFunction;
 
3633         definition.finalize = &Finalize;
 
3634         Message_ = JSClassCreate(&definition);
 
3636         definition = kJSClassDefinitionEmpty;
 
3637         definition.className = "Messages";
 
3638         definition.hasProperty = &Messages_hasProperty;
 
3639         definition.getProperty = &Messages_getProperty;
 
3640         definition.setProperty = &Messages_setProperty;
 
3642         definition.deleteProperty = &Messages_deleteProperty;
 
3644         definition.getPropertyNames = &Messages_getPropertyNames;
 
3645         definition.finalize = &Finalize;
 
3646         Messages_ = JSClassCreate(&definition);
 
3648         definition = kJSClassDefinitionEmpty;
 
3649         definition.className = "NSArrayPrototype";
 
3650         //definition.hasProperty = &NSArrayPrototype_hasProperty;
 
3651         //definition.getProperty = &NSArrayPrototype_getProperty;
 
3652         //definition.setProperty = &NSArrayPrototype_setProperty;
 
3653         //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
 
3654         //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
 
3655         NSArrayPrototype_ = JSClassCreate(&definition);
 
3657         definition = kJSClassDefinitionEmpty;
 
3658         definition.className = "Pointer";
 
3659         definition.staticValues = Pointer_staticValues;
 
3660         definition.staticFunctions = Pointer_staticFunctions;
 
3661         definition.getProperty = &Pointer_getProperty;
 
3662         definition.setProperty = &Pointer_setProperty;
 
3663         definition.finalize = &Finalize;
 
3664         Pointer_ = JSClassCreate(&definition);
 
3666         definition = kJSClassDefinitionEmpty;
 
3667         definition.className = "Selector";
 
3668         definition.staticValues = CYValue_staticValues;
 
3669         definition.staticFunctions = Selector_staticFunctions;
 
3670         definition.callAsFunction = &Selector_callAsFunction;
 
3671         definition.finalize = &Finalize;
 
3672         Selector_ = JSClassCreate(&definition);
 
3674         definition = kJSClassDefinitionEmpty;
 
3675         definition.className = "Struct";
 
3676         definition.staticFunctions = Struct_staticFunctions;
 
3677         definition.getProperty = &Struct_getProperty;
 
3678         definition.setProperty = &Struct_setProperty;
 
3679         definition.getPropertyNames = &Struct_getPropertyNames;
 
3680         definition.finalize = &Finalize;
 
3681         Struct_ = JSClassCreate(&definition);
 
3683         definition = kJSClassDefinitionEmpty;
 
3684         definition.className = "Type";
 
3685         definition.staticFunctions = Type_staticFunctions;
 
3686         definition.getProperty = &Type_getProperty;
 
3687         definition.callAsFunction = &Type_callAsFunction;
 
3688         definition.callAsConstructor = &Type_callAsConstructor;
 
3689         definition.finalize = &Finalize;
 
3690         Type_privateData::Class_ = JSClassCreate(&definition);
 
3692         definition = kJSClassDefinitionEmpty;
 
3693         definition.className = "Runtime";
 
3694         definition.getProperty = &Runtime_getProperty;
 
3695         Runtime_ = JSClassCreate(&definition);
 
3697         definition = kJSClassDefinitionEmpty;
 
3698         definition.className = "ObjectiveC::Classes";
 
3699         definition.getProperty = &ObjectiveC_Classes_getProperty;
 
3700         definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
 
3701         ObjectiveC_Classes_ = JSClassCreate(&definition);
 
3703         definition = kJSClassDefinitionEmpty;
 
3704         definition.className = "ObjectiveC::Images";
 
3705         definition.getProperty = &ObjectiveC_Images_getProperty;
 
3706         definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
 
3707         ObjectiveC_Images_ = JSClassCreate(&definition);
 
3709         definition = kJSClassDefinitionEmpty;
 
3710         definition.className = "ObjectiveC::Image::Classes";
 
3711         definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
 
3712         definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
 
3713         ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
 
3715         definition = kJSClassDefinitionEmpty;
 
3716         definition.className = "ObjectiveC::Protocols";
 
3717         definition.getProperty = &ObjectiveC_Protocols_getProperty;
 
3718         definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
 
3719         ObjectiveC_Protocols_ = JSClassCreate(&definition);
 
3721         definition = kJSClassDefinitionEmpty;
 
3722         //definition.getProperty = &Global_getProperty;
 
3723         JSClassRef Global(JSClassCreate(&definition));
 
3725         JSGlobalContextRef context(JSGlobalContextCreate(Global));
 
3728         JSObjectRef global(CYGetGlobalObject(context));
 
3730         JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
 
3731         ObjectiveC_ = JSObjectMake(context, NULL, NULL);
 
3732         CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
 
3734         CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
 
3735         CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
 
3736         CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
 
3738         Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
 
3739         Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
 
3740         String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
 
3742         length_ = JSStringCreateWithUTF8CString("length");
 
3743         message_ = JSStringCreateWithUTF8CString("message");
 
3744         name_ = JSStringCreateWithUTF8CString("name");
 
3745         prototype_ = JSStringCreateWithUTF8CString("prototype");
 
3746         toCYON_ = JSStringCreateWithUTF8CString("toCYON");
 
3747         toJSON_ = JSStringCreateWithUTF8CString("toJSON");
 
3749         JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
 
3750         Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
 
3752         Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
 
3753         Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
 
3754         Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
 
3755         Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
 
3757         JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
 
3758         JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
 
3759         JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
 
3760         JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
 
3762         Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
 
3764         JSValueRef function(CYGetProperty(context, Function_, prototype_));
 
3765         JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
 
3766         JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
 
3767         JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
 
3769         CYSetProperty(context, global, CYJSString("Functor"), Functor);
 
3770         CYSetProperty(context, global, CYJSString("Instance"), Instance);
 
3771         CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
 
3772         CYSetProperty(context, global, CYJSString("Selector"), Selector);
 
3773         CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
 
3775         MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
 
3778         class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
 
3781         JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
 
3782         CYSetProperty(context, global, CYJSString("Cycript"), cycript);
 
3783         CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
 
3785         CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
 
3786         CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
 
3787         CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
 
3789         System_ = JSObjectMake(context, NULL, NULL);
 
3790         CYSetProperty(context, global, CYJSString("system"), System_);
 
3791         CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
 
3792         //CYSetProperty(context, System_, CYJSString("global"), global);
 
3794         CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
 
3796         Result_ = JSStringCreateWithUTF8CString("_");
 
3798         JSValueProtect(context, Array_);
 
3799         JSValueProtect(context, Function_);
 
3800         JSValueProtect(context, String_);
 
3802         JSValueProtect(context, Instance_prototype_);
 
3803         JSValueProtect(context, Object_prototype_);
 
3805         JSValueProtect(context, Array_prototype_);
 
3806         JSValueProtect(context, Array_pop_);
 
3807         JSValueProtect(context, Array_push_);
 
3808         JSValueProtect(context, Array_splice_);