X-Git-Url: https://git.saurik.com/cycript.git/blobdiff_plain/8a199b13bf5ee472fbf9338eab33db123b81c10f..7d6921fe1c9d8408380476915e84f6216d90ee08:/Library.mm diff --git a/Library.mm b/Library.mm index 85638f5..973f441 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,9 +37,9 @@ */ /* }}} */ -#define _GNU_SOURCE - #include +#include + #include "cycript.hpp" #include "sig/parse.hpp" @@ -48,10 +48,14 @@ #include "Pooling.hpp" #include "Struct.hpp" +#ifdef __APPLE__ #include #include - +#include #include +#endif + +#include #include @@ -66,7 +70,7 @@ #include "Parser.hpp" #include "Cycript.tab.hh" -#include +#include #undef _assert #undef _trace @@ -77,7 +81,7 @@ } while (false) #define _trace() do { \ - CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \ + fprintf(stderr, "_trace():%u\n", __LINE__); \ } while (false) #define CYPoolTry { \ @@ -96,6 +100,198 @@ } \ } +#ifndef __APPLE__ +#define class_getSuperclass GSObjCSuper +#define object_getClass GSObjCClass +#endif + +void CYThrow(JSContextRef context, JSValueRef value); + +const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception); +JSStringRef CYCopyJSString(const char *value); + +void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value); + +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)()); +JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception); + +/* 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; \ +}) +/* }}} */ +/* 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 [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil]; + 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); +} + +#ifdef __APPLE__ +CFStringRef CYCopyCFString(JSStringRef value) { + return JSStringCopyCFString(kCFAllocatorDefault, value); +} + +CFStringRef CYCopyCFString(const char *value) { + return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8); +} + +template +NSString *CYCopyNSString(Type_ value) { + return (NSString *) CYCopyCFString(value); +} +#else +NSString *CYCopyNSString(const char *value) { + return [NSString stringWithUTF8String:value]; +} + +NSString *CYCopyNSString(JSStringRef value) { + return CYCopyNSString(CYCastCString_(value)); +} +#endif + +NSString *CYCopyNSString(JSContextRef context, JSValueRef value) { + return CYCopyNSString(CYJSString(context, value)); +} +/* }}} */ + static JSGlobalContextRef Context_; static JSObjectRef System_; static JSObjectRef ObjectiveC_; @@ -103,11 +299,13 @@ static JSObjectRef ObjectiveC_; static JSClassRef Functor_; static JSClassRef Instance_; static JSClassRef Internal_; +static JSClassRef Message_; +static JSClassRef Messages_; +static JSClassRef NSArrayPrototype_; static JSClassRef Pointer_; static JSClassRef Runtime_; static JSClassRef Selector_; static JSClassRef Struct_; -static JSClassRef Type_; static JSClassRef ObjectiveC_Classes_; static JSClassRef ObjectiveC_Image_Classes_; @@ -116,17 +314,32 @@ static JSClassRef ObjectiveC_Protocols_; static JSObjectRef Array_; static JSObjectRef Function_; +static JSObjectRef String_; static JSStringRef Result_; static JSStringRef length_; static JSStringRef message_; static JSStringRef name_; +static JSStringRef prototype_; static JSStringRef toCYON_; static JSStringRef toJSON_; +static JSObjectRef Instance_prototype_; +static JSObjectRef Object_prototype_; + +static JSObjectRef Array_prototype_; +static JSObjectRef Array_pop_; +static JSObjectRef Array_push_; +static JSObjectRef Array_splice_; + +#ifdef __APPLE__ static Class NSCFBoolean_; static Class NSCFType_; +#endif + +static Class NSArray_; +static Class NSDictionary_; static Class NSMessageBuilder_; static Class NSZombie_; static Class Object_; @@ -147,8 +360,8 @@ struct CYValue : CYValue() { } - CYValue(void *value) : - value_(value) + CYValue(const void *value) : + value_(const_cast(value)) { } @@ -177,6 +390,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 { @@ -197,11 +441,14 @@ 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) { - return JSObjectMake(context, Instance_, new Instance(object, flags)); + static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) { + JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags))); + JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object))); + return value; } id GetValue() const { @@ -215,19 +462,65 @@ struct Instance : virtual Type_privateData *GetType() const; }; -struct Internal : +struct Messages : + CYValue +{ + Messages(Class value) : + CYValue(value) + { + } + + static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) { + JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class))); + if (_class == NSArray_) + array = true; + if (Class super = class_getSuperclass(_class)) + JSObjectSetPrototype(context, value, Messages::Make(context, super, array)); + /*else if (array) + JSObjectSetPrototype(context, value, Array_prototype_);*/ + return value; + } + + Class GetValue() const { + return reinterpret_cast(value_); + } +}; + +struct CYOwned : CYValue { + private: + JSContextRef context_; JSObjectRef owner_; - Internal(id value, JSObjectRef owner) : + public: + CYOwned(void *value, JSContextRef context, JSObjectRef owner) : CYValue(value), + context_(context), owner_(owner) + { + JSValueProtect(context_, owner_); + } + + virtual ~CYOwned() { + JSValueUnprotect(context_, owner_); + } + + JSObjectRef GetOwner() const { + return owner_; + } +}; + +struct Internal : + CYOwned +{ + 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 { @@ -266,9 +559,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; @@ -334,6 +632,8 @@ struct Type_privateData : static Type_privateData *Object; static Type_privateData *Selector; + static JSClassRef Class_; + ffi_type *ffi_; sig::Type *type_; @@ -388,6 +688,7 @@ struct Type_privateData : } }; +JSClassRef Type_privateData::Class_; Type_privateData *Type_privateData::Object; Type_privateData *Type_privateData::Selector; @@ -400,27 +701,24 @@ Type_privateData *Selector_privateData::GetType() const { } 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) { } }; @@ -429,7 +727,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; @@ -452,22 +750,46 @@ struct Functor_privateData : sig::Signature signature_; ffi_cif cif_; + Functor_privateData(const char *type, void (*value)()) : CYValue(reinterpret_cast(value)) { sig::Parse(pool_, &signature_, type, &Structor_); sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_); } + + void (*GetValue())() const { + return reinterpret_cast(value_); + } }; -struct ffoData : +struct Closure_privateData : Functor_privateData { JSContextRef context_; JSObjectRef function_; - ffoData(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_); + } +}; + +struct Message_privateData : + Functor_privateData +{ + SEL sel_; + + Message_privateData(SEL sel, const char *type, IMP value = NULL) : + Functor_privateData(type, reinterpret_cast(value)), + sel_(sel) { } }; @@ -485,18 +807,6 @@ 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; - } -} - JSValueRef CYCastJSValue(JSContextRef context, bool value) { return JSValueMakeBoolean(context, value); } @@ -521,7 +831,29 @@ JSValueRef CYJSUndefined(JSContextRef context) { return JSValueMakeUndefined(context); } -bool CYGetIndex(const char *value, ssize_t &index) { +size_t CYGetIndex(const char *value) { + if (value[0] != '0') { + char *end; + size_t index(strtoul(value, &end, 10)); + if (value + strlen(value) == end) + return index; + } else if (value[1] == '\0') + return 0; + return _not(size_t); +} + +// XXX: fix this +static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value); + +size_t CYGetIndex(apr_pool_t *pool, NSString *value) { + return CYGetIndex(CYPoolCString(pool, value)); +} + +size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) { + return CYGetIndex(CYPoolCString(pool, value)); +} + +bool CYGetOffset(const char *value, ssize_t &index) { if (value[0] != '0') { char *end; index = strtol(value, &end, 10); @@ -535,8 +867,8 @@ bool CYGetIndex(const char *value, ssize_t &index) { return false; } -bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) { - return CYGetIndex(CYPoolCString(pool, value), index); +bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) { + return CYGetOffset(CYPoolCString(pool, value), index); } NSString *CYPoolNSCYON(apr_pool_t *pool, id value); @@ -569,6 +901,7 @@ NSString *CYPoolNSCYON(apr_pool_t *pool, id value); - (void *) cy$symbol; @end +#ifdef __APPLE__ struct PropertyAttributes { CYPool pool_; @@ -654,99 +987,35 @@ struct PropertyAttributes { } }; +#endif -@implementation NSProxy (Cycript) - -- (NSObject *) cy$toJSON:(NSString *)key { - return [self description]; +#ifdef __APPLE__ +NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { + return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]; } +#endif -- (NSString *) cy$toCYON { - return [[self cy$toJSON:@""] cy$toCYON]; +#ifndef __APPLE__ +@interface CYWebUndefined : NSObject { } ++ (CYWebUndefined *) undefined; + @end -@implementation NSObject (Cycript) +@implementation CYWebUndefined -- (JSValueRef) cy$JSValueInContext:(JSContextRef)context { - return CYMakeInstance(context, self, false); ++ (CYWebUndefined *) undefined { + static CYWebUndefined *instance_([[CYWebUndefined alloc] init]); + return instance_; } -- (JSType) cy$JSType { - return kJSTypeObject; -} +@end -- (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) { - return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]; -} - -@implementation WebUndefined (Cycript) - -- (JSType) cy$JSType { - return kJSTypeUndefined; -} - -- (NSObject *) cy$toJSON:(NSString *)key { - return self; -} - -- (NSString *) cy$toCYON { - return @"undefined"; -} - -- (JSValueRef) cy$JSValueInContext:(JSContextRef)context { - return CYJSUndefined(context); -} - -@end - -@implementation NSNull (Cycript) - -- (JSType) cy$JSType { - return kJSTypeNull; -} - -- (NSObject *) cy$toJSON:(NSString *)key { - return self; -} - -- (NSString *) cy$toCYON { - return @"null"; -} - -@end +#define WebUndefined CYWebUndefined +#endif +/* Bridge: NSArray {{{ */ @implementation NSArray (Cycript) - (NSString *) cy$toCYON { @@ -754,7 +1023,13 @@ 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 @@ -775,50 +1050,33 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { if ([name isEqualToString:@"length"]) return true; - ssize_t index; - if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast([self count])) + size_t index(CYGetIndex(NULL, name)); + if (index == _not(size_t) || index >= [self count]) return [super cy$hasProperty:name]; else return true; } - (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 + } - ssize_t index; - if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast([self count])) + size_t index(CYGetIndex(NULL, name)); + if (index == _not(size_t) || index >= [self count]) return [super cy$getProperty:name]; else return [self objectAtIndex:index]; } @end - -@implementation NSMutableArray (Cycript) - -- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value { - ssize_t index; - if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast([self count])) - return [super cy$setProperty:name to:value]; - else { - [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])]; - return true; - } -} - -- (bool) cy$deleteProperty:(NSString *)name { - ssize_t index; - if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast([self count])) - return [super cy$deleteProperty:name]; - else { - [self removeObjectAtIndex:index]; - return true; - } -} - -@end - +/* }}} */ +/* Bridge: NSDictionary {{{ */ @implementation NSDictionary (Cycript) - (NSString *) cy$toCYON { @@ -826,7 +1084,12 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { [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 @@ -850,7 +1113,63 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { } @end +/* }}} */ +/* Bridge: NSMutableArray {{{ */ +@implementation NSMutableArray (Cycript) +- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value { + if ([name isEqualToString:@"length"]) { + // XXX: is this not intelligent? + 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)]; + else if (size != count) { + WebUndefined *undefined([WebUndefined undefined]); + for (size_t i(count); i != size; ++i) + [self addObject:undefined]; + } + return true; + } + + size_t index(CYGetIndex(NULL, name)); + if (index == _not(size_t)) + return [super cy$setProperty:name to:value]; + + id object(value ?: [NSNull null]); + + size_t count([self count]); + if (index < count) + [self replaceObjectAtIndex:index withObject:object]; + else { + if (index != count) { + WebUndefined *undefined([WebUndefined undefined]); + for (size_t i(count); i != index; ++i) + [self addObject:undefined]; + } + + [self addObject:object]; + } + + return true; +} + +- (bool) cy$deleteProperty:(NSString *)name { + size_t index(CYGetIndex(NULL, name)); + if (index == _not(size_t) || index >= [self count]) + return [super cy$deleteProperty:name]; + [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]]; + return true; +} + +@end +/* }}} */ +/* Bridge: NSMutableDictionary {{{ */ @implementation NSMutableDictionary (Cycript) - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value { @@ -868,12 +1187,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 { @@ -889,7 +1213,79 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { } @end +/* }}} */ +/* Bridge: NSNull {{{ */ +@implementation NSNull (Cycript) + +- (JSType) cy$JSType { + return kJSTypeNull; +} + +- (NSObject *) cy$toJSON:(NSString *)key { + return self; +} + +- (NSString *) cy$toCYON { + 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) - (JSType) cy$JSType { @@ -902,18 +1298,19 @@ 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)); - 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); + NSMutableString *json([self mutableCopy]); + + [json replaceOccurrencesOfString:@"\\" withString:@"\\\\" options:NSLiteralSearch range:NSMakeRange(0, [json length])]; + [json replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:NSLiteralSearch range:NSMakeRange(0, [json length])]; + [json replaceOccurrencesOfString:@"\t" withString:@"\\t" options:NSLiteralSearch range:NSMakeRange(0, [json length])]; + [json replaceOccurrencesOfString:@"\r" withString:@"\\r" options:NSLiteralSearch range:NSMakeRange(0, [json length])]; + [json replaceOccurrencesOfString:@"\n" withString:@"\\n" options:NSLiteralSearch range:NSMakeRange(0, [json length])]; - CFStringInsert(json, 0, CFSTR("\"")); - CFStringAppend(json, CFSTR("\"")); + [json appendString:@"\""]; + [json insertString:@"\"" atIndex:0]; - return [reinterpret_cast(json) autorelease]; + return json; } - (NSString *) cy$toKey { @@ -924,8 +1321,8 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { goto cyon; if (DigitRange_[value[0]]) { - ssize_t index; - if (!CYGetIndex(NULL, self, index) || index < 0) + size_t index(CYGetIndex(NULL, self)); + if (index == _not(size_t)) goto cyon; } else { if (!WordStartRange_[value[0]]) @@ -947,15 +1344,38 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { } @end +/* }}} */ +/* Bridge: WebUndefined {{{ */ +@implementation WebUndefined (Cycript) -@interface CYJSObject : NSDictionary { +- (JSType) cy$JSType { + return kJSTypeUndefined; +} + +- (NSObject *) cy$toJSON:(NSString *)key { + return self; +} + +- (NSString *) cy$toCYON { + return @"undefined"; +} + +- (JSValueRef) cy$JSValueInContext:(JSContextRef)context { + return CYJSUndefined(context); +} + +@end +/* }}} */ + +/* Bridge: CYJSObject {{{ */ +@interface CYJSObject : NSMutableDictionary { JSObjectRef object_; JSContextRef context_; } - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context; -- (NSString *) cy$toJSON:(NSString *)key; +- (NSObject *) cy$toJSON:(NSString *)key; - (NSUInteger) count; - (id) objectForKey:(id)key; @@ -964,8 +1384,9 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { - (void) removeObjectForKey:(id)key; @end - -@interface CYJSArray : NSArray { +/* }}} */ +/* Bridge: CYJSArray {{{ */ +@interface CYJSArray : NSMutableArray { JSObjectRef object_; JSContextRef context_; } @@ -975,11 +1396,14 @@ NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) { - (NSUInteger) count; - (id) objectAtIndex:(NSUInteger)index; -@end +- (void) addObject:(id)anObject; +- (void) insertObject:(id)anObject atIndex:(NSUInteger)index; +- (void) removeLastObject; +- (void) removeObjectAtIndex:(NSUInteger)index; +- (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject; -CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9 -CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$ -CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9 +@end +/* }}} */ #define CYTry \ @try @@ -989,15 +1413,13 @@ CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$ 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) { +id CYPoolRelease_(apr_pool_t *pool, id object) { if (object == nil) return nil; else if (pool == NULL) @@ -1008,11 +1430,12 @@ id CYPoolRelease(apr_pool_t *pool, id object) { } } -CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) { - return (CFTypeRef) CYPoolRelease(pool, (id) object); +template +Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) { + return (Type_) CYPoolRelease_(pool, (id) object); } -id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) { +NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) { JSValueRef exception(NULL); bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception)); CYThrow(context, exception); @@ -1020,91 +1443,15 @@ id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) { return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]); } -id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) { +NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) { if (!JSValueIsObjectOfClass(context, object, Instance_)) return CYCastNSObject_(pool, context, object); else { - Instance *data(reinterpret_cast(JSObjectGetPrivate(object))); - return data->GetValue(); + 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_)) - { - } - - 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_; - } -}; - -CFStringRef CYCopyCFString(JSStringRef value) { - return JSStringCopyCFString(kCFAllocatorDefault, value); -} - -CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) { - return CYCopyCFString(CYJSString(context, value)); -} - double CYCastDouble(const char *value, size_t size) { char *end; double number(strtod(value, &end)); @@ -1124,29 +1471,21 @@ 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)); +NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) { + return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)]; } -NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) { - return (NSString *) CYPoolRelease(pool, CYCopyCFString(value)); +template +NSString *CYCastNSString(apr_pool_t *pool, Type_ value) { + return CYPoolRelease(pool, CYCopyNSString(value)); } bool CYCastBool(JSContextRef context, JSValueRef value) { return JSValueToBoolean(context, value); } -CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) { - CFTypeRef object; +id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) { + id object; bool copy; switch (JSType type = JSValueGetType(context, value)) { @@ -1160,23 +1499,28 @@ 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; @@ -1190,15 +1534,15 @@ 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); } -CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) { - return CYCFType(pool, context, value, false); +id CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) { + return CYNSObject(pool, context, value, false); } NSArray *CYCastNSArray(JSPropertyNameArrayRef names) { @@ -1210,10 +1554,6 @@ NSArray *CYCastNSArray(JSPropertyNameArrayRef names) { return array; } -id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) { - return reinterpret_cast(CYCastCFType(pool, context, value)); -} - void CYThrow(JSContextRef context, JSValueRef value) { if (value == NULL) return; @@ -1248,26 +1588,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, 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; @@ -1292,9 +1612,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]; +} + - (NSObject *) cy$toJSON:(NSString *)key { JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_)); if (!CYIsCallable(context_, toJSON)) @@ -1309,12 +1635,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 { @@ -1325,7 +1650,10 @@ bool CYIsCallable(JSContextRef context, JSValueRef value) { } - (id) objectForKey:(id)key { - return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null]; + JSValueRef value(CYGetProperty(context_, object_, CYJSString(key))); + if (JSValueIsUndefined(context_, value)) + return nil; + return CYCastNSObject(NULL, context_, value) ?: [NSNull null]; } - (NSEnumerator *) keyEnumerator { @@ -1353,20 +1681,75 @@ 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_)); } - (id) objectAtIndex:(NSUInteger)index { + size_t bounds([self count]); + if (index >= bounds) + @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil]; JSValueRef exception(NULL); JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception)); CYThrow(context_, exception); return CYCastNSObject(NULL, context_, value) ?: [NSNull null]; } +- (void) addObject:(id)object { + JSValueRef exception(NULL); + JSValueRef arguments[1]; + arguments[0] = CYCastJSValue(context_, object); + JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception); + CYThrow(context_, exception); +} + +- (void) insertObject:(id)object atIndex:(NSUInteger)index { + size_t bounds([self count] + 1); + if (index >= bounds) + @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil]; + JSValueRef exception(NULL); + JSValueRef arguments[3]; + arguments[0] = CYCastJSValue(context_, index); + arguments[1] = CYCastJSValue(context_, 0); + arguments[2] = CYCastJSValue(context_, object); + JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception); + CYThrow(context_, exception); +} + +- (void) removeLastObject { + JSValueRef exception(NULL); + JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception); + CYThrow(context_, exception); +} + +- (void) removeObjectAtIndex:(NSUInteger)index { + size_t bounds([self count]); + if (index >= bounds) + @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil]; + JSValueRef exception(NULL); + JSValueRef arguments[2]; + arguments[0] = CYCastJSValue(context_, index); + arguments[1] = CYCastJSValue(context_, 1); + JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception); + CYThrow(context_, exception); +} + +- (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { + size_t bounds([self count]); + if (index >= bounds) + @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil]; + CYSetProperty(context_, object_, index, CYCastJSValue(context_, object)); +} + @end NSString *CYCopyNSCYON(id value) { @@ -1378,9 +1761,9 @@ NSString *CYCopyNSCYON(id value) { Class _class(object_getClass(value)); SEL sel(@selector(cy$toCYON)); - if (Method toCYON = class_getInstanceMethod(_class, sel)) + if (objc_method *toCYON = class_getInstanceMethod(_class, sel)) string = reinterpret_cast(method_getImplementation(toCYON))(value, sel); - else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) { + 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; @@ -1484,23 +1867,24 @@ struct CYInternal : } }; -JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) { - Selector_privateData *data(new Selector_privateData(sel)); - return JSObjectMake(context, Selector_, data); +static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) { + Selector_privateData *internal(new Selector_privateData(sel)); + return JSObjectMake(context, Selector_, internal); } -JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) { - Pointer *data(new Pointer(pointer, type, owner)); - return JSObjectMake(context, Pointer_, data); +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) { - Functor_privateData *data(new Functor_privateData(type, function)); - return JSObjectMake(context, Functor_, data); +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) { +static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) { if (pool == NULL) { + // XXX: this could be much more efficient const char *string([CYCastNSString(NULL, value) UTF8String]); return string; } else { @@ -1511,30 +1895,15 @@ const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) { } } -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 CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) { - return CYGetIndex(CYPoolCString(pool, value), 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; @@ -1542,8 +1911,8 @@ void *CYCastPointer_(JSContextRef context, JSValueRef value) { return dlsym(RTLD_DEFAULT, CYCastCString(context, value)); case kJSTypeObject: if (JSValueIsObjectOfClass(context, value, Pointer_)) { - Pointer *data(reinterpret_cast(JSObjectGetPrivate((JSObjectRef) value))); - return data->value_; + Pointer *internal(reinterpret_cast(JSObjectGetPrivate((JSObjectRef) value))); + return internal->value_; }*/ default: double number(CYCastDouble(context, value)); @@ -1554,19 +1923,19 @@ void *CYCastPointer_(JSContextRef context, JSValueRef value) { } 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) { +static SEL CYCastSEL(JSContextRef context, JSValueRef value) { if (JSValueIsObjectOfClass(context, value, Selector_)) { - Selector_privateData *data(reinterpret_cast(JSObjectGetPrivate((JSObjectRef) value))); - return reinterpret_cast(data->value_); + Selector_privateData *internal(reinterpret_cast(JSObjectGetPrivate((JSObjectRef) value))); + return reinterpret_cast(internal->value_); } else return CYCastPointer(context, value); } -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); @@ -1644,7 +2013,7 @@ void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type } } -JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, 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) { @@ -1688,51 +2057,232 @@ JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void else goto null; break; - case sig::pointer_P: - if (void *pointer = *reinterpret_cast(data)) - value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner); - else goto null; - break; + case sig::pointer_P: + if (void *pointer = *reinterpret_cast(data)) + value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner); + else goto null; + break; + + case sig::string_P: + if (char *utf8 = *reinterpret_cast(data)) + value = CYCastJSValue(context, utf8); + else goto null; + break; + + case sig::struct_P: + value = CYMakeStruct(context, data, type, ffi, owner); + break; + + case sig::void_P: + value = CYJSUndefined(context); + break; + + null: + value = CYJSNull(context); + break; + + default: + NSLog(@"CYFromFFI(%c)\n", type->primitive); + _assert(false); + } + + return value; +} + +static bool CYImplements(id object, Class _class, SEL selector, bool devoid) { + if (objc_method *method = class_getInstanceMethod(_class, selector)) { + if (!devoid) + return true; + char type[16]; + method_getReturnType(method, type, sizeof(type)); + if (type[0] != 'v') + return true; + } + + // XXX: possibly use a more "awesome" check? + return false; +} + +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))]) + return CYPoolCString(pool, type); + else + return NULL; +} + +static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) { + Closure_privateData *internal(reinterpret_cast(arg)); + + JSContextRef context(internal->context_); + + size_t count(internal->cif_.nargs); + JSValueRef values[count]; + + for (size_t index(0); index != count; ++index) + values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]); + + JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values)); + CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value); +} + +static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) { + Closure_privateData *internal(reinterpret_cast(arg)); + + JSContextRef context(internal->context_); + + size_t count(internal->cif_.nargs); + JSValueRef values[count]; + + for (size_t index(0); index != count; ++index) + values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]); + + JSObjectRef _this(CYCastJSObject(context, values[0])); + + JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2)); + CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value); +} + +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(CYGetJSContext(), function, type)); + + ffi_closure *closure((ffi_closure *) _syscall(mmap( + NULL, sizeof(ffi_closure), + PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, + -1, 0 + ))); + + ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal)); + _assert(status == FFI_OK); + + _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC)); + + internal->value_ = closure; + + return internal; +} + +static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) { + Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_)); + return JSObjectMake(context, Functor_, internal); +} + +static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) { + JSValueRef exception(NULL); + bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception)); + CYThrow(context, exception); + + if (function) { + JSObjectRef function(CYCastJSObject(context, value)); + return CYMakeFunctor(context, function, type); + } else { + void (*function)()(CYCastPointer(context, value)); + return CYMakeFunctor(context, function, type); + } +} + +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); +} + +static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) { + JSObjectRef function(CYCastJSObject(context, value)); + Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_)); + return reinterpret_cast(internal->GetValue()); +} + +static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) { + 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 (class_getInstanceMethod(_class, sel) != NULL) + return true; + + return false; +} + +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 (objc_method *method = class_getInstanceMethod(_class, sel)) + return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method)); + + return NULL; +} - case sig::string_P: - if (char *utf8 = *reinterpret_cast(data)) - value = CYCastJSValue(context, utf8); - else goto null; - break; +static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { + Messages *internal(reinterpret_cast(JSObjectGetPrivate(object))); + Class _class(internal->GetValue()); - case sig::struct_P: - value = CYMakeStruct(context, data, type, ffi, owner); - break; + CYPool pool; + const char *name(CYPoolCString(pool, property)); - case sig::void_P: - value = CYJSUndefined(context); - break; + SEL sel(sel_registerName(name)); - null: - value = CYJSNull(context); - break; + objc_method *method(class_getInstanceMethod(_class, sel)); - default: - NSLog(@"CYFromFFI(%c)\n", type->primitive); - _assert(false); + const char *type; + IMP imp; + + if (JSValueIsObjectOfClass(context, value, Message_)) { + Message_privateData *message(reinterpret_cast(JSObjectGetPrivate((JSObjectRef) value))); + type = sig::Unparse(pool, &message->signature_); + imp = reinterpret_cast(message->GetValue()); + } else { + type = CYPoolTypeEncoding(pool, _class, sel, method); + imp = CYMakeMessage(context, value, type); } - return value; + if (method != NULL) + method_setImplementation(method, imp); + else + class_replaceMethod(_class, sel, imp, type); + + return true; } -static bool CYImplements(id object, Class _class, SEL selector, bool devoid) { - if (Method method = class_getInstanceMethod(_class, selector)) { - if (!devoid) - return true; - char type[16]; - method_getReturnType(method, type, sizeof(type)); - if (type[0] != 'v') +#if !__OBJC2__ +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 (objc_method *method = class_getInstanceMethod(_class, sel)) { + objc_method_list list = {NULL, 1, {method}}; + class_removeMethods(_class, &list); return true; - } + } - // XXX: possibly use a more "awesome" check? return false; } +#endif + +static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) { + Messages *internal(reinterpret_cast(JSObjectGetPrivate(object))); + Class _class(internal->GetValue()); + + unsigned int 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); +} static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) { Instance *internal(reinterpret_cast(JSObjectGetPrivate(object))); @@ -1748,13 +2298,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; @@ -1789,11 +2342,13 @@ 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); } +#endif if (SEL sel = sel_getUid(string)) if (CYImplements(self, _class, sel, true)) @@ -1804,12 +2359,14 @@ static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, } static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { + Instance *internal(reinterpret_cast(JSObjectGetPrivate(object))); + id self(internal->GetValue()); + CYPool pool; CYTry { - id self(CYCastNSObject(pool, context, object)); 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]) @@ -1819,6 +2376,7 @@ 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()) { @@ -1828,6 +2386,7 @@ static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStr return true; } } +#endif size_t length(strlen(string)); @@ -1861,9 +2420,11 @@ static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStr } static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { + Instance *internal(reinterpret_cast(JSObjectGetPrivate(object))); + id self(internal->GetValue()); + CYTry { CYPoolTry { - id self(CYCastNSObject(NULL, context, object)); NSString *name(CYCastNSString(NULL, property)); return [self cy$deleteProperty:name]; } CYPoolCatch(NULL) @@ -1871,8 +2432,10 @@ static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JS } static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) { + Instance *internal(reinterpret_cast(JSObjectGetPrivate(object))); + id self(internal->GetValue()); + CYPool pool; - NSString *self(CYCastNSObject(pool, context, object)); Class _class(object_getClass(self)); { @@ -1886,12 +2449,34 @@ static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry { - Instance *data(reinterpret_cast(JSObjectGetPrivate(object))); - JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized)); + Instance *internal(reinterpret_cast(JSObjectGetPrivate(object))); + JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized)); return value; } CYCatch } +static bool CYIsClass(id self) { + // XXX: this is a lame object_isClass + return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL; +} + +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; @@ -1940,6 +2525,17 @@ static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStr } CYCatch } +static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) { + if (Class super = class_getSuperclass(_class)) + Internal_getPropertyNames_(super, names); + + unsigned int size; + Ivar *data(class_copyIvarList(_class, &size)); + for (size_t i(0); i != size; ++i) + JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i]))); + free(data); +} + static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) { Internal *internal(reinterpret_cast(JSObjectGetPrivate(object))); CYPool pool; @@ -1947,21 +2543,15 @@ static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, id self(internal->GetValue()); Class _class(object_getClass(self)); - for (Class super(_class); super != NULL; super = class_getSuperclass(super)) { - unsigned int size; - Ivar *data(class_copyIvarList(super, &size)); - for (size_t i(0); i != size; ++i) - JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i]))); - free(data); - } + Internal_getPropertyNames_(_class, names); } 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(); } -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) @@ -2013,7 +2603,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); @@ -2028,11 +2618,11 @@ static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, if (typical->type_ == NULL) return NULL; - ssize_t index; - if (!CYGetIndex(pool, property, index)) + ssize_t offset; + if (!CYGetOffset(pool, property, offset)) return NULL; - return Pointer_getIndex(context, object, index, exception); + return Pointer_getIndex(context, object, offset, exception); } static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { @@ -2062,11 +2652,11 @@ static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStri if (typical->type_ == NULL) return NULL; - ssize_t index; - if (!CYGetIndex(pool, property, index)) + ssize_t offset; + if (!CYGetOffset(pool, property, offset)) return NULL; - return Pointer_setIndex(context, object, 0, value, exception); + return Pointer_setIndex(context, object, offset, value, exception); } static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { @@ -2090,7 +2680,7 @@ static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, J 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); @@ -2164,44 +2754,6 @@ JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, } CYCatch } -void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) { - ffoData *data(reinterpret_cast(arg)); - - JSContextRef context(data->context_); - - size_t count(data->cif_.nargs); - JSValueRef values[count]; - - for (size_t index(0); index != count; ++index) - values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]); - - JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values)); - CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value); -} - -JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) { - // XXX: in case of exceptions this will leak - ffoData *data(new ffoData(type)); - - ffi_closure *closure((ffi_closure *) _syscall(mmap( - NULL, sizeof(ffi_closure), - PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, - -1, 0 - ))); - - ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data)); - _assert(status == FFI_OK); - - _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC)); - - data->value_ = closure; - - data->context_ = CYGetJSContext(); - data->function_ = function; - - return JSObjectMake(context, Functor_, data); -} - static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry { CYPool pool; @@ -2314,9 +2866,19 @@ 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, Instance::None); + return Instance::Make(context, nil); CYTry { CYPool pool; @@ -2337,11 +2899,17 @@ 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) { +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 @@ -2351,12 +2919,14 @@ bool stret(ffi_type *ffi_type) { 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) + NSLog(@""); + else + NSLog(@"%s", CYCastCString(context, arguments[0])); return CYJSUndefined(context); } CYCatch } @@ -2365,7 +2935,7 @@ JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _c const char *type; Class _class(object_getClass(self)); - if (Method method = class_getInstanceMethod(_class, _cmd)) + if (objc_method *method = class_getInstanceMethod(_class, _cmd)) type = method_getTypeEncoding(method); else { CYTry { @@ -2392,6 +2962,14 @@ JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _c return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function); } +static size_t Nonce_(0); + +static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { + char name[16]; + sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++); + return CYCastJSValue(context, name); +} + static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYPool pool; @@ -2405,11 +2983,11 @@ static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObje @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil]; if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) { - Instance *data(reinterpret_cast(JSObjectGetPrivate((JSObjectRef) arguments[0]))); - self = data->GetValue(); - uninitialized = data->IsUninitialized(); + Instance *internal(reinterpret_cast(JSObjectGetPrivate((JSObjectRef) arguments[0]))); + self = internal->GetValue(); + uninitialized = internal->IsUninitialized(); if (uninitialized) - data->value_ = nil; + internal->value_ = nil; } else { self = CYCastNSObject(pool, context, arguments[0]); uninitialized = false; @@ -2424,6 +3002,9 @@ static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObje return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception); } +/* 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)); @@ -2447,11 +3028,20 @@ static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef obje if (count != 1) @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil]; CYPool pool; - Class _class(CYCastNSObject(pool, context, arguments[0])); + NSObject *value(CYCastNSObject(pool, context, arguments[0])); + if (value == NULL || !CYIsClass(value)) + @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil]; + Class _class((Class) value); $objc_registerClassPair(_class); return CYJSUndefined(context); } CYCatch } +/* }}} */ + +static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { + JSGarbageCollect(context); + return CYJSUndefined(context); +} static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { JSValueRef setup[count + 2]; @@ -2461,13 +3051,27 @@ static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef obje return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception); } +static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { + CYPool pool; + Message_privateData *internal(reinterpret_cast(JSObjectGetPrivate(object))); + + // XXX: handle Instance::Uninitialized? + id self(CYCastNSObject(pool, context, _this)); + + void *setup[2]; + setup[0] = &self; + setup[1] = &internal->sel_; + + return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue()); +} + static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYPool pool; - Functor_privateData *data(reinterpret_cast(JSObjectGetPrivate(object))); - return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast(data->value_)); + Functor_privateData *internal(reinterpret_cast(JSObjectGetPrivate(object))); + 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 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]; @@ -2476,7 +3080,7 @@ JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, } CYCatch } -JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { +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]; @@ -2493,25 +3097,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); -} - -JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { +static 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_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_; + + 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))); sig::Type *type(internal->type_); ffi_type *ffi(internal->GetFFI()); // XXX: alignment? @@ -2524,52 +3150,48 @@ 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) + if (count != 0) @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil]; 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) { +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]; id self(count == 0 ? nil : CYCastPointer(context, arguments[0])); - return Instance::Make(context, self, Instance::None); + return Instance::Make(context, self); } CYCatch } -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]; const char *type(CYCastCString(context, arguments[1])); - JSValueRef exception(NULL); - if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) { - JSObjectRef function(CYCastJSObject(context, arguments[0])); - return CYMakeFunctor(context, function, type); - } else if (exception != NULL) { - return NULL; - } else { - void (*function)()(CYCastPointer(context, arguments[0])); - return CYMakeFunctor(context, function, type); - } + 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_)); } -JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { - return Function_; -} - static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYValue *internal(reinterpret_cast(JSObjectGetPrivate(_this))); Type_privateData *typical(internal->GetType()); @@ -2610,7 +3232,33 @@ static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRe } CYCatch } +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_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()); + if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL) + return CYJSUndefined(context); + 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 { @@ -2621,31 +3269,38 @@ static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectR } 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) { - Instance *data(reinterpret_cast(JSObjectGetPrivate(_this))); + if (!JSValueIsObjectOfClass(context, _this, Instance_)) + return NULL; + + Instance *internal(reinterpret_cast(JSObjectGetPrivate(_this))); CYTry { CYPoolTry { - return CYCastJSValue(context, CYJSString([data->GetValue() description])); + return CYCastJSValue(context, CYJSString([internal->GetValue() description])); } CYPoolCatch(NULL) } CYCatch } static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { - Selector_privateData *data(reinterpret_cast(JSObjectGetPrivate(_this))); + Selector_privateData *internal(reinterpret_cast(JSObjectGetPrivate(_this))); CYTry { - return CYCastJSValue(context, sel_getName(data->GetValue())); + return CYCastJSValue(context, sel_getName(internal->GetValue())); } CYCatch } @@ -2670,14 +3325,20 @@ static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil]; CYPool pool; Selector_privateData *internal(reinterpret_cast(JSObjectGetPrivate(_this))); - Class _class(CYCastNSObject(pool, context, arguments[0])); - SEL sel(internal->GetValue()); - if (Method method = class_getInstanceMethod(_class, sel)) - return CYCastJSValue(context, method_getTypeEncoding(method)); - else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))]) - return CYCastJSValue(context, CYJSString(type)); - else + NSObject *value(CYCastNSObject(pool, context, arguments[0])); + if (value == NULL) lookup: + // XXX: do a lookup of some kind return CYJSNull(context); + else if (!CYIsClass(value)) + @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Selector.type takes a Class" userInfo:nil]; + else { + Class _class((Class) value); + SEL sel(internal->GetValue()); + if (objc_method *method = class_getInstanceMethod(_class, sel)) { + const char *type(CYPoolTypeEncoding(pool, _class, sel, method)); + return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type)); + } else goto lookup; + } } CYCatch } @@ -2736,13 +3397,11 @@ static JSStaticFunction Functor_staticFunctions[4] = { {NULL, NULL, 0} }; -/*static JSStaticValue Selector_staticValues[2] = { - {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete}, - {NULL, NULL, NULL, 0} -};*/ - -static JSStaticValue Instance_staticValues[2] = { - {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete}, +static JSStaticValue Instance_staticValues[5] = { + {"constructor", &Instance_getProperty_constructor, 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} }; @@ -2774,28 +3433,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]; @@ -2829,7 +3466,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; @@ -2837,25 +3481,7 @@ 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_; +static apr_pool_t *Pool_; struct CYExecute_ { apr_pool_t *pool_; @@ -2921,8 +3547,11 @@ struct CYClient : json = NULL; size = _not(size_t); } else { + CYContext context(driver.pool_); + driver.program_->Replace(context); std::ostringstream str; - driver.source_->Show(str); + CYOutput out(str); + out << *driver.program_; std::string code(str.str()); CYExecute_ execute = {pool, code.c_str()}; [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES]; @@ -2962,8 +3591,13 @@ MSInitialize { _pooled Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain]; +#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"); @@ -2990,6 +3624,7 @@ JSGlobalContextRef CYGetJSContext() { definition.deleteProperty = &Instance_deleteProperty; definition.getPropertyNames = &Instance_getPropertyNames; definition.callAsConstructor = &Instance_callAsConstructor; + definition.hasInstance = &Instance_hasInstance; definition.finalize = &Finalize; Instance_ = JSClassCreate(&definition); @@ -3003,6 +3638,34 @@ JSGlobalContextRef CYGetJSContext() { 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 = "NSArrayPrototype"; + //definition.hasProperty = &NSArrayPrototype_hasProperty; + //definition.getProperty = &NSArrayPrototype_getProperty; + //definition.setProperty = &NSArrayPrototype_setProperty; + //definition.deleteProperty = &NSArrayPrototype_deleteProperty; + //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames; + NSArrayPrototype_ = JSClassCreate(&definition); + definition = kJSClassDefinitionEmpty; definition.className = "Pointer"; definition.staticValues = Pointer_staticValues; @@ -3015,7 +3678,6 @@ JSGlobalContextRef CYGetJSContext() { definition = kJSClassDefinitionEmpty; definition.className = "Selector"; definition.staticValues = CYValue_staticValues; - //definition.staticValues = Selector_staticValues; definition.staticFunctions = Selector_staticFunctions; definition.callAsFunction = &Selector_callAsFunction; definition.finalize = &Finalize; @@ -3033,11 +3695,11 @@ 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"; @@ -3060,7 +3722,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; @@ -3086,18 +3747,56 @@ JSGlobalContextRef CYGetJSContext() { CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL)); CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL)); - CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new)); - CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, &Instance_new)); + Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))); + Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))); + String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("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_)); + + 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"))); + + JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new)); + JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new)); + JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL)); + JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new)); + + Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_); + + 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); + + CYSetProperty(context, global, CYJSString("Functor"), Functor); + CYSetProperty(context, global, CYJSString("Instance"), Instance); CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new)); - CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new)); - CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new)); + CYSetProperty(context, global, CYJSString("Selector"), Selector); + CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new)); MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair)); +#ifdef __APPLE__ class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast(&NSCFType$cy$toJSON), "@12@0:4@8"); +#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); CYSetProperty(context, global, CYJSString("system"), System_); @@ -3108,14 +3807,17 @@ JSGlobalContextRef CYGetJSContext() { Result_ = JSStringCreateWithUTF8CString("_"); - length_ = JSStringCreateWithUTF8CString("length"); - message_ = JSStringCreateWithUTF8CString("message"); - name_ = JSStringCreateWithUTF8CString("name"); - toCYON_ = JSStringCreateWithUTF8CString("toCYON"); - toJSON_ = JSStringCreateWithUTF8CString("toJSON"); + JSValueProtect(context, Array_); + JSValueProtect(context, Function_); + JSValueProtect(context, String_); - Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))); - Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))); + JSValueProtect(context, Instance_prototype_); + JSValueProtect(context, Object_prototype_); + + JSValueProtect(context, Array_prototype_); + JSValueProtect(context, Array_pop_); + JSValueProtect(context, Array_push_); + JSValueProtect(context, Array_splice_); } return Context_;