]> git.saurik.com Git - cycript.git/blobdiff - Library.mm
Renamed Application.cpp to Console.cpp.
[cycript.git] / Library.mm
index 0083fb54551b713e1cb45771bebbd950632fa092..2eeb1c7738a6ba44052506c8d82cdcb2b9ec8dff 100644 (file)
@@ -58,6 +58,8 @@
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
+#include <sys/un.h>
+
 #include <sys/mman.h>
 
 #include <iostream>
 #include <set>
 #include <map>
 
+#include <sstream>
 #include <cmath>
 
 #include "Parser.hpp"
 #include "Cycript.tab.hh"
 
+#include <fcntl.h>
+
+#include <apr-1/apr_thread_proc.h>
+
 #undef _assert
 #undef _trace
 
 
 static JSGlobalContextRef Context_;
 static JSObjectRef System_;
+static JSObjectRef ObjectiveC_;
 
 static JSClassRef Functor_;
 static JSClassRef Instance_;
+static JSClassRef Internal_;
 static JSClassRef Pointer_;
 static JSClassRef Runtime_;
 static JSClassRef Selector_;
 static JSClassRef Struct_;
+static JSClassRef Type_;
+
+static JSClassRef ObjectiveC_Classes_;
+static JSClassRef ObjectiveC_Image_Classes_;
+static JSClassRef ObjectiveC_Images_;
+static JSClassRef ObjectiveC_Protocols_;
 
 static JSObjectRef Array_;
 static JSObjectRef Function_;
 
+static JSStringRef Result_;
+
 static JSStringRef length_;
 static JSStringRef message_;
 static JSStringRef name_;
@@ -118,6 +135,10 @@ static JSStringRef toCYON_;
 static JSStringRef toJSON_;
 
 static Class NSCFBoolean_;
+static Class NSCFType_;
+static Class NSMessageBuilder_;
+static Class NSZombie_;
+static Class Object_;
 
 static NSArray *Bridge_;
 
@@ -127,39 +148,51 @@ struct CYData {
     virtual ~CYData() {
     }
 
-    void *operator new(size_t size) {
-        apr_pool_t *pool;
-        apr_pool_create(&pool, NULL);
+    static void *operator new(size_t size, apr_pool_t *pool) {
         void *data(apr_palloc(pool, size));
         reinterpret_cast<CYData *>(data)->pool_ = pool;
-        return data;;
+        return data;
+    }
+
+    static void *operator new(size_t size) {
+        apr_pool_t *pool;
+        apr_pool_create(&pool, NULL);
+        return operator new(size, pool);
+    }
+
+    static void operator delete(void *data) {
+        apr_pool_destroy(reinterpret_cast<CYData *>(data)->pool_);
     }
 
     static void Finalize(JSObjectRef object) {
-        CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
-        data->~CYData();
-        apr_pool_destroy(data->pool_);
+        delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
     }
 };
 
-struct Pointer_privateData :
+struct CYValue :
     CYData
 {
     void *value_;
-    sig::Type type_;
 
-    Pointer_privateData() {
+    CYValue() {
     }
 
-    Pointer_privateData(void *value) :
+    CYValue(void *value) :
         value_(value)
     {
     }
+
+    CYValue(const CYValue &rhs) :
+        value_(rhs.value_)
+    {
+    }
 };
 
-struct Selector_privateData : Pointer_privateData {
+struct Selector_privateData :
+    CYValue
+{
     Selector_privateData(SEL value) :
-        Pointer_privateData(value)
+        CYValue(value)
     {
     }
 
@@ -168,19 +201,55 @@ struct Selector_privateData : Pointer_privateData {
     }
 };
 
-struct Instance_privateData :
-    Pointer_privateData
+struct Instance :
+    CYValue
+{
+    enum Flags {
+        None          = 0,
+        Transient     = (1 << 0),
+        Uninitialized = (1 << 1),
+    };
+
+    Flags flags_;
+
+    Instance(id value, Flags flags) :
+        CYValue(value),
+        flags_(flags)
+    {
+    }
+
+    virtual ~Instance() {
+        if ((flags_ & Transient) == 0)
+            // XXX: does this handle background threads correctly?
+            [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
+    }
+
+    static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
+        return JSObjectMake(context, Instance_, new Instance(object, flags));
+    }
+
+    id GetValue() const {
+        return reinterpret_cast<id>(value_);
+    }
+
+    bool IsUninitialized() const {
+        return (flags_ & Uninitialized) != 0;
+    }
+};
+
+struct Internal :
+    CYValue
 {
-    bool transient_;
+    JSObjectRef owner_;
 
-    Instance_privateData(id value, bool transient) :
-        Pointer_privateData(value)
+    Internal(id value, JSObjectRef owner) :
+        CYValue(value),
+        owner_(owner)
     {
     }
 
-    virtual ~Instance_privateData() {
-        if (!transient_)
-            [GetValue() release];
+    static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
+        return JSObjectMake(context, Internal_, new Internal(object, owner));
     }
 
     id GetValue() const {
@@ -261,23 +330,106 @@ struct CStringMapLess :
     }
 };
 
-struct Type_privateData {
-    sig::Type type_;
-    ffi_type ffi_;
+void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
+    if (name == NULL)
+        return;
+
+    CYPoolTry {
+        if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
+            switch ([[entry objectAtIndex:0] intValue]) {
+                case 0: {
+                    sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
+                } break;
+
+                case 1: {
+                    sig::Signature signature;
+                    sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
+                    type = signature.elements[0].type;
+                } break;
+            }
+    } CYPoolCatch()
+}
+
+struct Type_privateData :
+    CYData
+{
+    ffi_type *ffi_;
+    sig::Type *type_;
+
+    void Set(sig::Type *type) {
+        type_ = new(pool_) sig::Type;
+        sig::Copy(pool_, *type_, *type);
+    }
+
+    Type_privateData(apr_pool_t *pool, const char *type) :
+        ffi_(NULL)
+    {
+        if (pool != NULL)
+            pool_ = pool;
+
+        sig::Signature signature;
+        sig::Parse(pool_, &signature, type, &Structor_);
+        type_ = signature.elements[0].type;
+    }
+
+    Type_privateData(sig::Type *type) :
+        ffi_(NULL)
+    {
+        if (type != NULL)
+            Set(type);
+    }
+
+    Type_privateData(sig::Type *type, ffi_type *ffi) {
+        ffi_ = new(pool_) ffi_type;
+        sig::Copy(pool_, *ffi_, *ffi);
+        Set(type);
+    }
+
+    ffi_type *GetFFI() {
+        if (ffi_ == NULL) {
+            ffi_ = new(pool_) ffi_type;
+
+            sig::Element element;
+            element.name = NULL;
+            element.type = type_;
+            element.offset = 0;
+
+            sig::Signature signature;
+            signature.elements = &element;
+            signature.count = 1;
+
+            ffi_cif cif;
+            sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
+            *ffi_ = *cif.rtype;
+        }
+
+        return ffi_;
+    }
+};
+
+struct Pointer :
+    CYValue
+{
+    JSObjectRef owner_;
+    Type_privateData *type_;
 
-    Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) {
-        sig::Copy(pool, type_, *type);
-        sig::Copy(pool, ffi_, *ffi);
+    Pointer(void *value, sig::Type *type, JSObjectRef owner) :
+        CYValue(value),
+        owner_(owner),
+        type_(new(pool_) Type_privateData(type))
+    {
     }
 };
 
 struct Struct_privateData :
-    Pointer_privateData
+    CYValue
 {
     JSObjectRef owner_;
     Type_privateData *type_;
 
-    Struct_privateData() {
+    Struct_privateData(JSObjectRef owner) :
+        owner_(owner)
+    {
     }
 };
 
@@ -285,18 +437,15 @@ typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
 static TypeMap Types_;
 
 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
-    Struct_privateData *internal(new Struct_privateData());
+    Struct_privateData *internal(new Struct_privateData(owner));
     apr_pool_t *pool(internal->pool_);
-    Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
+    Type_privateData *typical(new(pool) Type_privateData(type, ffi));
     internal->type_ = typical;
 
-    if (owner != NULL) {
-        internal->owner_ = owner;
+    if (owner != NULL)
         internal->value_ = data;
-    } else {
-        internal->owner_ = NULL;
-
-        size_t size(typical->ffi_.size);
+    else {
+        size_t size(typical->GetFFI()->size);
         void *copy(apr_palloc(internal->pool_, size));
         memcpy(copy, data, size);
         internal->value_ = copy;
@@ -305,27 +454,14 @@ JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_
     return JSObjectMake(context, Struct_, internal);
 }
 
-void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *type) {
-    CYPoolTry {
-        if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]]) {
-            switch ([[entry objectAtIndex:0] intValue]) {
-                case 0:
-                    static CYPool Pool_;
-                    sig::Parse(Pool_, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
-                break;
-            }
-        }
-    } CYPoolCatch()
-}
-
 struct Functor_privateData :
-    Pointer_privateData
+    CYValue
 {
     sig::Signature signature_;
     ffi_cif cif_;
 
     Functor_privateData(const char *type, void (*value)()) :
-        Pointer_privateData(reinterpret_cast<void *>(value))
+        CYValue(reinterpret_cast<void *>(value))
     {
         sig::Parse(pool_, &signature_, type, &Structor_);
         sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
@@ -345,10 +481,16 @@ struct ffoData :
 };
 
 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
-    if (!transient)
+    Instance::Flags flags;
+
+    if (transient)
+        flags = Instance::Transient;
+    else {
+        flags = Instance::None;
         object = [object retain];
-    Instance_privateData *data(new Instance_privateData(object, transient));
-    return JSObjectMake(context, Instance_, data);
+    }
+
+    return Instance::Make(context, object, flags);
 }
 
 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
@@ -387,49 +529,50 @@ JSValueRef CYJSUndefined(JSContextRef context) {
     return JSValueMakeUndefined(context);
 }
 
-size_t CYCastIndex(const char *value) {
-    if (value[0] == '0') {
-        if (value[1] == '\0')
-            return 0;
-    } else {
+bool CYGetIndex(const char *value, ssize_t &index) {
+    if (value[0] != '0') {
         char *end;
-        size_t index(strtoul(value, &end, 10));
+        index = strtol(value, &end, 10);
         if (value + strlen(value) == end)
-            return index;
+            return true;
+    } else if (value[1] == '\0') {
+        index = 0;
+        return true;
     }
 
-    return _not(size_t);
+    return false;
 }
 
-size_t CYCastIndex(NSString *value) {
-    return CYCastIndex([value UTF8String]);
+bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
+    return CYGetIndex(CYPoolCString(pool, value), index);
 }
 
+NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
+
 @interface NSMethodSignature (Cycript)
 - (NSString *) _typeString;
 @end
 
 @interface NSObject (Cycript)
 
+- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 - (JSType) cy$JSType;
 
 - (NSObject *) cy$toJSON:(NSString *)key;
 - (NSString *) cy$toCYON;
 - (NSString *) cy$toKey;
 
-- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
-
 - (NSObject *) cy$getProperty:(NSString *)name;
 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
 - (bool) cy$deleteProperty:(NSString *)name;
 
 @end
 
-@interface NSString (Cycript)
-- (void *) cy$symbol;
+@protocol Cycript
+- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 @end
 
-@interface NSNumber (Cycript)
+@interface NSString (Cycript)
 - (void *) cy$symbol;
 @end
 
@@ -519,8 +662,24 @@ struct PropertyAttributes {
 
 };
 
+@implementation NSProxy (Cycript)
+
+- (NSObject *) cy$toJSON:(NSString *)key {
+    return [self description];
+}
+
+- (NSString *) cy$toCYON {
+    return [[self cy$toJSON:@""] cy$toCYON];
+}
+
+@end
+
 @implementation NSObject (Cycript)
 
+- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
+    return CYMakeInstance(context, self, false);
+}
+
 - (JSType) cy$JSType {
     return kJSTypeObject;
 }
@@ -537,10 +696,6 @@ struct PropertyAttributes {
     return [self cy$toCYON];
 }
 
-- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
-    return CYMakeInstance(context, self, transient);
-}
-
 - (NSObject *) cy$getProperty:(NSString *)name {
     /*if (![name isEqualToString:@"prototype"])
         NSLog(@"get:%@", name);*/
@@ -559,6 +714,10 @@ struct PropertyAttributes {
 
 @end
 
+NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
+    return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
+}
+
 @implementation WebUndefined (Cycript)
 
 - (JSType) cy$JSType {
@@ -573,7 +732,7 @@ struct PropertyAttributes {
     return @"undefined";
 }
 
-- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
+- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
     return CYJSUndefined(context);
 }
 
@@ -608,7 +767,7 @@ struct PropertyAttributes {
         else
             comma = true;
         if ([object cy$JSType] != kJSTypeUndefined)
-            [json appendString:[object cy$toCYON]];
+            [json appendString:CYPoolNSCYON(NULL, object)];
         else {
             [json appendString:@","];
             comma = false;
@@ -623,8 +782,8 @@ struct PropertyAttributes {
     if ([name isEqualToString:@"length"])
         return [NSNumber numberWithUnsignedInteger:[self count]];
 
-    size_t index(CYCastIndex(name));
-    if (index == _not(size_t) || index >= [self count])
+    ssize_t index;
+    if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
         return [super cy$getProperty:name];
     else
         return [self objectAtIndex:index];
@@ -635,8 +794,8 @@ struct PropertyAttributes {
 @implementation NSMutableArray (Cycript)
 
 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
-    size_t index(CYCastIndex(name));
-    if (index == _not(size_t) || index >= [self count])
+    ssize_t index;
+    if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
         return [super cy$setProperty:name to:value];
     else {
         [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
@@ -645,8 +804,8 @@ struct PropertyAttributes {
 }
 
 - (bool) cy$deleteProperty:(NSString *)name {
-    size_t index(CYCastIndex(name));
-    if (index == _not(size_t) || index >= [self count])
+    ssize_t index;
+    if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
         return [super cy$deleteProperty:name];
     else {
         [self removeObjectAtIndex:index];
@@ -671,7 +830,7 @@ struct PropertyAttributes {
         [json appendString:[key cy$toKey]];
         [json appendString:@":"];
         NSObject *object([self objectForKey:key]);
-        [json appendString:[object cy$toCYON]];
+        [json appendString:CYPoolNSCYON(NULL, object)];
     }
 
     [json appendString:@"}"];
@@ -717,14 +876,10 @@ struct PropertyAttributes {
     return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
 }
 
-- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
+- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
     return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
 }
 
-- (void *) cy$symbol {
-    return [self pointerValue];
-}
-
 @end
 
 @implementation NSString (Cycript)
@@ -761,7 +916,8 @@ struct PropertyAttributes {
         goto cyon;
 
     if (DigitRange_[value[0]]) {
-        if (CYCastIndex(self) == _not(size_t))
+        ssize_t index;
+        if (!CYGetIndex(NULL, self, index) || index < 0)
             goto cyon;
     } else {
         if (!WordStartRange_[value[0]])
@@ -817,10 +973,6 @@ CYRange DigitRange_    (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
 CYRange WordEndRange_  (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
 
-JSGlobalContextRef CYGetJSContext() {
-    return Context_;
-}
-
 #define CYTry \
     @try
 #define CYCatch \
@@ -852,12 +1004,7 @@ CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
     return (CFTypeRef) CYPoolRelease(pool, (id) object);
 }
 
-id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
-    if (JSValueIsObjectOfClass(context, object, Instance_)) {
-        Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
-        return data->GetValue();
-    }
-
+id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
     JSValueRef exception(NULL);
     bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
     CYThrow(context, exception);
@@ -865,6 +1012,15 @@ id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
     return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
 }
 
+id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
+    if (!JSValueIsObjectOfClass(context, object, Instance_))
+        return CYCastNSObject_(pool, context, object);
+    else {
+        Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
+        return data->GetValue();
+    }
+}
+
 JSStringRef CYCopyJSString(id value) {
     return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
 }
@@ -1068,8 +1224,13 @@ JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
     return CYCastJSValue(context, CYJSString(value));
 }
 
-JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
-    return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
+JSValueRef CYCastJSValue(JSContextRef context, id value) {
+    if (value == nil)
+        return CYJSNull(context);
+    else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
+        return [value cy$JSValueInContext:context];
+    else
+        return CYMakeInstance(context, value, false);
 }
 
 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
@@ -1172,8 +1333,7 @@ bool CYIsCallable(JSContextRef context, JSValueRef value) {
 
 - (void) removeObjectForKey:(id)key {
     JSValueRef exception(NULL);
-    // XXX: this returns a bool... throw exception, or ignore?
-    JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
+    (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
     CYThrow(context_, exception);
 }
 
@@ -1201,96 +1361,114 @@ bool CYIsCallable(JSContextRef context, JSValueRef value) {
 
 @end
 
-CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
+NSString *CYCopyNSCYON(id value) {
+    Class _class(object_getClass(value));
+    SEL sel(@selector(cy$toCYON));
+
+    NSString *string;
+
+    if (Method toCYON = class_getInstanceMethod(_class, sel))
+        string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
+    else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
+        if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
+            string = [value cy$toCYON];
+        else goto fail;
+    } else fail: {
+        if (value == NSZombie_)
+            string = @"_NSZombie_";
+        else if (_class == NSZombie_)
+            string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
+        // XXX: frowny /in/ the pants
+        else if (value == NSMessageBuilder_ || value == Object_)
+            string = nil;
+        else
+            string = [NSString stringWithFormat:@"%@", value];
+    }
+
+    // XXX: frowny pants
+    if (string == nil)
+        string = @"undefined";
+    return [string retain];
+}
+
+NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
     CYTry {
         CYPoolTry {
-            id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
-            return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
+            return CYCopyNSCYON(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
         } CYPoolCatch(NULL)
     } CYCatch
 }
 
-const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
-    if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
+NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
+    return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
+}
+
+const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
+    if (NSString *json = CYCopyNSCYON(context, value, exception)) {
         const char *string(CYPoolCString(pool, json));
         [json release];
         return string;
     } else return NULL;
 }
 
-static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
-    CYPool pool;
+// XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
+struct CYInternal :
+    CYData
+{
+    JSObjectRef object_;
 
-    CYTry {
-        NSString *self(CYCastNSObject(pool, context, object));
-        NSString *name(CYCastNSString(pool, property));
+    CYInternal() :
+        object_(NULL)
+    {
+    }
 
-        CYPoolTry {
-            if (NSObject *data = [self cy$getProperty:name])
-                return CYCastJSValue(context, data);
-        } CYPoolCatch(NULL)
+    ~CYInternal() {
+        // XXX: delete object_? ;(
+    }
 
-        if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
-            PropertyAttributes attributes(property);
-            SEL sel(sel_registerName(attributes.Getter()));
-            return CYSendMessage(pool, context, self, sel, 0, NULL, exception);
+    static CYInternal *Get(id self) {
+        CYInternal *internal(NULL);
+        if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
+            // XXX: do something epic? ;P
         }
 
-        return NULL;
-    } CYCatch
-}
-
-static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
-    CYPool pool;
-
-    CYTry {
-        NSString *self(CYCastNSObject(pool, context, object));
-        NSString *name(CYCastNSString(pool, property));
-        NSString *data(CYCastNSObject(pool, context, value));
-
-        CYPoolTry {
-            if ([self cy$setProperty:name to:data])
-                return true;
-        } CYPoolCatch(NULL)
+        return internal;
+    }
 
-        if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
-            PropertyAttributes attributes(property);
-            if (const char *setter = attributes.Setter()) {
-                SEL sel(sel_registerName(setter));
-                JSValueRef arguments[1] = {value};
-                CYSendMessage(pool, context, self, sel, 1, arguments, exception);
-                return true;
+    static CYInternal *Set(id self) {
+        CYInternal *internal(NULL);
+        if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
+            if (internal == NULL) {
+                internal = new CYInternal();
+                object_setIvar(self, ivar, reinterpret_cast<id>(internal));
             }
+        } else {
+            // XXX: do something epic? ;P
         }
 
-        return false;
-    } CYCatch
-}
+        return internal;
+    }
 
-static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
-    CYTry {
-        CYPoolTry {
-            NSString *self(CYCastNSObject(NULL, context, object));
-            NSString *name(CYCastNSString(NULL, property));
-            return [self cy$deleteProperty:name];
-        } CYPoolCatch(NULL)
-    } CYCatch
-}
+    JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
+        if (object_ == NULL)
+            return NULL;
+        return CYGetProperty(context, object_, name);
+    }
 
-static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
-    CYTry {
-        Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
-        return CYMakeInstance(context, [data->GetValue() alloc], true);
-    } CYCatch
-}
+    void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
+        if (object_ == NULL)
+            object_ = JSObjectMake(context, NULL, NULL);
+        CYSetProperty(context, object_, name, value);
+    }
+};
 
 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
     Selector_privateData *data(new Selector_privateData(sel));
     return JSObjectMake(context, Selector_, data);
 }
 
-JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
-    Pointer_privateData *data(new Pointer_privateData(pointer));
+JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
+    Pointer *data(new Pointer(pointer, type, owner));
     return JSObjectMake(context, Pointer_, data);
 }
 
@@ -1299,31 +1477,24 @@ JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *
     return JSObjectMake(context, Functor_, data);
 }
 
-const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
+const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
     if (pool == NULL) {
         const char *string([CYCastNSString(NULL, value) UTF8String]);
-        if (length != NULL)
-            *length = strlen(string);
         return string;
     } else {
         size_t size(JSStringGetMaximumUTF8CStringSize(value));
         char *string(new(pool) char[size]);
         JSStringGetUTF8CString(value, string, size);
-        // XXX: this is ironic
-        if (length != NULL)
-            *length = strlen(string);
         return string;
     }
 }
 
-const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
-    if (!JSValueIsNull(context, value))
-        return CYPoolCString(pool, CYJSString(context, value), length);
-    else {
-        if (length != NULL)
-            *length = 0;
-        return NULL;
-    }
+const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
+    return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
+}
+
+bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
+    return CYGetIndex(CYPoolCString(pool, value), index);
 }
 
 // XXX: this macro is unhygenic
@@ -1349,7 +1520,7 @@ void *CYCastPointer_(JSContextRef context, JSValueRef value) {
             return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
         case kJSTypeObject:
             if (JSValueIsObjectOfClass(context, value, Pointer_)) {
-                Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
+                Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
                 return data->value_;
             }*/
         default:
@@ -1451,7 +1622,7 @@ void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type
     }
 }
 
-JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
+JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
     JSValueRef value;
 
     switch (type->primitive) {
@@ -1477,9 +1648,13 @@ JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void
         CYFromFFI_(float, float)
         CYFromFFI_(double, double)
 
-        case sig::object_P:
-            value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
-        break;
+        case sig::object_P: {
+            if (id object = *reinterpret_cast<id *>(data)) {
+                value = CYCastJSValue(context, object);
+                if (initialize)
+                    [object release];
+            } else goto null;
+        } break;
 
         case sig::typename_P:
             value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
@@ -1493,7 +1668,7 @@ JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void
 
         case sig::pointer_P:
             if (void *pointer = *reinterpret_cast<void **>(data))
-                value = CYMakePointer(context, pointer);
+                value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
             else goto null;
         break;
 
@@ -1523,61 +1698,328 @@ JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void
     return value;
 }
 
-bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
-    Type_privateData *typical(internal->type_);
+static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    CYPool pool;
 
-    size_t length;
-    const char *name(CYPoolCString(pool, property, &length));
-    double number(CYCastDouble(name, length));
+    CYTry {
+        id self(CYCastNSObject(pool, context, object));
+        NSString *name(CYCastNSString(pool, property));
 
-    size_t count(typical->type_.data.signature.count);
+        if (CYInternal *internal = CYInternal::Get(self))
+            if (JSValueRef value = internal->GetProperty(context, property))
+                return value;
 
-    if (std::isnan(number)) {
-        if (property == NULL)
-            return false;
+        CYPoolTry {
+            if (NSObject *data = [self cy$getProperty:name])
+                return CYCastJSValue(context, data);
+        } CYPoolCatch(NULL)
 
-        sig::Element *elements(typical->type_.data.signature.elements);
+        const char *string(CYPoolCString(pool, name));
+        Class _class(object_getClass(self));
 
-        for (size_t local(0); local != count; ++local) {
-            sig::Element *element(&elements[local]);
-            if (element->name != NULL && strcmp(name, element->name) == 0) {
-                index = local;
-                goto base;
-            }
+        if (objc_property_t property = class_getProperty(_class, string)) {
+            PropertyAttributes attributes(property);
+            SEL sel(sel_registerName(attributes.Getter()));
+            return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
         }
 
-        return false;
-    } else {
-        index = static_cast<ssize_t>(number);
-        if (index != number || index < 0 || static_cast<size_t>(index) >= count)
-            return false;
-    }
+        if (SEL sel = sel_getUid(string))
+            // XXX: possibly use a more "awesome" check?
+            if (class_getInstanceMethod(_class, sel) != NULL)
+                return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
 
-  base:
-    base = reinterpret_cast<uint8_t *>(internal->value_);
-    for (ssize_t local(0); local != index; ++local)
-        base += typical->ffi_.elements[local]->size;
+        return NULL;
+    } CYCatch
+}
 
-    return true;
+static JSValueRef Instance_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
+    return Internal::Make(context, internal->GetValue(), object);
 }
 
-static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
     CYPool pool;
-    Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
-    Type_privateData *typical(internal->type_);
-
-    ssize_t index;
-    uint8_t *base;
-
-    if (!Index_(pool, internal, property, index, base))
-        return NULL;
 
     CYTry {
-        return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
-    } CYCatch
-}
+        id self(CYCastNSObject(pool, context, object));
+        NSString *name(CYCastNSString(pool, property));
+        NSString *data(CYCastNSObject(pool, context, value));
 
-static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
+        CYPoolTry {
+            if ([self cy$setProperty:name to:data])
+                return true;
+        } CYPoolCatch(NULL)
+
+        const char *string(CYPoolCString(pool, name));
+        Class _class(object_getClass(self));
+
+        if (objc_property_t property = class_getProperty(_class, string)) {
+            PropertyAttributes attributes(property);
+            if (const char *setter = attributes.Setter()) {
+                SEL sel(sel_registerName(setter));
+                JSValueRef arguments[1] = {value};
+                CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
+                return true;
+            }
+        }
+
+        size_t length(strlen(string));
+
+        char set[length + 5];
+
+        set[0] = 's';
+        set[1] = 'e';
+        set[2] = 't';
+
+        if (string[0] != '\0') {
+            set[3] = toupper(string[0]);
+            memcpy(set + 4, string + 1, length - 1);
+        }
+
+        set[length + 3] = ':';
+        set[length + 4] = '\0';
+
+        if (SEL sel = sel_getUid(set))
+            // XXX: possibly use a more "awesome" check?
+            if (class_getInstanceMethod(_class, sel) != NULL) {
+                JSValueRef arguments[1] = {value};
+                CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
+            }
+
+        if (CYInternal *internal = CYInternal::Set(self)) {
+            internal->SetProperty(context, property, value);
+            return true;
+        }
+
+        return false;
+    } CYCatch
+}
+
+static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    CYTry {
+        CYPoolTry {
+            id self(CYCastNSObject(NULL, context, object));
+            NSString *name(CYCastNSString(NULL, property));
+            return [self cy$deleteProperty:name];
+        } CYPoolCatch(NULL)
+    } CYCatch
+}
+
+static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
+    CYPool pool;
+    NSString *self(CYCastNSObject(pool, context, object));
+    Class _class(object_getClass(self));
+
+    {
+        unsigned int size;
+        objc_property_t *data(class_copyPropertyList(_class, &size));
+        for (size_t i(0); i != size; ++i)
+            JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
+        free(data);
+    }
+}
+
+static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
+        JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
+        return value;
+    } CYCatch
+}
+
+static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
+    CYPool pool;
+
+    CYTry {
+        id self(internal->GetValue());
+        const char *name(CYPoolCString(pool, property));
+
+        if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
+            Type_privateData type(pool, ivar_getTypeEncoding(ivar));
+            return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
+        }
+
+        return NULL;
+    } CYCatch
+}
+
+static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
+    Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
+    CYPool pool;
+
+    CYTry {
+        id self(internal->GetValue());
+        const char *name(CYPoolCString(pool, property));
+
+        if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
+            Type_privateData type(pool, ivar_getTypeEncoding(ivar));
+            CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
+            return true;
+        }
+
+        return false;
+    } CYCatch
+}
+
+static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
+    Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
+    CYPool pool;
+
+    id self(internal->GetValue());
+    Class _class(object_getClass(self));
+
+    for (Class super(_class); super != NULL; super = class_getSuperclass(super)) {
+        unsigned int size;
+        Ivar *data(class_copyIvarList(super, &size));
+        for (size_t i(0); i != size; ++i)
+            JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
+        free(data);
+    }
+}
+
+static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
+    return internal->owner_;
+}
+
+bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
+    Type_privateData *typical(internal->type_);
+    sig::Type *type(typical->type_);
+    if (type == NULL)
+        return false;
+
+    const char *name(CYPoolCString(pool, property));
+    size_t length(strlen(name));
+    double number(CYCastDouble(name, length));
+
+    size_t count(type->data.signature.count);
+
+    if (std::isnan(number)) {
+        if (property == NULL)
+            return false;
+
+        sig::Element *elements(type->data.signature.elements);
+
+        for (size_t local(0); local != count; ++local) {
+            sig::Element *element(&elements[local]);
+            if (element->name != NULL && strcmp(name, element->name) == 0) {
+                index = local;
+                goto base;
+            }
+        }
+
+        return false;
+    } else {
+        index = static_cast<ssize_t>(number);
+        if (index != number || index < 0 || static_cast<size_t>(index) >= count)
+            return false;
+    }
+
+  base:
+    ffi_type **elements(typical->GetFFI()->elements);
+
+    base = reinterpret_cast<uint8_t *>(internal->value_);
+    for (ssize_t local(0); local != index; ++local)
+        base += elements[local]->size;
+
+    return true;
+}
+
+static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
+    Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
+    Type_privateData *typical(internal->type_);
+
+    ffi_type *ffi(typical->GetFFI());
+
+    uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
+    base += ffi->size * index;
+
+    JSObjectRef owner(internal->owner_ ?: object);
+
+    CYTry {
+        return CYFromFFI(context, typical->type_, ffi, base, false, owner);
+    } CYCatch
+}
+
+static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    CYPool pool;
+    Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
+    Type_privateData *typical(internal->type_);
+
+    if (typical->type_ == NULL)
+        return NULL;
+
+    ssize_t index;
+    if (!CYGetIndex(pool, property, index))
+        return NULL;
+
+    return Pointer_getIndex(context, object, index, exception);
+}
+
+static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    return Pointer_getIndex(context, object, 0, exception);
+}
+
+static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
+    Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
+    Type_privateData *typical(internal->type_);
+
+    ffi_type *ffi(typical->GetFFI());
+
+    uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
+    base += ffi->size * index;
+
+    CYTry {
+        CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
+        return true;
+    } CYCatch
+}
+
+static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
+    CYPool pool;
+    Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
+    Type_privateData *typical(internal->type_);
+
+    if (typical->type_ == NULL)
+        return NULL;
+
+    ssize_t index;
+    if (!CYGetIndex(pool, property, index))
+        return NULL;
+
+    return Pointer_setIndex(context, object, 0, value, exception);
+}
+
+static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
+    return Pointer_setIndex(context, object, 0, value, exception);
+}
+
+static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
+    Type_privateData *typical(internal->type_);
+    return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
+}
+
+static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    CYPool pool;
+    Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
+    Type_privateData *typical(internal->type_);
+
+    ssize_t index;
+    uint8_t *base;
+
+    if (!Index_(pool, internal, property, index, base))
+        return NULL;
+
+    JSObjectRef owner(internal->owner_ ?: object);
+
+    CYTry {
+        return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
+    } CYCatch
+}
+
+static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
     CYPool pool;
     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
     Type_privateData *typical(internal->type_);
@@ -1589,7 +2031,7 @@ static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStrin
         return false;
 
     CYTry {
-        CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
+        CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
         return true;
     } CYCatch
 }
@@ -1597,9 +2039,13 @@ static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStrin
 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
     Type_privateData *typical(internal->type_);
+    sig::Type *type(typical->type_);
+
+    if (type == NULL)
+        return;
 
-    size_t count(typical->type_.data.signature.count);
-    sig::Element *elements(typical->type_.data.signature.elements);
+    size_t count(type->data.signature.count);
+    sig::Element *elements(type->data.signature.elements);
 
     char number[32];
 
@@ -1616,7 +2062,7 @@ static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JS
     }
 }
 
-JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
+JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
     CYTry {
         if (setups + count != signature->count - 1)
             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
@@ -1636,7 +2082,7 @@ JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups,
         uint8_t value[cif->rtype->size];
         ffi_call(cif, function, value, values);
 
-        return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
+        return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
     } CYCatch
 }
 
@@ -1659,12 +2105,11 @@ JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char
     // XXX: in case of exceptions this will leak
     ffoData *data(new ffoData(type));
 
-    ffi_closure *closure;
-    _syscall(closure = (ffi_closure *) mmap(
+    ffi_closure *closure((ffi_closure *) _syscall(mmap(
         NULL, sizeof(ffi_closure),
         PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
         -1, 0
-    ));
+    )));
 
     ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
     _assert(status == FFI_OK);
@@ -1679,6 +2124,118 @@ JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char
     return JSObjectMake(context, Functor_, data);
 }
 
+static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    CYTry {
+        CYPool pool;
+        NSString *name(CYCastNSString(pool, property));
+        if (Class _class = NSClassFromString(name))
+            return CYMakeInstance(context, _class, true);
+        return NULL;
+    } CYCatch
+}
+
+static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
+    size_t size(objc_getClassList(NULL, 0));
+    Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
+
+  get:
+    size_t writ(objc_getClassList(data, size));
+    if (size < writ) {
+        size = writ;
+        if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
+            data = copy;
+            goto get;
+        } else goto done;
+    }
+
+    for (size_t i(0); i != writ; ++i)
+        JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
+
+  done:
+    free(data);
+}
+
+static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
+
+    CYTry {
+        CYPool pool;
+        const char *name(CYPoolCString(pool, property));
+        unsigned int size;
+        const char **data(objc_copyClassNamesForImage(internal, &size));
+        JSValueRef value;
+        for (size_t i(0); i != size; ++i)
+            if (strcmp(name, data[i]) == 0) {
+                if (Class _class = objc_getClass(name)) {
+                    value = CYMakeInstance(context, _class, true);
+                    goto free;
+                } else
+                    break;
+            }
+        value = NULL;
+      free:
+        free(data);
+        return value;
+    } CYCatch
+}
+
+static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
+    const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
+    unsigned int size;
+    const char **data(objc_copyClassNamesForImage(internal, &size));
+    for (size_t i(0); i != size; ++i)
+        JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
+    free(data);
+}
+
+static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    CYTry {
+        CYPool pool;
+        const char *name(CYPoolCString(pool, property));
+        unsigned int size;
+        const char **data(objc_copyImageNames(&size));
+        for (size_t i(0); i != size; ++i)
+            if (strcmp(name, data[i]) == 0) {
+                name = data[i];
+                goto free;
+            }
+        name = NULL;
+      free:
+        free(data);
+        if (name == NULL)
+            return NULL;
+        JSObjectRef value(JSObjectMake(context, NULL, NULL));
+        CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
+        return value;
+    } CYCatch
+}
+
+static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
+    unsigned int size;
+    const char **data(objc_copyImageNames(&size));
+    for (size_t i(0); i != size; ++i)
+        JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
+    free(data);
+}
+
+static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    CYTry {
+        CYPool pool;
+        NSString *name(CYCastNSString(pool, property));
+        if (Protocol *protocol = NSProtocolFromString(name))
+            return CYMakeInstance(context, protocol, true);
+        return NULL;
+    } CYCatch
+}
+
+static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
+    unsigned int size;
+    Protocol **data(objc_copyProtocolList(&size));
+    for (size_t i(0); i != size; ++i)
+        JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
+    free(data);
+}
+
 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
     CYTry {
         CYPool pool;
@@ -1723,38 +2280,21 @@ static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjec
     } CYCatch
 }
 
-static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
-    CYTry {
-        CYPool pool;
-
-        int argc(CYCastDouble(context, arguments[0]));
-        char **argv(CYCastPointer<char **>(context, arguments[1]));
-        NSString *principal(CYCastNSObject(pool, context, arguments[2]));
-        NSString *delegate(CYCastNSObject(pool, context, arguments[3]));
-
-        argc = *_NSGetArgc() - 1;
-        argv = *_NSGetArgv() + 1;
-        for (int i(0); i != argc; ++i)
-            NSLog(@"argv[%i]=%s", i, argv[i]);
-
-        _pooled
-        return CYCastJSValue(context, UIApplicationMain(argc, argv, principal, delegate));
-    } CYCatch
-}
-
-JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
     const char *type;
 
     Class _class(object_getClass(self));
     if (Method method = class_getInstanceMethod(_class, _cmd))
         type = method_getTypeEncoding(method);
     else {
-        CYPoolTry {
-            NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
-            if (method == nil)
-                @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
-            type = CYPoolCString(pool, [method _typeString]);
-        } CYPoolCatch(NULL)
+        CYTry {
+            CYPoolTry {
+                NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
+                if (method == nil)
+                    @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
+                type = CYPoolCString(pool, [method _typeString]);
+            } CYPoolCatch(NULL)
+        } CYCatch
     }
 
     void *setup[2];
@@ -1768,12 +2308,14 @@ JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _c
     sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
 
     void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
-    return CYCallFunction(pool, context, 2, setup, count, arguments, exception, &signature, &cif, function);
+    return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
 }
 
 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYPool pool;
 
+    bool uninitialized;
+
     id self;
     SEL _cmd;
 
@@ -1781,14 +2323,53 @@ static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObje
         if (count < 2)
             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
 
-        self = CYCastNSObject(pool, context, arguments[0]);
+        if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
+            Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
+            self = data->GetValue();
+            uninitialized = data->IsUninitialized();
+            if (uninitialized)
+                data->value_ = nil;
+        } else {
+            self = CYCastNSObject(pool, context, arguments[0]);
+            uninitialized = false;
+        }
+
         if (self == nil)
             return CYJSNull(context);
 
         _cmd = CYCastSEL(context, arguments[1]);
     } CYCatch
 
-    return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, exception);
+    return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
+}
+
+MSHook(void, CYDealloc, id self, SEL sel) {
+    CYInternal *internal;
+    object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
+    if (internal != NULL)
+        delete internal;
+    _CYDealloc(self, sel);
+}
+
+MSHook(void, objc_registerClassPair, Class _class) {
+    Class super(class_getSuperclass(_class));
+    if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
+        class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
+        MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
+    }
+
+    _objc_registerClassPair(_class);
+}
+
+static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        if (count != 1)
+            @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
+        CYPool pool;
+        Class _class(CYCastNSObject(pool, context, arguments[0]));
+        $objc_registerClassPair(_class);
+        return CYJSUndefined(context);
+    } CYCatch
 }
 
 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
@@ -1802,7 +2383,7 @@ static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef obje
 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYPool pool;
     Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
-    return CYCallFunction(pool, context, 0, NULL, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
+    return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
 }
 
 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
@@ -1814,6 +2395,64 @@ JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count,
     } CYCatch
 }
 
+JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        if (count != 2)
+            @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
+
+        void *value(CYCastPointer<void *>(context, arguments[0]));
+        const char *type(CYCastCString(context, arguments[1]));
+
+        CYPool pool;
+
+        sig::Signature signature;
+        sig::Parse(pool, &signature, type, &Structor_);
+
+        return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
+    } CYCatch
+}
+
+JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
+    Type_privateData *internal(new Type_privateData(NULL, type));
+    return JSObjectMake(context, Type_, internal);
+}
+
+JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        if (count != 1)
+            @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
+        const char *type(CYCastCString(context, arguments[0]));
+        return CYMakeType(context, object, type);
+    } CYCatch
+}
+
+static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        if (count != 1)
+            @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
+        Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
+        sig::Type *type(internal->type_);
+        ffi_type *ffi(internal->GetFFI());
+        // XXX: alignment?
+        uint8_t value[ffi->size];
+        CYPool pool;
+        CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
+        return CYFromFFI(context, type, ffi, value);
+    } CYCatch
+}
+
+static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        if (count > 1)
+            @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
+        Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
+        size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
+        // XXX: alignment?
+        void *value(malloc(internal->GetFFI()->size * size));
+        return CYMakePointer(context, value, internal->type_, internal->ffi_, NULL);
+    } CYCatch
+}
+
 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
         if (count != 2)
@@ -1832,57 +2471,57 @@ JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count,
     } CYCatch
 }
 
-JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
-    Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
-    return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
+JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
+    return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
 }
 
 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
     return Function_;
 }
 
-static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
-        Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
-        return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
+        CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
+        return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
     } CYCatch
 }
 
-static JSValueRef Pointer_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
-    return Pointer_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
+static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
 }
 
-static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
-        Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
+        CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
         char string[32];
-        sprintf(string, "%p", data->value_);
+        sprintf(string, "%p", internal->value_);
         return CYCastJSValue(context, string);
     } CYCatch
 }
 
 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
-        Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
+        Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
         CYPoolTry {
-            return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
+            return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toCYON]));
         } CYPoolCatch(NULL)
     } CYCatch
 }
 
 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
-        Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
+        Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
         CYPoolTry {
             NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
-            return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
+            return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
         } CYPoolCatch(NULL)
     } CYCatch
 }
 
 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
-        Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
+        Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
         CYPoolTry {
             return CYCastJSValue(context, CYJSString([data->GetValue() description]));
         } CYPoolCatch(NULL)
@@ -1902,8 +2541,8 @@ static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectR
 
 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
-        Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
-        const char *name(sel_getName(data->GetValue()));
+        Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
+        const char *name(sel_getName(internal->GetValue()));
         CYPoolTry {
             return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
         } CYPoolCatch(NULL)
@@ -1912,14 +2551,13 @@ static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectR
 
 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
-        if (count != 2)
+        if (count != 1)
             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
         CYPool pool;
-        Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
+        Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
         Class _class(CYCastNSObject(pool, context, arguments[0]));
-        bool instance(CYCastBool(context, arguments[1]));
-        SEL sel(data->GetValue());
-        if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
+        SEL sel(internal->GetValue());
+        if (Method method = class_getInstanceMethod(_class, sel))
             return CYCastJSValue(context, method_getTypeEncoding(method));
         else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
             return CYCastJSValue(context, CYJSString(type));
@@ -1928,15 +2566,58 @@ static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef
     } CYCatch
 }
 
+static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
+        CYPool pool;
+        const char *type(sig::Unparse(pool, internal->type_));
+        CYPoolTry {
+            return CYCastJSValue(context, CYJSString(type));
+        } CYPoolCatch(NULL)
+    } CYCatch
+}
+
+static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
+        CYPool pool;
+        const char *type(sig::Unparse(pool, internal->type_));
+        CYPoolTry {
+            return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
+        } CYPoolCatch(NULL)
+    } CYCatch
+}
+
+static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
+}
+
+static JSStaticValue CYValue_staticValues[2] = {
+    {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
+    {NULL, NULL, NULL, 0}
+};
+
 static JSStaticValue Pointer_staticValues[2] = {
-    {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
+    {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontDelete},
     {NULL, NULL, NULL, 0}
 };
 
 static JSStaticFunction Pointer_staticFunctions[4] = {
-    {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
-    {"toJSON", &Pointer_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
-    {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {NULL, NULL, 0}
+};
+
+static JSStaticFunction Struct_staticFunctions[2] = {
+    {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {NULL, NULL, 0}
+};
+
+static JSStaticFunction Functor_staticFunctions[4] = {
+    {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
     {NULL, NULL, 0}
 };
 
@@ -1945,6 +2626,12 @@ static JSStaticFunction Pointer_staticFunctions[4] = {
     {NULL, NULL, NULL, 0}
 };*/
 
+static JSStaticValue Instance_staticValues[3] = {
+    {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
+    {"$cyi", &Instance_getProperty_$cyi, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
+    {NULL, NULL, NULL, 0}
+};
+
 static JSStaticFunction Instance_staticFunctions[4] = {
     {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
     {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
@@ -1952,6 +2639,11 @@ static JSStaticFunction Instance_staticFunctions[4] = {
     {NULL, NULL, 0}
 };
 
+static JSStaticFunction Internal_staticFunctions[2] = {
+    {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {NULL, NULL, 0}
+};
+
 static JSStaticFunction Selector_staticFunctions[5] = {
     {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
     {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
@@ -1960,6 +2652,13 @@ static JSStaticFunction Selector_staticFunctions[5] = {
     {NULL, NULL, 0}
 };
 
+static JSStaticFunction Type_staticFunctions[4] = {
+    {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {NULL, NULL, 0}
+};
+
 CYDriver::CYDriver(const std::string &filename) :
     state_(CYClear),
     data_(NULL),
@@ -1996,94 +2695,343 @@ JSObjectRef CYGetGlobalObject(JSContextRef context) {
     return JSContextGetGlobalObject(context);
 }
 
+const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
+    JSContextRef context(CYGetJSContext());
+    JSValueRef exception(NULL), result;
+
+    try {
+        result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
+    } catch (const char *error) {
+        return error;
+    }
+
+    if (exception != NULL) { error:
+        result = exception;
+        exception = NULL;
+    }
+
+    if (JSValueIsUndefined(context, result))
+        return NULL;
+
+    const char *json(CYPoolCCYON(pool, context, result, &exception));
+    if (exception != NULL)
+        goto error;
+
+    CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
+    return json;
+}
+
+bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
+    while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
+        data += writ;
+        size -= writ;
+    } else
+        return false;
+    return true;
+}
+
+bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
+    while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
+        data += writ;
+        size -= writ;
+    } else
+        return false;
+    return true;
+}
+
+static int Socket_;
+apr_pool_t *Pool_;
+
+struct CYExecute_ {
+    apr_pool_t *pool_;
+    const char * volatile data_;
+};
+
+// XXX: this is "tre lame"
+@interface CYClient_ : NSObject {
+}
+
+- (void) execute:(NSValue *)value;
+
+@end
+
+@implementation CYClient_
+
+- (void) execute:(NSValue *)value {
+    CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
+    const char *data(execute->data_);
+    execute->data_ = NULL;
+    execute->data_ = CYExecute(execute->pool_, data);
+}
+
+@end
+
+struct CYClient :
+    CYData
+{
+    int socket_;
+    apr_thread_t *thread_;
+
+    CYClient(int socket) :
+        socket_(socket)
+    {
+    }
+
+    ~CYClient() {
+        _syscall(close(socket_));
+    }
+
+    void Handle() { _pooled
+        CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
+
+        for (;;) {
+            size_t size;
+            if (!CYRecvAll(socket_, &size, sizeof(size)))
+                return;
+
+            CYPool pool;
+            char *data(new(pool) char[size + 1]);
+            if (!CYRecvAll(socket_, data, size))
+                return;
+            data[size] = '\0';
+
+            CYDriver driver("");
+            cy::parser parser(driver);
+
+            driver.data_ = data;
+            driver.size_ = size;
+
+            const char *json;
+            if (parser.parse() != 0 || !driver.errors_.empty()) {
+                json = NULL;
+                size = _not(size_t);
+            } else {
+                std::ostringstream str;
+                driver.source_->Show(str);
+                std::string code(str.str());
+                CYExecute_ execute = {pool, code.c_str()};
+                [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
+                json = execute.data_;
+                size = json == NULL ? _not(size_t) : strlen(json);
+            }
+
+            if (!CYSendAll(socket_, &size, sizeof(size)))
+                return;
+            if (json != NULL)
+                if (!CYSendAll(socket_, json, size))
+                    return;
+        }
+    }
+};
+
+static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
+    CYClient *client(reinterpret_cast<CYClient *>(data));
+    client->Handle();
+    delete client;
+    return NULL;
+}
+
+static void * APR_THREAD_FUNC Cyrver(apr_thread_t *thread, void *data) {
+    for (;;) {
+        int socket(_syscall(accept(Socket_, NULL, NULL)));
+        CYClient *client(new CYClient(socket));
+        apr_threadattr_t *attr;
+        _aprcall(apr_threadattr_create(&attr, Pool_));
+        _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
+    }
+
+    return NULL;
+}
+
+void Unlink() {
+    pid_t pid(getpid());
+    char path[104];
+    sprintf(path, "/tmp/.s.cy.%u", pid);
+    unlink(path);
+}
+
 MSInitialize { _pooled
-    apr_initialize();
+    _aprcall(apr_initialize());
+    _aprcall(apr_pool_create(&Pool_, NULL));
 
     Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
 
     NSCFBoolean_ = objc_getClass("NSCFBoolean");
+    NSCFType_ = objc_getClass("NSCFType");
+    NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
+    NSZombie_ = objc_getClass("_NSZombie_");
+    Object_ = objc_getClass("Object");
 
-    JSClassDefinition definition;
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Pointer";
-    definition.staticValues = Pointer_staticValues;
-    definition.staticFunctions = Pointer_staticFunctions;
-    definition.finalize = &CYData::Finalize;
-    Pointer_ = JSClassCreate(&definition);
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Functor";
-    definition.staticValues = Pointer_staticValues;
-    definition.staticFunctions = Pointer_staticFunctions;
-    definition.callAsFunction = &Functor_callAsFunction;
-    definition.finalize = &CYData::Finalize;
-    Functor_ = JSClassCreate(&definition);
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Struct";
-    definition.getProperty = &Struct_getProperty;
-    definition.setProperty = &Struct_setProperty;
-    definition.getPropertyNames = &Struct_getPropertyNames;
-    definition.finalize = &CYData::Finalize;
-    Struct_ = JSClassCreate(&definition);
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Selector";
-    definition.staticValues = Pointer_staticValues;
-    //definition.staticValues = Selector_staticValues;
-    definition.staticFunctions = Selector_staticFunctions;
-    definition.callAsFunction = &Selector_callAsFunction;
-    definition.finalize = &CYData::Finalize;
-    Selector_ = JSClassCreate(&definition);
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Instance";
-    definition.staticValues = Pointer_staticValues;
-    definition.staticFunctions = Instance_staticFunctions;
-    definition.getProperty = &Instance_getProperty;
-    definition.setProperty = &Instance_setProperty;
-    definition.deleteProperty = &Instance_deleteProperty;
-    definition.callAsConstructor = &Instance_callAsConstructor;
-    definition.finalize = &CYData::Finalize;
-    Instance_ = JSClassCreate(&definition);
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Runtime";
-    definition.getProperty = &Runtime_getProperty;
-    Runtime_ = JSClassCreate(&definition);
-
-    definition = kJSClassDefinitionEmpty;
-    //definition.getProperty = &Global_getProperty;
-    JSClassRef Global(JSClassCreate(&definition));
-
-    JSGlobalContextRef context(JSGlobalContextCreate(Global));
-    Context_ = context;
-
-    JSObjectRef global(CYGetGlobalObject(context));
-
-    JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
-    CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
-
-    CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
-    CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
-
-    CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
-    CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
-
-    System_ = JSObjectMake(context, NULL, NULL);
-    CYSetProperty(context, global, CYJSString("system"), System_);
-    CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
-    //CYSetProperty(context, System_, CYJSString("global"), global);
-
-    CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
-
-    length_ = JSStringCreateWithUTF8CString("length");
-    message_ = JSStringCreateWithUTF8CString("message");
-    name_ = JSStringCreateWithUTF8CString("name");
-    toCYON_ = JSStringCreateWithUTF8CString("toCYON");
-    toJSON_ = JSStringCreateWithUTF8CString("toJSON");
-
-    Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
-    Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
+    Socket_ = _syscall(socket(PF_UNIX, SOCK_STREAM, 0));
+
+    struct sockaddr_un address;
+    memset(&address, 0, sizeof(address));
+    address.sun_family = AF_UNIX;
+
+    pid_t pid(getpid());
+    sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
+
+    try {
+        _syscall(bind(Socket_, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
+        atexit(&Unlink);
+        _syscall(listen(Socket_, 0));
+
+        apr_threadattr_t *attr;
+        _aprcall(apr_threadattr_create(&attr, Pool_));
+
+        apr_thread_t *thread;
+        _aprcall(apr_thread_create(&thread, attr, &Cyrver, NULL, Pool_));
+    } catch (...) {
+        NSLog(@"failed to setup Cyrver");
+    }
+}
+
+JSGlobalContextRef CYGetJSContext() {
+    if (Context_ == NULL) {
+        JSClassDefinition definition;
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Functor";
+        definition.staticFunctions = Functor_staticFunctions;
+        definition.callAsFunction = &Functor_callAsFunction;
+        definition.finalize = &CYData::Finalize;
+        Functor_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Instance";
+        definition.staticValues = Instance_staticValues;
+        definition.staticFunctions = Instance_staticFunctions;
+        definition.getProperty = &Instance_getProperty;
+        definition.setProperty = &Instance_setProperty;
+        definition.deleteProperty = &Instance_deleteProperty;
+        definition.getPropertyNames = &Instance_getPropertyNames;
+        definition.callAsConstructor = &Instance_callAsConstructor;
+        definition.finalize = &CYData::Finalize;
+        Instance_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Internal";
+        definition.staticFunctions = Internal_staticFunctions;
+        definition.getProperty = &Internal_getProperty;
+        definition.setProperty = &Internal_setProperty;
+        definition.getPropertyNames = &Internal_getPropertyNames;
+        definition.finalize = &CYData::Finalize;
+        Internal_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Pointer";
+        definition.staticValues = Pointer_staticValues;
+        definition.staticFunctions = Pointer_staticFunctions;
+        definition.getProperty = &Pointer_getProperty;
+        definition.setProperty = &Pointer_setProperty;
+        definition.finalize = &CYData::Finalize;
+        Pointer_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Selector";
+        definition.staticValues = CYValue_staticValues;
+        //definition.staticValues = Selector_staticValues;
+        definition.staticFunctions = Selector_staticFunctions;
+        definition.callAsFunction = &Selector_callAsFunction;
+        definition.finalize = &CYData::Finalize;
+        Selector_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Struct";
+        definition.staticFunctions = Struct_staticFunctions;
+        definition.getProperty = &Struct_getProperty;
+        definition.setProperty = &Struct_setProperty;
+        definition.getPropertyNames = &Struct_getPropertyNames;
+        definition.finalize = &CYData::Finalize;
+        Struct_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Type";
+        definition.staticFunctions = Type_staticFunctions;
+        //definition.getProperty = &Type_getProperty;
+        definition.callAsFunction = &Type_callAsFunction;
+        definition.callAsConstructor = &Type_callAsConstructor;
+        definition.finalize = &CYData::Finalize;
+        Type_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Runtime";
+        definition.getProperty = &Runtime_getProperty;
+        Runtime_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "ObjectiveC::Classes";
+        definition.getProperty = &ObjectiveC_Classes_getProperty;
+        definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
+        ObjectiveC_Classes_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "ObjectiveC::Images";
+        definition.getProperty = &ObjectiveC_Images_getProperty;
+        definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
+        ObjectiveC_Images_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "ObjectiveC::Image::Classes";
+        definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
+        definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
+        definition.finalize = &CYData::Finalize;
+        ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "ObjectiveC::Protocols";
+        definition.getProperty = &ObjectiveC_Protocols_getProperty;
+        definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
+        ObjectiveC_Protocols_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        //definition.getProperty = &Global_getProperty;
+        JSClassRef Global(JSClassCreate(&definition));
+
+        JSGlobalContextRef context(JSGlobalContextCreate(Global));
+        Context_ = context;
+
+        JSObjectRef global(CYGetGlobalObject(context));
+
+        JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
+        ObjectiveC_ = JSObjectMake(context, NULL, NULL);
+        CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
+
+        CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
+        CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
+        CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
+
+        CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
+        CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, NULL));
+        CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
+        CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
+        CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
+
+        MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
+
+        class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
+
+        CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
+        CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
+
+        System_ = JSObjectMake(context, NULL, NULL);
+        CYSetProperty(context, global, CYJSString("system"), System_);
+        CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
+        //CYSetProperty(context, System_, CYJSString("global"), global);
+
+        CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
+
+        Result_ = JSStringCreateWithUTF8CString("_");
+
+        length_ = JSStringCreateWithUTF8CString("length");
+        message_ = JSStringCreateWithUTF8CString("message");
+        name_ = JSStringCreateWithUTF8CString("name");
+        toCYON_ = JSStringCreateWithUTF8CString("toCYON");
+        toJSON_ = JSStringCreateWithUTF8CString("toJSON");
+
+        Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
+        Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
+    }
+
+    return Context_;
 }