]> git.saurik.com Git - cycript.git/blobdiff - Library.mm
Added Instance constructor instance (for Instance.prototype), implemented Type class...
[cycript.git] / Library.mm
index 9cb0060e14d0b3db5dd55c37fcf7694c375f16bf..c4289e7086a8d937c709cae8f01709384b9ecfc4 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
 
@@ -107,10 +114,13 @@ static JSClassRef Pointer_;
 static JSClassRef Runtime_;
 static JSClassRef Selector_;
 static JSClassRef Struct_;
+static JSClassRef Type_;
 
 static JSObjectRef Array_;
 static JSObjectRef Function_;
 
+static JSStringRef Result_;
+
 static JSStringRef length_;
 static JSStringRef message_;
 static JSStringRef name_;
@@ -127,14 +137,18 @@ struct CYData {
     virtual ~CYData() {
     }
 
-    static 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;
     }
 
+    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_);
     }
@@ -280,29 +294,56 @@ struct CStringMapLess :
     }
 };
 
-struct Type_privateData {
-    apr_pool_t *pool_;
+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_;
 
-    Type_privateData(apr_pool_t *pool, sig::Type *type) :
-        pool_(pool),
+    void Set(sig::Type *type) {
+        type_ = new(pool_) sig::Type;
+        sig::Copy(pool_, *type_, *type);
+    }
+
+    Type_privateData(const char *type) :
         ffi_(NULL)
     {
-        if (type != NULL) {
-            type_ = new(pool) sig::Type;
-            sig::Copy(pool, *type_, *type);
-        }
+        sig::Signature signature;
+        sig::Parse(pool_, &signature, type, &Structor_);
+        type_ = signature.elements[0].type;
     }
 
-    Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) :
-        pool_(pool)
+    Type_privateData(sig::Type *type) :
+        ffi_(NULL)
     {
-        ffi_ = new(pool) ffi_type;
-        sig::Copy(pool, *ffi_, *ffi);
-        type_ = new(pool) sig::Type;
-        sig::Copy(pool, *type_, *type);
+        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() {
@@ -336,7 +377,7 @@ struct Pointer :
     Pointer(void *value, sig::Type *type, JSObjectRef owner) :
         CYValue(value),
         owner_(owner),
-        type_(new(pool_) Type_privateData(pool_, type))
+        type_(new(pool_) Type_privateData(type))
     {
     }
 };
@@ -359,7 +400,7 @@ static TypeMap Types_;
 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
     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)
@@ -374,26 +415,6 @@ 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) {
-    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 Functor_privateData :
     CYValue
 {
@@ -895,10 +916,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 \
@@ -1304,6 +1321,7 @@ const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef
     } else return NULL;
 }
 
+// XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
 struct CYInternal :
     CYData
 {
@@ -1445,31 +1463,20 @@ 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) {
@@ -1683,8 +1690,8 @@ bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property
     if (type == NULL)
         return false;
 
-    size_t length;
-    const char *name(CYPoolCString(pool, property, &length));
+    const char *name(CYPoolCString(pool, property));
+    size_t length(strlen(name));
     double number(CYCastDouble(name, length));
 
     size_t count(type->data.signature.count);
@@ -1871,12 +1878,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);
@@ -1942,12 +1948,14 @@ JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _c
     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];
@@ -2016,8 +2024,10 @@ MSHook(void, objc_registerClassPair, Class _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, object));
+        Class _class(CYCastNSObject(pool, context, arguments[0]));
         $objc_registerClassPair(_class);
         return CYJSUndefined(context);
     } CYCatch
@@ -2063,6 +2073,46 @@ JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count,
     } CYCatch
 }
 
+JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
+    Type_privateData *internal(new Type_privateData(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, false);
+    } 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)));
+        // XXX: alignment?
+        void *value(malloc(internal->GetFFI()->size));
+        return CYMakePointer(context, value, internal->type_, NULL);
+    } CYCatch
+}
+
 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
         if (count != 2)
@@ -2252,97 +2302,292 @@ JSObjectRef CYGetGlobalObject(JSContextRef context) {
     return JSContextGetGlobalObject(context);
 }
 
+const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
+    JSStringRef script(JSStringCreateWithUTF8CString(code));
+
+    JSContextRef context(CYGetJSContext());
+
+    JSValueRef exception(NULL);
+    JSValueRef result(JSEvaluateScript(context, script, NULL, NULL, 0, &exception));
+    JSStringRelease(script);
+
+    if (exception != NULL) { error:
+        result = exception;
+        exception = NULL;
+    }
+
+    if (JSValueIsUndefined(context, result))
+        return NULL;
+
+    const char *json(CYPoolCYONString(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]));
+    NSLog(@"b:%p", execute->data_);
+    NSLog(@"s:%s", execute->data_);
+    execute->data_ = CYExecute(execute->pool_, execute->data_);
+    NSLog(@"a:%p", execute->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");
 
-    JSClassDefinition definition;
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Pointer";
-    definition.staticFunctions = Pointer_staticFunctions;
-    definition.getProperty = &Pointer_getProperty;
-    definition.setProperty = &Pointer_setProperty;
-    definition.finalize = &CYData::Finalize;
-    Pointer_ = JSClassCreate(&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 = "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 = 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 = "Instance";
-    definition.staticValues = CYValue_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("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
-    CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
-    CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
-
-    MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
-
-    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));
-
-    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 = CYValue_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 = "Pointer";
+        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.getProperty = &Struct_getProperty;
+        definition.setProperty = &Struct_setProperty;
+        definition.getPropertyNames = &Struct_getPropertyNames;
+        definition.finalize = &CYData::Finalize;
+        Struct_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Type";
+        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.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("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));
+
+        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_;
 }