X-Git-Url: https://git.saurik.com/cycript.git/blobdiff_plain/367eebb166684de7a659b4e9cd34565b62b7928d..cb02f8aec13cb7ffea9631c401293e80447e6ae7:/Library.mm diff --git a/Library.mm b/Library.mm index 89ed137..bef1661 100644 --- a/Library.mm +++ b/Library.mm @@ -1,4 +1,4 @@ -/* Cycript - Remove Execution Server and Disassembler +/* Cycript - Remote Execution Server and Disassembler * Copyright (C) 2009 Jay Freeman (saurik) */ @@ -37,21 +37,34 @@ */ /* }}} */ -#define _GNU_SOURCE - #include + +#include +#include + #include "cycript.hpp" #include "sig/parse.hpp" #include "sig/ffi_type.hpp" #include "Pooling.hpp" + +#ifdef __OBJC__ #include "Struct.hpp" +#endif +#ifdef __APPLE__ #include #include +#include +#endif +#ifdef __OBJC__ +#ifdef __APPLE__ #include +#endif +#include +#endif #include @@ -59,27 +72,45 @@ #include #include #include - +#include #include #include #include "Parser.hpp" #include "Cycript.tab.hh" -#include - #undef _assert #undef _trace +#ifdef __OBJC__ +#define _throw(name, args...) \ + @throw [NSException exceptionWithName:name reason:[NSString stringWithFormat:@args] userInfo:nil] +#else +#define _throw(name, args...) \ + throw "_throw()" +#endif + #define _assert(test) do { \ if (!(test)) \ - @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \ + _throw(NSInternalInconsistencyException, "*** _assert(%s):%s(%u):%s [errno=%d]", #test, __FILE__, __LINE__, __FUNCTION__, errno); \ } while (false) #define _trace() do { \ - CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \ + fprintf(stderr, "_trace():%u\n", __LINE__); \ } while (false) +#define CYTry \ + try +#define CYCatch \ + catch (NSException *error) { \ + CYThrow(context, error, exception); \ + return NULL; \ + } catch (...) { \ + *exception = CYCastJSValue(context, "catch(...)"); \ + return NULL; \ + } + +#ifdef __OBJC__ #define CYPoolTry { \ id _saved(nil); \ NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \ @@ -95,29 +126,330 @@ [_saved autorelease]; \ } \ } +#else +#define CYPoolTry { +#define CYPoolCatch } +#endif + +#ifndef __APPLE__ +#define class_getSuperclass GSObjCSuper +#define object_getClass GSObjCClass +#endif + +void CYThrow(JSContextRef context, JSValueRef value); + +JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception); + +struct CYUTF8String { + const char *data; + size_t size; + + CYUTF8String(const char *data, size_t size) : + data(data), + size(size) + { + } +}; + +struct CYUTF16String { + const uint16_t *data; + size_t size; + + CYUTF16String(const uint16_t *data, size_t size) : + data(data), + size(size) + { + } +}; + +/* JavaScript Properties {{{ */ +JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) { + JSValueRef exception(NULL); + JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception)); + CYThrow(context, exception); + return value; +} + +JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) { + JSValueRef exception(NULL); + JSValueRef value(JSObjectGetProperty(context, object, name, &exception)); + CYThrow(context, exception); + return value; +} + +void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) { + JSValueRef exception(NULL); + JSObjectSetPropertyAtIndex(context, object, index, value, &exception); + CYThrow(context, exception); +} + +void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) { + JSValueRef exception(NULL); + JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception); + CYThrow(context, exception); +} +/* }}} */ +/* JavaScript Strings {{{ */ +JSStringRef CYCopyJSString(const char *value) { + return value == NULL ? NULL : JSStringCreateWithUTF8CString(value); +} + +JSStringRef CYCopyJSString(JSStringRef value) { + return value == NULL ? NULL : JSStringRetain(value); +} + +JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) { + if (JSValueIsNull(context, value)) + return NULL; + JSValueRef exception(NULL); + JSStringRef string(JSValueToStringCopy(context, value, &exception)); + CYThrow(context, exception); + return string; +} + +class CYJSString { + private: + JSStringRef string_; + + void Clear_() { + if (string_ != NULL) + JSStringRelease(string_); + } + + public: + CYJSString(const CYJSString &rhs) : + string_(CYCopyJSString(rhs.string_)) + { + } + + template + CYJSString(Arg0_ arg0) : + string_(CYCopyJSString(arg0)) + { + } + + template + CYJSString(Arg0_ arg0, Arg1_ arg1) : + string_(CYCopyJSString(arg0, arg1)) + { + } + + CYJSString &operator =(const CYJSString &rhs) { + Clear_(); + string_ = CYCopyJSString(rhs.string_); + return *this; + } + + ~CYJSString() { + Clear_(); + } + + void Clear() { + Clear_(); + string_ = NULL; + } + + operator JSStringRef() const { + return string_; + } +}; +/* }}} */ +/* C Strings {{{ */ +// XXX: this macro is unhygenic +#define CYCastCString_(string) ({ \ + char *utf8; \ + if (string == NULL) \ + utf8 = NULL; \ + else { \ + size_t size(JSStringGetMaximumUTF8CStringSize(string)); \ + utf8 = reinterpret_cast(alloca(size)); \ + JSStringGetUTF8CString(string, utf8, size); \ + } \ + utf8; \ +}) + +// XXX: this macro is unhygenic +#define CYCastCString(context, value) ({ \ + char *utf8; \ + if (value == NULL) \ + utf8 = NULL; \ + else if (JSStringRef string = CYCopyJSString(context, value)) { \ + utf8 = CYCastCString_(string); \ + JSStringRelease(string); \ + } else \ + utf8 = NULL; \ + utf8; \ +}) + +/* }}} */ + +#ifdef __OBJC__ +/* Objective-C Pool Release {{{ */ +apr_status_t CYPoolRelease_(void *data) { + id object(reinterpret_cast(data)); + [object release]; + return APR_SUCCESS; +} + +id CYPoolRelease_(apr_pool_t *pool, id object) { + if (object == nil) + return nil; + else if (pool == NULL) + return [object autorelease]; + else { + apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null); + return object; + } +} + +template +Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) { + return (Type_) CYPoolRelease_(pool, (id) object); +} +/* }}} */ +/* Objective-C Strings {{{ */ +const char *CYPoolCString(apr_pool_t *pool, NSString *value) { + if (pool == NULL) + return [value UTF8String]; + else { + size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1); + char *string(new(pool) char[size]); + if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding]) + _throw(NSInternalInconsistencyException, "[NSString getCString:maxLength:encoding:] == NO"); + return string; + } +} + +JSStringRef CYCopyJSString_(NSString *value) { +#ifdef __APPLE__ + return JSStringCreateWithCFString(reinterpret_cast(value)); +#else + CYPool pool; + return CYCopyJSString(CYPoolCString(pool, value)); +#endif +} + +JSStringRef CYCopyJSString(id value) { + if (value == nil) + return NULL; + // XXX: this definition scares me; is anyone using this?! + NSString *string([value description]); + return CYCopyJSString_(string); +} + +NSString *CYCopyNSString(const CYUTF8String &value) { +#ifdef __APPLE__ + return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast(value.data), value.size, kCFStringEncodingUTF8, true); +#else + return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding]; +#endif +} + +NSString *CYCopyNSString(JSStringRef value) { +#ifdef __APPLE__ + return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value); +#else + return CYCopyNSString(CYCastCString_(value)); +#endif +} + +NSString *CYCopyNSString(JSContextRef context, JSValueRef value) { + return CYCopyNSString(CYJSString(context, value)); +} + +NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) { + return CYPoolRelease(pool, CYCopyNSString(value)); +} + +NSString *CYCastNSString(apr_pool_t *pool, SEL sel) { + const char *name(sel_getName(sel)); + return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name)))); +} + +NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) { + return CYPoolRelease(pool, CYCopyNSString(value)); +} + +CYUTF8String CYCastUTF8String(NSString *value) { + NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]); + return CYUTF8String(reinterpret_cast([data bytes]), [data length]); +} +/* }}} */ +#endif + +/* JavaScript Stringify {{{ */ +void CYStringify(std::ostringstream &str, const char *data, size_t size) { + unsigned quot(0), apos(0); + for (const char *value(data), *end(data + size); value != end; ++value) + if (*value == '"') + ++quot; + else if (*value == '\'') + ++apos; + + bool single(quot > apos); + + str << (single ? '\'' : '"'); + + for (const char *value(data), *end(data + size); value != end; ++value) + switch (*value) { + case '\\': str << "\\\\"; break; + case '\b': str << "\\b"; break; + case '\f': str << "\\f"; break; + case '\n': str << "\\n"; break; + case '\r': str << "\\r"; break; + case '\t': str << "\\t"; break; + case '\v': str << "\\v"; break; + + case '"': + if (!single) + str << "\\\""; + else goto simple; + break; + + case '\'': + if (single) + str << "\\'"; + else goto simple; + break; + + default: + if (*value < 0x20 || *value >= 0x7f) + str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(*value); + else simple: + str << *value; + } + + str << (single ? '\'' : '"'); +} +/* }}} */ static JSGlobalContextRef Context_; static JSObjectRef System_; -static JSObjectRef ObjectiveC_; static JSClassRef Functor_; +static JSClassRef Pointer_; +static JSClassRef Runtime_; +static JSClassRef Struct_; + +#ifdef __OBJC__ static JSClassRef Instance_; static JSClassRef Internal_; static JSClassRef Message_; -static JSClassRef Pointer_; -static JSClassRef Prototype_; -static JSClassRef Runtime_; +static JSClassRef Messages_; static JSClassRef Selector_; -static JSClassRef Struct_; -static JSClassRef Type_; +static JSClassRef Super_; static JSClassRef ObjectiveC_Classes_; static JSClassRef ObjectiveC_Image_Classes_; static JSClassRef ObjectiveC_Images_; static JSClassRef ObjectiveC_Protocols_; +static JSObjectRef Instance_prototype_; +#endif + static JSObjectRef Array_; static JSObjectRef Function_; +static JSObjectRef String_; static JSStringRef Result_; @@ -128,17 +460,25 @@ static JSStringRef prototype_; static JSStringRef toCYON_; static JSStringRef toJSON_; +static JSObjectRef Object_prototype_; + static JSObjectRef Array_prototype_; static JSObjectRef Array_pop_; static JSObjectRef Array_push_; static JSObjectRef Array_splice_; -static Class NSArray_; +#ifdef __OBJC__ +#ifdef __APPLE__ static Class NSCFBoolean_; static Class NSCFType_; +#endif + +static Class NSArray_; +static Class NSDictionary_; static Class NSMessageBuilder_; static Class NSZombie_; static Class Object_; +#endif static NSArray *Bridge_; @@ -156,8 +496,8 @@ struct CYValue : CYValue() { } - CYValue(void *value) : - value_(value) + CYValue(const void *value) : + value_(const_cast(value)) { } @@ -171,6 +511,34 @@ struct CYValue : } }; +struct CYOwned : + CYValue +{ + private: + JSContextRef context_; + JSObjectRef owner_; + + public: + CYOwned(void *value, JSContextRef context, JSObjectRef owner) : + CYValue(value), + context_(context), + owner_(owner) + { + if (owner_ != NULL) + JSValueProtect(context_, owner_); + } + + virtual ~CYOwned() { + if (owner_ != NULL) + JSValueUnprotect(context_, owner_); + } + + JSObjectRef GetOwner() const { + return owner_; + } +}; + +#ifdef __OBJC__ struct Selector_privateData : CYValue { @@ -186,6 +554,37 @@ struct Selector_privateData : virtual Type_privateData *GetType() const; }; +// XXX: trick this out with associated objects! +JSValueRef CYGetClassPrototype(JSContextRef context, id self) { + if (self == nil) + return Instance_prototype_; + + // XXX: I need to think through multi-context + typedef std::map CacheMap; + static CacheMap cache_; + + JSValueRef &value(cache_[self]); + if (value != NULL) + return value; + + JSClassRef _class(NULL); + JSValueRef prototype; + + if (self == NSArray_) + prototype = Array_prototype_; + else if (self == NSDictionary_) + prototype = Object_prototype_; + else + prototype = CYGetClassPrototype(context, class_getSuperclass(self)); + + JSObjectRef object(JSObjectMake(context, _class, NULL)); + JSObjectSetPrototype(context, object, prototype); + + JSValueProtect(context, object); + value = object; + return object; +} + struct Instance : CYValue { @@ -206,17 +605,13 @@ struct Instance : virtual ~Instance() { if ((flags_ & Transient) == 0) // XXX: does this handle background threads correctly? + // XXX: this simply does not work on the console because I'm stupid [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0]; } static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) { JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags))); - if (object != nil) - for (Class _class(object_getClass(object)); _class != nil; _class = class_getSuperclass(_class)) - if (_class == NSArray_) { - JSObjectSetPrototype(context, value, Array_prototype_); - break; - } + JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object))); return value; } @@ -231,20 +626,37 @@ struct Instance : virtual Type_privateData *GetType() const; }; -struct Prototype : +struct Super : + Instance +{ + Class class_; + + Super(id value, Class _class) : + Instance(value, Instance::Transient), + class_(_class) + { + } + + static JSObjectRef Make(JSContextRef context, id object, Class _class) { + JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class))); + return value; + } +}; + +struct Messages : CYValue { - Prototype(Class value) : + Messages(Class value) : CYValue(value) { } static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) { - JSObjectRef value(JSObjectMake(context, Prototype_, new Prototype(_class))); + JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class))); if (_class == NSArray_) array = true; if (Class super = class_getSuperclass(_class)) - JSObjectSetPrototype(context, value, Prototype::Make(context, super, array)); + JSObjectSetPrototype(context, value, Messages::Make(context, super, array)); /*else if (array) JSObjectSetPrototype(context, value, Array_prototype_);*/ return value; @@ -256,24 +668,22 @@ struct Prototype : }; struct Internal : - CYValue + CYOwned { - JSObjectRef owner_; - - Internal(id value, JSObjectRef owner) : - CYValue(value), - owner_(owner) + Internal(id value, JSContextRef context, JSObjectRef owner) : + CYOwned(value, context, owner) { } static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) { - return JSObjectMake(context, Internal_, new Internal(object, owner)); + return JSObjectMake(context, Internal_, new Internal(object, context, owner)); } id GetValue() const { return reinterpret_cast(value_); } }; +#endif namespace sig { @@ -306,9 +716,14 @@ void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) { if (sig::IsAggregate(rhs.primitive)) Copy(pool, lhs.data.signature, rhs.data.signature); else { - if (rhs.data.data.type != NULL) { - lhs.data.data.type = new(pool) Type; - Copy(pool, *lhs.data.data.type, *rhs.data.data.type); + sig::Type *&lht(lhs.data.data.type); + sig::Type *&rht(rhs.data.data.type); + + if (rht == NULL) + lht = NULL; + else { + lht = new(pool) Type; + Copy(pool, *lht, *rht); } lhs.data.data.size = rhs.data.data.size; @@ -371,8 +786,12 @@ void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type struct Type_privateData : CYData { +#ifdef __OBJC__ static Type_privateData *Object; static Type_privateData *Selector; +#endif + + static JSClassRef Class_; ffi_type *ffi_; sig::Type *type_; @@ -428,6 +847,9 @@ struct Type_privateData : } }; +JSClassRef Type_privateData::Class_; + +#ifdef __OBJC__ Type_privateData *Type_privateData::Object; Type_privateData *Type_privateData::Selector; @@ -438,29 +860,27 @@ Type_privateData *Instance::GetType() const { Type_privateData *Selector_privateData::GetType() const { return Type_privateData::Selector; } +#endif struct Pointer : - CYValue + CYOwned { - JSObjectRef owner_; Type_privateData *type_; - Pointer(void *value, sig::Type *type, JSObjectRef owner) : - CYValue(value), - owner_(owner), + Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) : + CYOwned(value, context, owner), type_(new(pool_) Type_privateData(type)) { } }; struct Struct_privateData : - CYValue + CYOwned { - JSObjectRef owner_; Type_privateData *type_; - Struct_privateData(JSObjectRef owner) : - owner_(owner) + Struct_privateData(JSContextRef context, JSObjectRef owner) : + CYOwned(NULL, context, owner) { } }; @@ -469,7 +889,7 @@ typedef std::map TypeMap; static TypeMap Types_; JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) { - Struct_privateData *internal(new Struct_privateData(owner)); + Struct_privateData *internal(new Struct_privateData(context, owner)); apr_pool_t *pool(internal->pool_); Type_privateData *typical(new(pool) Type_privateData(type, ffi)); internal->type_ = typical; @@ -492,7 +912,6 @@ struct Functor_privateData : sig::Signature signature_; ffi_cif cif_; - Functor_privateData(const char *type, void (*value)()) : CYValue(reinterpret_cast(value)) { @@ -511,12 +930,20 @@ struct Closure_privateData : JSContextRef context_; JSObjectRef function_; - Closure_privateData(const char *type) : - Functor_privateData(type, NULL) + Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) : + Functor_privateData(type, NULL), + context_(context), + function_(function) { + JSValueProtect(context_, function_); + } + + virtual ~Closure_privateData() { + JSValueUnprotect(context_, function_); } }; +#ifdef __OBJC__ struct Message_privateData : Functor_privateData { @@ -541,18 +968,7 @@ JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) { return Instance::Make(context, object, flags); } - -const char *CYPoolCString(apr_pool_t *pool, NSString *value) { - if (pool == NULL) - return [value UTF8String]; - else { - size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1); - char *string(new(pool) char[size]); - if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding]) - @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil]; - return string; - } -} +#endif JSValueRef CYCastJSValue(JSContextRef context, bool value) { return JSValueMakeBoolean(context, value); @@ -578,19 +994,22 @@ JSValueRef CYJSUndefined(JSContextRef context) { return JSValueMakeUndefined(context); } -size_t CYGetIndex(const char *value) { - if (value[0] != '0') { +size_t CYGetIndex(const CYUTF8String &value) { + if (value.data[0] != '0') { char *end; - size_t index(strtoul(value, &end, 10)); - if (value + strlen(value) == end) + size_t index(strtoul(value.data, &end, 10)); + if (value.data + value.size == end) return index; - } else if (value[1] == '\0') + } else if (value.data[1] == '\0') return 0; return _not(size_t); } -size_t CYGetIndex(apr_pool_t *pool, NSString *value) { - return CYGetIndex(CYPoolCString(pool, value)); +// XXX: fix this +static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value); + +size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) { + return CYGetIndex(CYPoolUTF8String(pool, value)); } bool CYGetOffset(const char *value, ssize_t &index) { @@ -607,12 +1026,17 @@ bool CYGetOffset(const char *value, ssize_t &index) { return false; } +#ifdef __OBJC__ +size_t CYGetIndex(NSString *value) { + return CYGetIndex(CYCastUTF8String(value)); +} + bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) { return CYGetOffset(CYPoolCString(pool, value), index); } +#endif -NSString *CYPoolNSCYON(apr_pool_t *pool, id value); - +#ifdef __OBJC__ @interface NSMethodSignature (Cycript) - (NSString *) _typeString; @end @@ -640,7 +1064,47 @@ NSString *CYPoolNSCYON(apr_pool_t *pool, id value); @interface NSString (Cycript) - (void *) cy$symbol; @end +#endif + +#ifdef __OBJC__ +NSString *CYCastNSCYON(id value) { + NSString *string; + if (value == nil) + string = @"nil"; + else { + Class _class(object_getClass(value)); + SEL sel(@selector(cy$toCYON)); + + if (objc_method *toCYON = class_getInstanceMethod(_class, sel)) + string = reinterpret_cast(method_getImplementation(toCYON))(value, sel); + else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) { + if (reinterpret_cast(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; +} +#endif + +#ifdef __OBJC__ +#ifdef __APPLE__ struct PropertyAttributes { CYPool pool_; @@ -726,99 +1190,41 @@ struct PropertyAttributes { } }; +#endif +#endif -@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; -} - -- (NSObject *) cy$toJSON:(NSString *)key { - return [self description]; -} - -- (NSString *) cy$toCYON { - return [[self cy$toJSON:@""] cy$toCYON]; -} - -- (NSString *) cy$toKey { - return [self cy$toCYON]; -} - -- (bool) cy$hasProperty:(NSString *)name { - return false; -} - -- (NSObject *) cy$getProperty:(NSString *)name { - return nil; -} - -- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value { - return false; -} - -- (bool) cy$deleteProperty:(NSString *)name { - return false; -} - -@end - -NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { +#ifdef __OBJC__ +#ifdef __APPLE__ +NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]; } +#endif +#endif -@implementation WebUndefined (Cycript) - -- (JSType) cy$JSType { - return kJSTypeUndefined; -} - -- (NSObject *) cy$toJSON:(NSString *)key { - return self; -} - -- (NSString *) cy$toCYON { - return @"undefined"; +#ifdef __OBJC__ +#ifndef __APPLE__ +@interface CYWebUndefined : NSObject { } -- (JSValueRef) cy$JSValueInContext:(JSContextRef)context { - return CYJSUndefined(context); -} ++ (CYWebUndefined *) undefined; @end -@implementation NSNull (Cycript) +@implementation CYWebUndefined -- (JSType) cy$JSType { - return kJSTypeNull; -} - -- (NSObject *) cy$toJSON:(NSString *)key { - return self; -} - -- (NSString *) cy$toCYON { - return @"null"; ++ (CYWebUndefined *) undefined { + static CYWebUndefined *instance_([[CYWebUndefined alloc] init]); + return instance_; } @end +#define WebUndefined CYWebUndefined +#endif +#endif + +#ifdef __OBJC__ +/* Bridge: NSArray {{{ */ @implementation NSArray (Cycript) - (NSString *) cy$toCYON { @@ -826,13 +1232,19 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { [json appendString:@"["]; bool comma(false); +#ifdef __APPLE__ for (id object in self) { +#else + id object; + for (size_t index(0), count([self count]); index != count; ++index) { + object = [self objectAtIndex:index]; +#endif if (comma) [json appendString:@","]; else comma = true; if (object == nil || [object cy$JSType] != kJSTypeUndefined) - [json appendString:CYPoolNSCYON(NULL, object)]; + [json appendString:CYCastNSCYON(object)]; else { [json appendString:@","]; comma = false; @@ -847,7 +1259,7 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { if ([name isEqualToString:@"length"]) return true; - size_t index(CYGetIndex(NULL, name)); + size_t index(CYGetIndex(name)); if (index == _not(size_t) || index >= [self count]) return [super cy$hasProperty:name]; else @@ -855,10 +1267,16 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { } - (NSObject *) cy$getProperty:(NSString *)name { - if ([name isEqualToString:@"length"]) - return [NSNumber numberWithUnsignedInteger:[self count]]; + if ([name isEqualToString:@"length"]) { + NSUInteger count([self count]); +#ifdef __APPLE__ + return [NSNumber numberWithUnsignedInteger:count]; +#else + return [NSNumber numberWithUnsignedInt:count]; +#endif + } - size_t index(CYGetIndex(NULL, name)); + size_t index(CYGetIndex(name)); if (index == _not(size_t) || index >= [self count]) return [super cy$getProperty:name]; else @@ -866,13 +1284,57 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { } @end +/* }}} */ +/* Bridge: NSDictionary {{{ */ +@implementation NSDictionary (Cycript) + +- (NSString *) cy$toCYON { + NSMutableString *json([[[NSMutableString alloc] init] autorelease]); + [json appendString:@"{"]; + + bool comma(false); +#ifdef __APPLE__ + for (id key in self) { +#else + NSEnumerator *keys([self keyEnumerator]); + while (id key = [keys nextObject]) { +#endif + if (comma) + [json appendString:@","]; + else + comma = true; + [json appendString:[key cy$toKey]]; + [json appendString:@":"]; + NSObject *object([self objectForKey:key]); + [json appendString:CYCastNSCYON(object)]; + } + + [json appendString:@"}"]; + return json; +} + +- (bool) cy$hasProperty:(NSString *)name { + return [self objectForKey:name] != nil; +} + +- (NSObject *) cy$getProperty:(NSString *)name { + return [self objectForKey:name]; +} +@end +/* }}} */ +/* Bridge: NSMutableArray {{{ */ @implementation NSMutableArray (Cycript) - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value { if ([name isEqualToString:@"length"]) { // XXX: is this not intelligent? - NSUInteger size([(NSNumber *)value unsignedIntegerValue]); + NSNumber *number(reinterpret_cast(value)); +#ifdef __APPLE__ + NSUInteger size([number unsignedIntegerValue]); +#else + NSUInteger size([number unsignedIntValue]); +#endif NSUInteger count([self count]); if (size < count) [self removeObjectsInRange:NSMakeRange(size, count - size)]; @@ -884,7 +1346,7 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { return true; } - size_t index(CYGetIndex(NULL, name)); + size_t index(CYGetIndex(name)); if (index == _not(size_t)) return [super cy$setProperty:name to:value]; @@ -907,7 +1369,7 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { } - (bool) cy$deleteProperty:(NSString *)name { - size_t index(CYGetIndex(NULL, name)); + size_t index(CYGetIndex(name)); if (index == _not(size_t) || index >= [self count]) return [super cy$deleteProperty:name]; [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]]; @@ -915,39 +1377,8 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { } @end - -@implementation NSDictionary (Cycript) - -- (NSString *) cy$toCYON { - NSMutableString *json([[[NSMutableString alloc] init] autorelease]); - [json appendString:@"{"]; - - bool comma(false); - for (id key in self) { - if (comma) - [json appendString:@","]; - else - comma = true; - [json appendString:[key cy$toKey]]; - [json appendString:@":"]; - NSObject *object([self objectForKey:key]); - [json appendString:CYPoolNSCYON(NULL, object)]; - } - - [json appendString:@"}"]; - return json; -} - -- (bool) cy$hasProperty:(NSString *)name { - return [self objectForKey:name] != nil; -} - -- (NSObject *) cy$getProperty:(NSString *)name { - return [self objectForKey:name]; -} - -@end - +/* }}} */ +/* Bridge: NSMutableDictionary {{{ */ @implementation NSMutableDictionary (Cycript) - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value { @@ -965,12 +1396,17 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { } @end - +/* }}} */ +/* Bridge: NSNumber {{{ */ @implementation NSNumber (Cycript) - (JSType) cy$JSType { +#ifdef __APPLE__ // XXX: this just seems stupid - return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber; + if ([self class] == NSCFBoolean_) + return kJSTypeBoolean; +#endif + return kJSTypeNumber; } - (NSObject *) cy$toJSON:(NSString *)key { @@ -986,11 +1422,12 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { } @end - -@implementation NSString (Cycript) +/* }}} */ +/* Bridge: NSNull {{{ */ +@implementation NSNull (Cycript) - (JSType) cy$JSType { - return kJSTypeString; + return kJSTypeNull; } - (NSObject *) cy$toJSON:(NSString *)key { @@ -998,19 +1435,82 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { } - (NSString *) cy$toCYON { - // XXX: this should use the better code from Output.cpp - CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self)); + return @"null"; +} + +@end +/* }}} */ +/* Bridge: NSObject {{{ */ +@implementation NSObject (Cycript) + +- (JSValueRef) cy$JSValueInContext:(JSContextRef)context { + return CYMakeInstance(context, self, false); +} + +- (JSType) cy$JSType { + return kJSTypeObject; +} + +- (NSObject *) cy$toJSON:(NSString *)key { + return [self description]; +} + +- (NSString *) cy$toCYON { + return [[self cy$toJSON:@""] cy$toCYON]; +} + +- (NSString *) cy$toKey { + return [self cy$toCYON]; +} + +- (bool) cy$hasProperty:(NSString *)name { + return false; +} + +- (NSObject *) cy$getProperty:(NSString *)name { + return nil; +} + +- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value { + return false; +} + +- (bool) cy$deleteProperty:(NSString *)name { + return false; +} + +@end +/* }}} */ +/* Bridge: NSProxy {{{ */ +@implementation NSProxy (Cycript) + +- (NSObject *) cy$toJSON:(NSString *)key { + return [self description]; +} + +- (NSString *) cy$toCYON { + return [[self cy$toJSON:@""] cy$toCYON]; +} + +@end +/* }}} */ +/* Bridge: NSString {{{ */ +@implementation NSString (Cycript) - CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0); - CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0); - CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0); - CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0); - CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0); +- (JSType) cy$JSType { + return kJSTypeString; +} - CFStringInsert(json, 0, CFSTR("\"")); - CFStringAppend(json, CFSTR("\"")); +- (NSObject *) cy$toJSON:(NSString *)key { + return self; +} - return [reinterpret_cast(json) autorelease]; +- (NSString *) cy$toCYON { + std::ostringstream str; + CYUTF8String string(CYCastUTF8String(self)); + CYStringify(str, string.data, string.size); + std::string value(str.str()); + return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size())); } - (NSString *) cy$toKey { @@ -1021,7 +1521,7 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { goto cyon; if (DigitRange_[value[0]]) { - size_t index(CYGetIndex(NULL, self)); + size_t index(CYGetIndex(self)); if (index == _not(size_t)) goto cyon; } else { @@ -1044,169 +1544,86 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { } @end +/* }}} */ +/* Bridge: WebUndefined {{{ */ +@implementation WebUndefined (Cycript) -@interface CYJSObject : NSMutableDictionary { - JSObjectRef object_; - JSContextRef context_; +- (JSType) cy$JSType { + return kJSTypeUndefined; } -- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context; +- (NSObject *) cy$toJSON:(NSString *)key { + return self; +} -- (NSString *) cy$toJSON:(NSString *)key; +- (NSString *) cy$toCYON { + return @"undefined"; +} -- (NSUInteger) count; -- (id) objectForKey:(id)key; -- (NSEnumerator *) keyEnumerator; -- (void) setObject:(id)object forKey:(id)key; -- (void) removeObjectForKey:(id)key; +- (JSValueRef) cy$JSValueInContext:(JSContextRef)context { + return CYJSUndefined(context); +} @end +/* }}} */ -@interface CYJSArray : NSMutableArray { +/* Bridge: CYJSObject {{{ */ +@interface CYJSObject : NSMutableDictionary { JSObjectRef object_; JSContextRef context_; } - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context; -- (NSUInteger) count; -- (id) objectAtIndex:(NSUInteger)index; - -- (void) addObject:(id)anObject; -- (void) insertObject:(id)anObject atIndex:(NSUInteger)index; -- (void) removeLastObject; -- (void) removeObjectAtIndex:(NSUInteger)index; -- (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject; - -@end - -CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9 -CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$ -CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9 - -#define CYTry \ - @try -#define CYCatch \ - @catch (id error) { \ - CYThrow(context, error, exception); \ - return NULL; \ - } - -void CYThrow(JSContextRef context, JSValueRef value); - -apr_status_t CYPoolRelease_(void *data) { - id object(reinterpret_cast(data)); - [object release]; - return APR_SUCCESS; -} - -id CYPoolRelease(apr_pool_t *pool, id object) { - if (object == nil) - return nil; - else if (pool == NULL) - return [object autorelease]; - else { - apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null); - return object; - } -} - -CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) { - return (CFTypeRef) CYPoolRelease(pool, (id) object); -} - -id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) { - JSValueRef exception(NULL); - bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception)); - CYThrow(context, exception); - id value(array ? [CYJSArray alloc] : [CYJSObject alloc]); - 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 *internal(reinterpret_cast(JSObjectGetPrivate(object))); - return internal->GetValue(); - } -} - -JSStringRef CYCopyJSString(id value) { - return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast([value description])); -} - -JSStringRef CYCopyJSString(const char *value) { - return value == NULL ? NULL : JSStringCreateWithUTF8CString(value); -} - -JSStringRef CYCopyJSString(JSStringRef value) { - return value == NULL ? NULL : JSStringRetain(value); -} - -JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) { - if (JSValueIsNull(context, value)) - return NULL; - JSValueRef exception(NULL); - JSStringRef string(JSValueToStringCopy(context, value, &exception)); - CYThrow(context, exception); - return string; -} - -class CYJSString { - private: - JSStringRef string_; - - void Clear_() { - if (string_ != NULL) - JSStringRelease(string_); - } - - public: - CYJSString(const CYJSString &rhs) : - string_(CYCopyJSString(rhs.string_)) - { - } +- (NSObject *) cy$toJSON:(NSString *)key; - template - CYJSString(Arg0_ arg0) : - string_(CYCopyJSString(arg0)) - { - } +- (NSUInteger) count; +- (id) objectForKey:(id)key; +- (NSEnumerator *) keyEnumerator; +- (void) setObject:(id)object forKey:(id)key; +- (void) removeObjectForKey:(id)key; - template - CYJSString(Arg0_ arg0, Arg1_ arg1) : - string_(CYCopyJSString(arg0, arg1)) - { - } +@end +/* }}} */ +/* Bridge: CYJSArray {{{ */ +@interface CYJSArray : NSMutableArray { + JSObjectRef object_; + JSContextRef context_; +} - CYJSString &operator =(const CYJSString &rhs) { - Clear_(); - string_ = CYCopyJSString(rhs.string_); - return *this; - } +- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context; - ~CYJSString() { - Clear_(); - } +- (NSUInteger) count; +- (id) objectAtIndex:(NSUInteger)index; - void Clear() { - Clear_(); - string_ = NULL; - } +- (void) addObject:(id)anObject; +- (void) insertObject:(id)anObject atIndex:(NSUInteger)index; +- (void) removeLastObject; +- (void) removeObjectAtIndex:(NSUInteger)index; +- (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject; - operator JSStringRef() const { - return string_; - } -}; +@end +/* }}} */ +#endif -CFStringRef CYCopyCFString(JSStringRef value) { - return JSStringCopyCFString(kCFAllocatorDefault, value); +#ifdef __OBJC__ +NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) { + JSValueRef exception(NULL); + bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception)); + CYThrow(context, exception); + id value(array ? [CYJSArray alloc] : [CYJSObject alloc]); + return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]); } -CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) { - return CYCopyCFString(CYJSString(context, value)); +NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) { + if (!JSValueIsObjectOfClass(context, object, Instance_)) + return CYCastNSObject_(pool, context, object); + else { + Instance *internal(reinterpret_cast(JSObjectGetPrivate(object))); + return internal->GetValue(); + } } +#endif double CYCastDouble(const char *value, size_t size) { char *end; @@ -1227,29 +1644,19 @@ double CYCastDouble(JSContextRef context, JSValueRef value) { return number; } -CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) { - double number(CYCastDouble(context, value)); - return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number); -} - -CFStringRef CYCopyCFString(const char *value) { - return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8); -} - -NSString *CYCastNSString(apr_pool_t *pool, const char *value) { - return (NSString *) CYPoolRelease(pool, CYCopyCFString(value)); -} - -NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) { - return (NSString *) CYPoolRelease(pool, CYCopyCFString(value)); +#ifdef __OBJC__ +NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) { + return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)]; } +#endif bool CYCastBool(JSContextRef context, JSValueRef value) { return JSValueToBoolean(context, value); } -CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) { - CFTypeRef object; +#ifdef __OBJC__ +id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) { + id object; bool copy; switch (JSType type = JSValueGetType(context, value)) { @@ -1263,28 +1670,33 @@ CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, boo break; case kJSTypeBoolean: - object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse; +#ifdef __APPLE__ + object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse); copy = false; +#else + object = [[NSNumber alloc] initWithBool:CYCastBool(context, value)]; + copy = true; +#endif break; case kJSTypeNumber: - object = CYCopyCFNumber(context, value); + object = CYCopyNSNumber(context, value); copy = true; break; case kJSTypeString: - object = CYCopyCFString(context, value); + object = CYCopyNSString(context, value); copy = true; break; case kJSTypeObject: // XXX: this might could be more efficient - object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value); + object = CYCastNSObject(pool, context, (JSObjectRef) value); copy = false; break; default: - @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil]; + _throw(NSInternalInconsistencyException, "JSValueGetType() == 0x%x", type); break; } @@ -1293,15 +1705,27 @@ CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, boo else if (copy) return CYPoolRelease(pool, object); else - return CFRetain(object); + return [object retain]; } -CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) { - return CYCFType(pool, context, value, true); +NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) { + return CYNSObject(pool, context, value, true); +} +NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) { + return CYNSObject(pool, context, value, false); +} + +static bool CYIsClass(id self) { + // XXX: this is a lame object_isClass + return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL; } -CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) { - return CYCFType(pool, context, value, false); +Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) { + id self(CYCastNSObject(pool, context, value)); + if (CYIsClass(self)) + return (Class) self; + _throw(NSInvalidArgumentException, "got something that is not a Class"); + return NULL; } NSArray *CYCastNSArray(JSPropertyNameArrayRef names) { @@ -1312,15 +1736,17 @@ NSArray *CYCastNSArray(JSPropertyNameArrayRef names) { [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))]; return array; } - -id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) { - return reinterpret_cast(CYCastCFType(pool, context, value)); -} +#endif void CYThrow(JSContextRef context, JSValueRef value) { if (value == NULL) return; +#ifdef __OBJC__ @throw CYCastNSObject(NULL, context, value); +#else + // XXX: why not? + throw value; +#endif } JSValueRef CYJSNull(JSContextRef context) { @@ -1335,6 +1761,7 @@ JSValueRef CYCastJSValue(JSContextRef context, const char *value) { return CYCastJSValue(context, CYJSString(value)); } +#ifdef __OBJC__ JSValueRef CYCastJSValue(JSContextRef context, id value) { if (value == nil) return CYJSNull(context); @@ -1343,6 +1770,7 @@ JSValueRef CYCastJSValue(JSContextRef context, id value) { else return CYMakeInstance(context, value, false); } +#endif JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) { JSValueRef exception(NULL); @@ -1351,32 +1779,6 @@ JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) { return object; } -JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) { - JSValueRef exception(NULL); - JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception)); - CYThrow(context, exception); - return value; -} - -JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) { - JSValueRef exception(NULL); - JSValueRef value(JSObjectGetProperty(context, object, name, &exception)); - CYThrow(context, exception); - return value; -} - -void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) { - JSValueRef exception(NULL); - JSObjectSetPropertyAtIndex(context, object, index, value, &exception); - CYThrow(context, exception); -} - -void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) { - JSValueRef exception(NULL); - JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception); - CYThrow(context, exception); -} - void CYThrow(JSContextRef context, id error, JSValueRef *exception) { if (exception == NULL) throw error; @@ -1391,19 +1793,25 @@ JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObject } bool CYIsCallable(JSContextRef context, JSValueRef value) { - // XXX: this isn't actually correct - return value != NULL && JSValueIsObject(context, value); + return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value); } +#ifdef __OBJC__ @implementation CYJSObject - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { if ((self = [super init]) != nil) { object_ = object; context_ = context; + JSValueProtect(context_, object_); } return self; } +- (void) dealloc { + JSValueUnprotect(context_, object_); + [super dealloc]; +} + - (NSObject *) cy$toJSON:(NSString *)key { JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_)); if (!CYIsCallable(context_, toJSON)) @@ -1418,12 +1826,11 @@ bool CYIsCallable(JSContextRef context, JSValueRef value) { - (NSString *) cy$toCYON { JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_)); - if (!CYIsCallable(context_, toCYON)) + if (!CYIsCallable(context_, toCYON)) super: return [super cy$toCYON]; - else { - JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL)); + else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL)) return CYCastNSString(NULL, CYJSString(context_, value)); - } + else goto super; } - (NSUInteger) count { @@ -1465,9 +1872,15 @@ bool CYIsCallable(JSContextRef context, JSValueRef value) { if ((self = [super init]) != nil) { object_ = object; context_ = context; + JSValueProtect(context_, object_); } return self; } +- (void) dealloc { + JSValueUnprotect(context_, object_); + [super dealloc]; +} + - (NSUInteger) count { return CYCastDouble(context_, CYGetProperty(context_, object_, length_)); } @@ -1529,41 +1942,7 @@ bool CYIsCallable(JSContextRef context, JSValueRef value) { } @end - -NSString *CYCopyNSCYON(id value) { - NSString *string; - - if (value == nil) - string = @"nil"; - else { - Class _class(object_getClass(value)); - SEL sel(@selector(cy$toCYON)); - - if (Method toCYON = class_getInstanceMethod(_class, sel)) - string = reinterpret_cast(method_getImplementation(toCYON))(value, sel); - else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) { - if (reinterpret_cast(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]; -} +#endif NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) { if (JSValueIsNull(context, value)) @@ -1571,15 +1950,11 @@ NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *excep CYTry { CYPoolTry { - return CYCopyNSCYON(CYCastNSObject(NULL, context, value)); + return [CYCastNSCYON(CYCastNSObject(NULL, context, value)) retain]; } CYPoolCatch(NULL) } CYCatch } -NSString *CYPoolNSCYON(apr_pool_t *pool, id value) { - return CYPoolRelease(pool, static_cast(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)); @@ -1588,6 +1963,7 @@ const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value } else return NULL; } +#ifdef __OBJC__ // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6 struct CYInternal : CYData @@ -1644,58 +2020,66 @@ struct CYInternal : CYSetProperty(context, object_, name, value); } }; +#endif -JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) { +#ifdef __OBJC__ +static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) { Selector_privateData *internal(new Selector_privateData(sel)); return JSObjectMake(context, Selector_, internal); } +#endif -JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) { - Pointer *internal(new Pointer(pointer, type, owner)); +static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) { + Pointer *internal(new Pointer(pointer, context, owner, type)); return JSObjectMake(context, Pointer_, internal); } -JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) { +static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) { Functor_privateData *internal(new Functor_privateData(type, function)); return JSObjectMake(context, Functor_, internal); } -const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) { - if (pool == NULL) { - const char *string([CYCastNSString(NULL, value) UTF8String]); - return string; - } else { - size_t size(JSStringGetMaximumUTF8CStringSize(value)); - char *string(new(pool) char[size]); - JSStringGetUTF8CString(value, string, size); - return string; - } +static CYUTF16String CYCastUTF16String(JSStringRef value) { + return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value)); +} + +// XXX: sometimes pool is null +static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value) { + CYUTF16String utf16(CYCastUTF16String(value)); + const char *in(reinterpret_cast(utf16.data)); + + iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL"))); + + size_t size(JSStringGetMaximumUTF8CStringSize(value)); + char *out(new(pool) char[size]); + CYUTF8String utf8(out, size); + + size = utf16.size * 2; + _syscall(iconv(conversion, const_cast(&in), &size, &out, &utf8.size)); + + *out = '\0'; + utf8.size = out - utf8.data; + + _syscall(iconv_close(conversion)); + + return utf8; +} + +static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) { + CYUTF8String utf8(CYPoolUTF8String(pool, value)); + _assert(memchr(utf8.data, '\0', utf8.size) == NULL); + return utf8.data; } -const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) { +static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) { return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value)); } -bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) { +static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) { return CYGetOffset(CYPoolCString(pool, value), index); } -// XXX: this macro is unhygenic -#define CYCastCString(context, value) ({ \ - char *utf8; \ - if (value == NULL) \ - utf8 = NULL; \ - else if (JSStringRef string = CYCopyJSString(context, value)) { \ - size_t size(JSStringGetMaximumUTF8CStringSize(string)); \ - utf8 = reinterpret_cast(alloca(size)); \ - JSStringGetUTF8CString(string, utf8, size); \ - JSStringRelease(string); \ - } else \ - utf8 = NULL; \ - utf8; \ -}) - -void *CYCastPointer_(JSContextRef context, JSValueRef value) { +static void *CYCastPointer_(JSContextRef context, JSValueRef value) { switch (JSValueGetType(context, value)) { case kJSTypeNull: return NULL; @@ -1709,25 +2093,27 @@ void *CYCastPointer_(JSContextRef context, JSValueRef value) { default: double number(CYCastDouble(context, value)); if (std::isnan(number)) - @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil]; + _throw(NSInvalidArgumentException, "cannot convert value to pointer"); return reinterpret_cast(static_cast(static_cast(number))); } } template -_finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) { +static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) { return reinterpret_cast(CYCastPointer_(context, value)); } -SEL CYCastSEL(JSContextRef context, JSValueRef value) { +#ifdef __OBJC__ +static SEL CYCastSEL(JSContextRef context, JSValueRef value) { if (JSValueIsObjectOfClass(context, value, Selector_)) { Selector_privateData *internal(reinterpret_cast(JSObjectGetPrivate((JSObjectRef) value))); return reinterpret_cast(internal->value_); } else return CYCastPointer(context, value); } +#endif -void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { +static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { switch (type->primitive) { case sig::boolean_P: *reinterpret_cast(data) = JSValueToBoolean(context, value); @@ -1751,6 +2137,7 @@ void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type CYPoolFFI_(float, float) CYPoolFFI_(double, double) +#ifdef __OBJC__ case sig::object_P: case sig::typename_P: *reinterpret_cast(data) = CYCastNSObject(pool, context, value); @@ -1759,6 +2146,7 @@ void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type case sig::selector_P: *reinterpret_cast(data) = CYCastSEL(context, value); break; +#endif case sig::pointer_P: *reinterpret_cast(data) = CYCastPointer(context, value); @@ -1786,7 +2174,7 @@ void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type else goto undefined; if (JSValueIsUndefined(context, rhs)) undefined: - @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil]; + _throw(NSInvalidArgumentException, "unable to extract structure value"); } } @@ -1800,12 +2188,12 @@ void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type break; default: - NSLog(@"CYPoolFFI(%c)\n", type->primitive); + fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive); _assert(false); } } -JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) { +static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) { JSValueRef value; switch (type->primitive) { @@ -1831,6 +2219,7 @@ JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void CYFromFFI_(float, float) CYFromFFI_(double, double) +#ifdef __OBJC__ case sig::object_P: { if (id object = *reinterpret_cast(data)) { value = CYCastJSValue(context, object); @@ -1848,6 +2237,7 @@ JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void value = CYMakeSelector(context, sel); else goto null; break; +#endif case sig::pointer_P: if (void *pointer = *reinterpret_cast(data)) @@ -1874,7 +2264,7 @@ JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void break; default: - NSLog(@"CYFromFFI(%c)\n", type->primitive); + fprintf(stderr, "CYFromFFI(%c)\n", type->primitive); _assert(false); } @@ -1882,7 +2272,7 @@ JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void } static bool CYImplements(id object, Class _class, SEL selector, bool devoid) { - if (Method method = class_getInstanceMethod(_class, selector)) { + if (objc_method *method = class_getInstanceMethod(_class, selector)) { if (!devoid) return true; char type[16]; @@ -1895,16 +2285,16 @@ static bool CYImplements(id object, Class _class, SEL selector, bool devoid) { return false; } -const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) { +static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, objc_method *method) { if (method != NULL) return method_getTypeEncoding(method); - else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))]) + else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel)]) return CYPoolCString(pool, type); else return NULL; } -void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) { +static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) { Closure_privateData *internal(reinterpret_cast(arg)); JSContextRef context(internal->context_); @@ -1919,7 +2309,7 @@ void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) { CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value); } -void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) { +static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) { Closure_privateData *internal(reinterpret_cast(arg)); JSContextRef context(internal->context_); @@ -1936,10 +2326,10 @@ void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) { CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value); } -Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) { +static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) { // XXX: in case of exceptions this will leak // XXX: in point of fact, this may /need/ to leak :( - Closure_privateData *internal(new Closure_privateData(type)); + Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type)); ffi_closure *closure((ffi_closure *) _syscall(mmap( NULL, sizeof(ffi_closure), @@ -1954,13 +2344,10 @@ Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, internal->value_ = closure; - internal->context_ = CYGetJSContext(); - internal->function_ = function; - return internal; } -JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) { +static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) { Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_)); return JSObjectMake(context, Functor_, internal); } @@ -1979,6 +2366,7 @@ static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const c } } +#ifdef __OBJC__ static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) { Message_privateData *internal(new Message_privateData(sel, type, imp)); return JSObjectMake(context, Message_, internal); @@ -1990,8 +2378,8 @@ static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *typ return reinterpret_cast(internal->GetValue()); } -static bool Prototype_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) { - Prototype *internal(reinterpret_cast(JSObjectGetPrivate(object))); +static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) { + Messages *internal(reinterpret_cast(JSObjectGetPrivate(object))); Class _class(internal->GetValue()); CYPool pool; @@ -2004,22 +2392,22 @@ static bool Prototype_hasProperty(JSContextRef context, JSObjectRef object, JSSt return false; } -static JSValueRef Prototype_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { - Prototype *internal(reinterpret_cast(JSObjectGetPrivate(object))); +static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { + Messages *internal(reinterpret_cast(JSObjectGetPrivate(object))); Class _class(internal->GetValue()); CYPool pool; const char *name(CYPoolCString(pool, property)); if (SEL sel = sel_getUid(name)) - if (Method method = class_getInstanceMethod(_class, sel)) + if (objc_method *method = class_getInstanceMethod(_class, sel)) return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method)); return NULL; } -static bool Prototype_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { - Prototype *internal(reinterpret_cast(JSObjectGetPrivate(object))); +static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { + Messages *internal(reinterpret_cast(JSObjectGetPrivate(object))); Class _class(internal->GetValue()); CYPool pool; @@ -2027,7 +2415,7 @@ static bool Prototype_setProperty(JSContextRef context, JSObjectRef object, JSSt SEL sel(sel_registerName(name)); - Method method(class_getInstanceMethod(_class, sel)); + objc_method *method(class_getInstanceMethod(_class, sel)); const char *type; IMP imp; @@ -2050,15 +2438,15 @@ static bool Prototype_setProperty(JSContextRef context, JSObjectRef object, JSSt } #if !__OBJC2__ -static bool Prototype_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { - Prototype *internal(reinterpret_cast(JSObjectGetPrivate(object))); +static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { + Messages *internal(reinterpret_cast(JSObjectGetPrivate(object))); Class _class(internal->GetValue()); CYPool pool; const char *name(CYPoolCString(pool, property)); if (SEL sel = sel_getUid(name)) - if (Method method = class_getInstanceMethod(_class, sel)) { + if (objc_method *method = class_getInstanceMethod(_class, sel)) { objc_method_list list = {NULL, 1, {method}}; class_removeMethods(_class, &list); return true; @@ -2068,12 +2456,12 @@ static bool Prototype_deleteProperty(JSContextRef context, JSObjectRef object, J } #endif -static void Prototype_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) { - Prototype *internal(reinterpret_cast(JSObjectGetPrivate(object))); +static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) { + Messages *internal(reinterpret_cast(JSObjectGetPrivate(object))); Class _class(internal->GetValue()); unsigned int size; - Method *data(class_copyMethodList(_class, &size)); + objc_method **data(class_copyMethodList(_class, &size)); for (size_t i(0); i != size; ++i) JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i])))); free(data); @@ -2093,13 +2481,16 @@ static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStr if (internal->HasProperty(context, property)) return true; + Class _class(object_getClass(self)); + CYPoolTry { - if ([self cy$hasProperty:name]) - return true; + // XXX: this is an evil hack to deal with NSProxy; fix elsewhere + if (CYImplements(self, _class, @selector(cy$hasProperty:), false)) + if ([self cy$hasProperty:name]) + return true; } CYPoolCatch(false) const char *string(CYPoolCString(pool, name)); - Class _class(object_getClass(self)); if (class_getProperty(_class, string) != NULL) return true; @@ -2134,15 +2525,17 @@ static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, const char *string(CYPoolCString(pool, name)); Class _class(object_getClass(self)); +#ifdef __APPLE__ 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 CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception); } +#endif if (SEL sel = sel_getUid(string)) if (CYImplements(self, _class, sel, true)) - return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception); + return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception); return NULL; } CYCatch @@ -2156,7 +2549,7 @@ static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStr CYTry { NSString *name(CYCastNSString(pool, property)); - NSString *data(CYCastNSObject(pool, context, value)); + NSObject *data(CYCastNSObject(pool, context, value)); CYPoolTry { if ([self cy$setProperty:name to:data]) @@ -2166,15 +2559,17 @@ static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStr const char *string(CYPoolCString(pool, name)); Class _class(object_getClass(self)); +#ifdef __APPLE__ 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); + CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception); return true; } } +#endif size_t length(strlen(string)); @@ -2195,7 +2590,7 @@ static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStr if (SEL sel = sel_getUid(set)) if (CYImplements(self, _class, sel, false)) { JSValueRef arguments[1] = {value}; - CYSendMessage(pool, context, self, sel, 1, arguments, false, exception); + CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception); } if (CYInternal *internal = CYInternal::Set(self)) { @@ -2243,6 +2638,23 @@ static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef } CYCatch } +static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { + Instance *internal(reinterpret_cast(JSObjectGetPrivate((JSObjectRef) constructor))); + Class _class(internal->GetValue()); + if (!CYIsClass(_class)) + return false; + + if (JSValueIsObjectOfClass(context, instance, Instance_)) { + Instance *linternal(reinterpret_cast(JSObjectGetPrivate((JSObjectRef) instance))); + // XXX: this isn't always safe + CYTry { + return [linternal->GetValue() isKindOfClass:_class]; + } CYCatch + } + + return false; +} + static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) { Internal *internal(reinterpret_cast(JSObjectGetPrivate(object))); CYPool pool; @@ -2314,10 +2726,11 @@ static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { Internal *internal(reinterpret_cast(JSObjectGetPrivate(object))); - return internal->owner_; + return internal->GetOwner(); } +#endif -bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) { +static 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) @@ -2369,7 +2782,7 @@ static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, siz uint8_t *base(reinterpret_cast(internal->value_)); base += ffi->size * index; - JSObjectRef owner(internal->owner_ ?: object); + JSObjectRef owner(internal->GetOwner() ?: object); CYTry { return CYFromFFI(context, typical->type_, ffi, base, false, owner); @@ -2443,12 +2856,12 @@ static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, J ssize_t index; uint8_t *base; - if (!Index_(pool, internal, property, index, base)) - return NULL; + CYTry { + if (!Index_(pool, internal, property, index, base)) + return NULL; - JSObjectRef owner(internal->owner_ ?: object); + JSObjectRef owner(internal->GetOwner() ?: object); - CYTry { return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner); } CYCatch } @@ -2461,10 +2874,10 @@ static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStrin ssize_t index; uint8_t *base; - if (!Index_(pool, internal, property, index, base)) - return false; - CYTry { + if (!Index_(pool, internal, property, index, base)) + return false; + CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value); return true; } CYCatch @@ -2499,7 +2912,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[], 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]; + _throw(NSInvalidArgumentException, "incorrect number of arguments to ffi function"); size_t size(setups + count); void *values[size]; @@ -2632,6 +3045,16 @@ static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObject free(data); } +static JSObjectRef CYMakeType(JSContextRef context, const char *type) { + Type_privateData *internal(new Type_privateData(NULL, type)); + return JSObjectMake(context, Type_privateData::Class_, internal); +} + +static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) { + Type_privateData *internal(new Type_privateData(type)); + return JSObjectMake(context, Type_privateData::Class_, internal); +} + static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { if (JSStringIsEqualToUTF8CString(property, "nil")) return Instance::Make(context, nil); @@ -2655,49 +3078,64 @@ static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif); return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]); } + if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name]) + switch ([[entry objectAtIndex:0] intValue]) { + // XXX: implement case 0 + case 1: + return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1])); + } return NULL; } CYCatch } -bool stret(ffi_type *ffi_type) { +#ifdef __OBJC__ +static bool stret(ffi_type *ffi_type) { return ffi_type->type == FFI_TYPE_STRUCT && ( ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE || struct_forward_array[ffi_type->size] != 0 ); } +#endif extern "C" { int *_NSGetArgc(void); char ***_NSGetArgv(void); - int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName); } static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry { - NSLog(@"%s", CYCastCString(context, arguments[0])); + if (count == 0) + printf("\n"); + else + printf("%s\n", CYCastCString(context, arguments[0])); return CYJSUndefined(context); } CYCatch } -JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) { +JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class _class, 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)) + if (_class == NULL) + _class = object_getClass(self); + + if (objc_method *method = class_getInstanceMethod(_class, _cmd)) type = method_getTypeEncoding(method); else { 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]; + _throw(NSInvalidArgumentException, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self); type = CYPoolCString(pool, [method _typeString]); } CYPoolCatch(NULL) } CYCatch } + objc_super super = {self, _class}; + void *arg0 = &super; + void *setup[2]; - setup[0] = &self; + setup[0] = &arg0; setup[1] = &_cmd; sig::Signature signature; @@ -2706,7 +3144,7 @@ JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _c ffi_cif cif; sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif); - void (*function)() = stret(cif.rtype) ? reinterpret_cast(&objc_msgSend_stret) : reinterpret_cast(&objc_msgSend); + void (*function)() = stret(cif.rtype) ? reinterpret_cast(&objc_msgSendSuper_stret) : reinterpret_cast(&objc_msgSendSuper); return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function); } @@ -2725,19 +3163,27 @@ static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObje id self; SEL _cmd; + Class _class; CYTry { if (count < 2) - @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil]; + _throw(NSInvalidArgumentException, "too few arguments to objc_msgSend"); - if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) { + if (JSValueIsObjectOfClass(context, arguments[0], Super_)) { + Super *internal(reinterpret_cast(JSObjectGetPrivate((JSObjectRef) arguments[0]))); + self = internal->GetValue(); + _class = internal->class_;; + uninitialized = false; + } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) { Instance *internal(reinterpret_cast(JSObjectGetPrivate((JSObjectRef) arguments[0]))); self = internal->GetValue(); + _class = nil; uninitialized = internal->IsUninitialized(); if (uninitialized) internal->value_ = nil; } else { self = CYCastNSObject(pool, context, arguments[0]); + _class = nil; uninitialized = false; } @@ -2747,9 +3193,13 @@ static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObje _cmd = CYCastSEL(context, arguments[1]); } CYCatch - return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception); + return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception); } +#ifdef __OBJC__ +/* Hook: objc_registerClassPair {{{ */ +// XXX: replace this with associated objects + MSHook(void, CYDealloc, id self, SEL sel) { CYInternal *internal; object_getInstanceVariable(self, "cy$internal_", reinterpret_cast(&internal)); @@ -2771,14 +3221,25 @@ 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]; + _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair"); CYPool pool; - Class _class(CYCastNSObject(pool, context, arguments[0])); + NSObject *value(CYCastNSObject(pool, context, arguments[0])); + if (value == NULL || !CYIsClass(value)) + _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair"); + Class _class((Class) value); $objc_registerClassPair(_class); return CYJSUndefined(context); } CYCatch } +/* }}} */ +#endif + +static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { + JSGarbageCollect(context); + return CYJSUndefined(context); +} +#ifdef __OBJC__ static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { JSValueRef setup[count + 2]; setup[0] = _this; @@ -2800,6 +3261,7 @@ static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef objec return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue()); } +#endif static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYPool pool; @@ -2807,19 +3269,30 @@ static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef objec return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue()); } -JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { +static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { + CYTry { + if (count != 2) + _throw(NSInvalidArgumentException, "incorrect number of arguments to Super constructor"); + CYPool pool; + NSObject *self(CYCastNSObject(pool, context, arguments[0])); + Class _class(CYCastClass(pool, context, arguments[1])); + return Super::Make(context, self, _class); + } CYCatch +} + +static JSObjectRef Selector_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 Selector constructor" userInfo:nil]; + _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector constructor"); const char *name(CYCastCString(context, arguments[0])); return CYMakeSelector(context, sel_registerName(name)); } CYCatch } -JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { +static 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]; + _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor"); void *value(CYCastPointer(context, arguments[0])); const char *type(CYCastCString(context, arguments[1])); @@ -2833,25 +3306,47 @@ 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(NULL, type)); - return JSObjectMake(context, Type_, internal); -} +static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { + CYTry { + if (count != 1) + _throw(NSInvalidArgumentException, "incorrect number of arguments to Type constructor"); + const char *type(CYCastCString(context, arguments[0])); + return CYMakeType(context, type); + } CYCatch +} + +static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { + Type_privateData *internal(reinterpret_cast(JSObjectGetPrivate(object))); + + CYTry { + sig::Type type; + + if (JSStringIsEqualToUTF8CString(property, "$cyi")) { + type.primitive = sig::pointer_P; + type.data.data.size = 0; + } else { + size_t index(CYGetIndex(NULL, property)); + if (index == _not(size_t)) + return NULL; + type.primitive = sig::array_P; + type.data.data.size = index; + } + + type.name = NULL; + type.flags = 0; + + type.data.data.type = internal->type_; -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); + return CYMakeType(context, &type); } CYCatch } static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { + Type_privateData *internal(reinterpret_cast(JSObjectGetPrivate(object))); + CYTry { if (count != 1) - @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil]; - Type_privateData *internal(reinterpret_cast(JSObjectGetPrivate(object))); + _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function"); sig::Type *type(internal->type_); ffi_type *ffi(internal->GetFFI()); // XXX: alignment? @@ -2864,35 +3359,46 @@ static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, 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]; + if (count != 0) + _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function"); Type_privateData *internal(reinterpret_cast(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); + + sig::Type *type(internal->type_); + size_t size; + + if (type->primitive != sig::array_P) + size = 0; + else { + size = type->data.data.size; + type = type->data.data.type; + } + + void *value(malloc(internal->GetFFI()->size)); + return CYMakePointer(context, value, type, NULL, NULL); } CYCatch } -JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { +#ifdef __OBJC__ +static JSObjectRef Instance_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 Instance constructor" userInfo:nil]; + _throw(NSInvalidArgumentException, "incorrect number of arguments to Instance constructor"); id self(count == 0 ? nil : CYCastPointer(context, arguments[0])); return Instance::Make(context, self); } CYCatch } +#endif -JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { +static JSObjectRef Functor_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]; + _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor"); const char *type(CYCastCString(context, arguments[1])); return CYMakeFunctor(context, arguments[0], type); } CYCatch } -JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { +static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYValue *internal(reinterpret_cast(JSObjectGetPrivate(object))); return CYCastJSValue(context, reinterpret_cast(internal->value_)); } @@ -2937,42 +3443,62 @@ static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRe } CYCatch } +#ifdef __OBJC__ static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { Instance *internal(reinterpret_cast(JSObjectGetPrivate(object))); return Instance::Make(context, object_getClass(internal->GetValue())); } -static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { +static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { + Instance *internal(reinterpret_cast(JSObjectGetPrivate(object))); + id self(internal->GetValue()); + if (!CYIsClass(self)) + return CYJSUndefined(context); + CYTry { + return CYGetClassPrototype(context, self); + } CYCatch +} + +static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { Instance *internal(reinterpret_cast(JSObjectGetPrivate(object))); id self(internal->GetValue()); - // XXX: this is a lame object_isClass if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL) return CYJSUndefined(context); - return Prototype::Make(context, self); + return Messages::Make(context, self); } static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { + if (!JSValueIsObjectOfClass(context, _this, Instance_)) + return NULL; + Instance *internal(reinterpret_cast(JSObjectGetPrivate(_this))); CYTry { CYPoolTry { - return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue()))); + return CYCastJSValue(context, CYJSString(CYCastNSCYON(internal->GetValue()))); } CYPoolCatch(NULL) } CYCatch } static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { + if (!JSValueIsObjectOfClass(context, _this, Instance_)) + return NULL; + Instance *internal(reinterpret_cast(JSObjectGetPrivate(_this))); CYTry { CYPoolTry { NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0]))); + // XXX: check for support of cy$toJSON? 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) { + if (!JSValueIsObjectOfClass(context, _this, Instance_)) + return NULL; + Instance *internal(reinterpret_cast(JSObjectGetPrivate(_this))); CYTry { @@ -3008,25 +3534,28 @@ 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 != 1) - @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil]; + _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector.type"); CYPool pool; Selector_privateData *internal(reinterpret_cast(JSObjectGetPrivate(_this))); - Class _class(CYCastNSObject(pool, context, arguments[0])); - SEL sel(internal->GetValue()); - Method method(class_getInstanceMethod(_class, sel)); - const char *type(CYPoolTypeEncoding(pool, _class, sel, method)); - return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type)); + if (Class _class = CYCastClass(pool, context, arguments[0])) { + SEL sel(internal->GetValue()); + if (objc_method *method = class_getInstanceMethod(_class, sel)) + if (const char *type = CYPoolTypeEncoding(pool, _class, sel, method)) + return CYCastJSValue(context, CYJSString(type)); + } + + // XXX: do a lookup of some kind + return CYJSNull(context); } CYCatch } +#endif 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(JSObjectGetPrivate(_this))); CYPool pool; const char *type(sig::Unparse(pool, internal->type_)); - CYPoolTry { - return CYCastJSValue(context, CYJSString(type)); - } CYPoolCatch(NULL) + return CYCastJSValue(context, CYJSString(type)); } CYCatch } @@ -3035,9 +3564,14 @@ static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef o Type_privateData *internal(reinterpret_cast(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) + size_t size(strlen(type)); + char *cyon(new(pool) char[12 + size + 1]); + memcpy(cyon, "new Type(\"", 10); + cyon[12 + size] = '\0'; + cyon[12 + size - 2] = '"'; + cyon[12 + size - 1] = ')'; + memcpy(cyon + 10, type, size); + return CYCastJSValue(context, CYJSString(cyon)); } CYCatch } @@ -3074,9 +3608,11 @@ static JSStaticFunction Functor_staticFunctions[4] = { {NULL, NULL, 0} }; -static JSStaticValue Instance_staticValues[4] = { +#ifdef __OBJC__ +static JSStaticValue Instance_staticValues[5] = { {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, - {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, + {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, + {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, {NULL, NULL, NULL, 0} }; @@ -3101,6 +3637,7 @@ static JSStaticFunction Selector_staticFunctions[5] = { {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, {NULL, NULL, 0} }; +#endif static JSStaticFunction Type_staticFunctions[4] = { {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, @@ -3109,28 +3646,6 @@ static JSStaticFunction Type_staticFunctions[4] = { {NULL, NULL, 0} }; -CYDriver::CYDriver(const std::string &filename) : - state_(CYClear), - data_(NULL), - size_(0), - file_(NULL), - filename_(filename), - source_(NULL) -{ - ScannerInit(); -} - -CYDriver::~CYDriver() { - ScannerDestroy(); -} - -void cy::parser::error(const cy::parser::location_type &location, const std::string &message) { - CYDriver::Error error; - error.location_ = location; - error.message_ = message; - driver.errors_.push_back(error); -} - void CYSetArgs(int argc, const char *argv[]) { JSContextRef context(CYGetJSContext()); JSValueRef args[argc]; @@ -3164,7 +3679,14 @@ const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled if (JSValueIsUndefined(context, result)) return NULL; - const char *json(CYPoolCCYON(pool, context, result, &exception)); + const char *json; + + try { + json = CYPoolCCYON(pool, context, result, &exception); + } catch (const char *error) { + return error; + } + if (exception != NULL) goto error; @@ -3172,137 +3694,33 @@ const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled 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; -} - -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([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(data)); - client->Handle(); - delete client; - return NULL; -} +static apr_pool_t *Pool_; -extern "C" void CYHandleClient(apr_pool_t *pool, int socket) { - CYClient *client(new(pool) CYClient(socket)); - apr_threadattr_t *attr; - _aprcall(apr_threadattr_create(&attr, client->pool_)); - _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_)); +apr_pool_t *CYGetGlobalPool() { + return Pool_; } MSInitialize { _pooled _aprcall(apr_initialize()); _aprcall(apr_pool_create(&Pool_, NULL)); + Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain]; + +#ifdef __OBJC__ Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@"); Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":"); - Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain]; - - NSArray_ = objc_getClass("NSArray"); +#ifdef __APPLE__ NSCFBoolean_ = objc_getClass("NSCFBoolean"); NSCFType_ = objc_getClass("NSCFType"); +#endif + + NSArray_ = objc_getClass("NSArray"); + NSDictionary_ = objc_getClass("NSDictonary"); NSMessageBuilder_ = objc_getClass("NSMessageBuilder"); NSZombie_ = objc_getClass("_NSZombie_"); Object_ = objc_getClass("Object"); +#endif } JSGlobalContextRef CYGetJSContext() { @@ -3316,36 +3734,6 @@ JSGlobalContextRef CYGetJSContext() { definition.finalize = &Finalize; Functor_ = JSClassCreate(&definition); - definition = kJSClassDefinitionEmpty; - definition.className = "Instance"; - definition.staticValues = Instance_staticValues; - definition.staticFunctions = Instance_staticFunctions; - definition.hasProperty = &Instance_hasProperty; - definition.getProperty = &Instance_getProperty; - definition.setProperty = &Instance_setProperty; - definition.deleteProperty = &Instance_deleteProperty; - definition.getPropertyNames = &Instance_getPropertyNames; - definition.callAsConstructor = &Instance_callAsConstructor; - definition.finalize = &Finalize; - Instance_ = JSClassCreate(&definition); - - definition = kJSClassDefinitionEmpty; - definition.className = "Internal"; - definition.staticFunctions = Internal_staticFunctions; - definition.hasProperty = &Internal_hasProperty; - definition.getProperty = &Internal_getProperty; - definition.setProperty = &Internal_setProperty; - definition.getPropertyNames = &Internal_getPropertyNames; - definition.finalize = &Finalize; - Internal_ = JSClassCreate(&definition); - - definition = kJSClassDefinitionEmpty; - definition.className = "Message"; - definition.staticFunctions = Functor_staticFunctions; - definition.callAsFunction = &Message_callAsFunction; - definition.finalize = &Finalize; - Message_ = JSClassCreate(&definition); - definition = kJSClassDefinitionEmpty; definition.className = "Pointer"; definition.staticValues = Pointer_staticValues; @@ -3355,18 +3743,6 @@ JSGlobalContextRef CYGetJSContext() { definition.finalize = &Finalize; Pointer_ = JSClassCreate(&definition); - definition = kJSClassDefinitionEmpty; - definition.className = "Prototype"; - definition.hasProperty = &Prototype_hasProperty; - definition.getProperty = &Prototype_getProperty; - definition.setProperty = &Prototype_setProperty; -#if !__OBJC2__ - definition.deleteProperty = &Prototype_deleteProperty; -#endif - definition.getPropertyNames = &Prototype_getPropertyNames; - definition.finalize = &Finalize; - Prototype_ = JSClassCreate(&definition); - definition = kJSClassDefinitionEmpty; definition.className = "Selector"; definition.staticValues = CYValue_staticValues; @@ -3387,17 +3763,112 @@ JSGlobalContextRef CYGetJSContext() { definition = kJSClassDefinitionEmpty; definition.className = "Type"; definition.staticFunctions = Type_staticFunctions; - //definition.getProperty = &Type_getProperty; + definition.getProperty = &Type_getProperty; definition.callAsFunction = &Type_callAsFunction; definition.callAsConstructor = &Type_callAsConstructor; definition.finalize = &Finalize; - Type_ = JSClassCreate(&definition); + Type_privateData::Class_ = 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)); + + Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))); + JSValueProtect(context, Array_); + + Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))); + JSValueProtect(context, Function_); + + String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String"))); + JSValueProtect(context, String_); + + length_ = JSStringCreateWithUTF8CString("length"); + message_ = JSStringCreateWithUTF8CString("message"); + name_ = JSStringCreateWithUTF8CString("name"); + prototype_ = JSStringCreateWithUTF8CString("prototype"); + toCYON_ = JSStringCreateWithUTF8CString("toCYON"); + toJSON_ = JSStringCreateWithUTF8CString("toJSON"); + + JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object")))); + Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_)); + JSValueProtect(context, Object_prototype_); + + Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_)); + Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop"))); + Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push"))); + Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice"))); + + JSValueProtect(context, Array_prototype_); + JSValueProtect(context, Array_pop_); + JSValueProtect(context, Array_push_); + JSValueProtect(context, Array_splice_); + + JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new)); + + JSValueRef function(CYGetProperty(context, Function_, prototype_)); + +/* Objective-C Classes {{{ */ +#ifdef __OBJC__ + definition = kJSClassDefinitionEmpty; + definition.className = "Instance"; + definition.staticValues = Instance_staticValues; + definition.staticFunctions = Instance_staticFunctions; + definition.hasProperty = &Instance_hasProperty; + definition.getProperty = &Instance_getProperty; + definition.setProperty = &Instance_setProperty; + definition.deleteProperty = &Instance_deleteProperty; + definition.getPropertyNames = &Instance_getPropertyNames; + definition.callAsConstructor = &Instance_callAsConstructor; + definition.hasInstance = &Instance_hasInstance; + definition.finalize = &Finalize; + Instance_ = JSClassCreate(&definition); + + definition = kJSClassDefinitionEmpty; + definition.className = "Internal"; + definition.staticFunctions = Internal_staticFunctions; + definition.hasProperty = &Internal_hasProperty; + definition.getProperty = &Internal_getProperty; + definition.setProperty = &Internal_setProperty; + definition.getPropertyNames = &Internal_getPropertyNames; + definition.finalize = &Finalize; + Internal_ = JSClassCreate(&definition); + + definition = kJSClassDefinitionEmpty; + definition.className = "Message"; + definition.staticFunctions = Functor_staticFunctions; + definition.callAsFunction = &Message_callAsFunction; + definition.finalize = &Finalize; + Message_ = JSClassCreate(&definition); + + definition = kJSClassDefinitionEmpty; + definition.className = "Messages"; + definition.hasProperty = &Messages_hasProperty; + definition.getProperty = &Messages_getProperty; + definition.setProperty = &Messages_setProperty; +#if !__OBJC2__ + definition.deleteProperty = &Messages_deleteProperty; +#endif + definition.getPropertyNames = &Messages_getPropertyNames; + definition.finalize = &Finalize; + Messages_ = JSClassCreate(&definition); + + definition = kJSClassDefinitionEmpty; + definition.className = "Super"; + definition.staticFunctions = Internal_staticFunctions; + definition.finalize = &Finalize; + Super_ = JSClassCreate(&definition); + definition = kJSClassDefinitionEmpty; definition.className = "ObjectiveC::Classes"; definition.getProperty = &ObjectiveC_Classes_getProperty; @@ -3414,7 +3885,6 @@ JSGlobalContextRef CYGetJSContext() { definition.className = "ObjectiveC::Image::Classes"; definition.getProperty = &ObjectiveC_Image_Classes_getProperty; definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames; - definition.finalize = &Finalize; ObjectiveC_Image_Classes_ = JSClassCreate(&definition); definition = kJSClassDefinitionEmpty; @@ -3423,62 +3893,56 @@ JSGlobalContextRef CYGetJSContext() { 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_); + JSObjectRef 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, 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)); - Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))); - Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))); + JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new)); + JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL)); + JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new)); + JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new)); - length_ = JSStringCreateWithUTF8CString("length"); - message_ = JSStringCreateWithUTF8CString("message"); - name_ = JSStringCreateWithUTF8CString("name"); - prototype_ = JSStringCreateWithUTF8CString("prototype"); - toCYON_ = JSStringCreateWithUTF8CString("toCYON"); - toJSON_ = JSStringCreateWithUTF8CString("toJSON"); + Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_); + JSValueProtect(context, Instance_prototype_); - Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_)); - Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop"))); - Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push"))); - Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice"))); + CYSetProperty(context, global, CYJSString("Instance"), Instance); + CYSetProperty(context, global, CYJSString("Selector"), Selector); + CYSetProperty(context, global, CYJSString("Super"), Super); - JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new)); - JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL)); - JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new)); + 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)); - JSValueRef function(CYGetProperty(context, Function_, prototype_)); JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function); - JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function); JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function); +#endif +/* }}} */ + + JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function); CYSetProperty(context, global, CYJSString("Functor"), Functor); - CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, &Instance_new)); CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new)); - CYSetProperty(context, global, CYJSString("Selector"), Selector); - CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new)); + CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new)); MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair)); +#ifdef __OBJC__ +#ifdef __APPLE__ class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast(&NSCFType$cy$toJSON), "@12@0:4@8"); +#endif +#endif + + JSObjectRef cycript(JSObjectMake(context, NULL, NULL)); + CYSetProperty(context, global, CYJSString("Cycript"), cycript); + CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction)); - 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)); CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq)); System_ = JSObjectMake(context, NULL, NULL); + JSValueProtect(context, System_); + CYSetProperty(context, global, CYJSString("system"), System_); CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context)); //CYSetProperty(context, System_, CYJSString("global"), global);