1 /* Cycript - Remove Execution Server and Disassembler
2 * Copyright (C) 2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 #include <substrate.h>
43 #include "cycript.hpp"
45 #include "sig/parse.hpp"
46 #include "sig/ffi_type.hpp"
48 #include "Pooling.hpp"
53 #include <CoreFoundation/CoreFoundation.h>
54 #include <CoreFoundation/CFLogUtilities.h>
56 #include <WebKit/WebScriptObject.h>
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
66 #include <ext/stdio_filebuf.h>
74 #include "Cycript.tab.hh"
78 #include <apr-1/apr_thread_proc.h>
83 #define _assert(test) do { \
85 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
88 #define _trace() do { \
89 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
94 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
96 #define CYPoolCatch(value) \
97 @catch (NSException *error) { \
98 _saved = [error retain]; \
104 [_saved autorelease]; \
108 static JSGlobalContextRef Context_;
109 static JSObjectRef System_;
110 static JSObjectRef ObjectiveC_;
112 static JSClassRef Functor_;
113 static JSClassRef Instance_;
114 static JSClassRef Internal_;
115 static JSClassRef Pointer_;
116 static JSClassRef Runtime_;
117 static JSClassRef Selector_;
118 static JSClassRef Struct_;
119 static JSClassRef Type_;
121 static JSClassRef ObjectiveC_Classes_;
122 static JSClassRef ObjectiveC_Image_Classes_;
123 static JSClassRef ObjectiveC_Images_;
124 static JSClassRef ObjectiveC_Protocols_;
126 static JSObjectRef Array_;
127 static JSObjectRef Function_;
129 static JSStringRef Result_;
131 static JSStringRef length_;
132 static JSStringRef message_;
133 static JSStringRef name_;
134 static JSStringRef toCYON_;
135 static JSStringRef toJSON_;
137 static Class NSCFBoolean_;
138 static Class NSCFType_;
139 static Class NSMessageBuilder_;
140 static Class NSZombie_;
141 static Class Object_;
143 static NSArray *Bridge_;
151 static void *operator new(size_t size, apr_pool_t *pool) {
152 void *data(apr_palloc(pool, size));
153 reinterpret_cast<CYData *>(data)->pool_ = pool;
157 static void *operator new(size_t size) {
159 apr_pool_create(&pool, NULL);
160 return operator new(size, pool);
163 static void operator delete(void *data) {
164 apr_pool_destroy(reinterpret_cast<CYData *>(data)->pool_);
167 static void Finalize(JSObjectRef object) {
168 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
172 class Type_privateData;
182 CYValue(void *value) :
187 CYValue(const CYValue &rhs) :
192 virtual Type_privateData *GetType() const {
197 struct Selector_privateData :
200 Selector_privateData(SEL value) :
205 SEL GetValue() const {
206 return reinterpret_cast<SEL>(value_);
209 virtual Type_privateData *GetType() const;
217 Transient = (1 << 0),
218 Uninitialized = (1 << 1),
223 Instance(id value, Flags flags) :
229 virtual ~Instance() {
230 if ((flags_ & Transient) == 0)
231 // XXX: does this handle background threads correctly?
232 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
235 static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
236 return JSObjectMake(context, Instance_, new Instance(object, flags));
239 id GetValue() const {
240 return reinterpret_cast<id>(value_);
243 bool IsUninitialized() const {
244 return (flags_ & Uninitialized) != 0;
247 virtual Type_privateData *GetType() const;
255 Internal(id value, JSObjectRef owner) :
261 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
262 return JSObjectMake(context, Internal_, new Internal(object, owner));
265 id GetValue() const {
266 return reinterpret_cast<id>(value_);
272 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
274 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
275 lhs.name = apr_pstrdup(pool, rhs.name);
276 if (rhs.type == NULL)
279 lhs.type = new(pool) Type;
280 Copy(pool, *lhs.type, *rhs.type);
282 lhs.offset = rhs.offset;
285 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
286 size_t count(rhs.count);
288 lhs.elements = new(pool) Element[count];
289 for (size_t index(0); index != count; ++index)
290 Copy(pool, lhs.elements[index], rhs.elements[index]);
293 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
294 lhs.primitive = rhs.primitive;
295 lhs.name = apr_pstrdup(pool, rhs.name);
296 lhs.flags = rhs.flags;
298 if (sig::IsAggregate(rhs.primitive))
299 Copy(pool, lhs.data.signature, rhs.data.signature);
301 if (rhs.data.data.type != NULL) {
302 lhs.data.data.type = new(pool) Type;
303 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
306 lhs.data.data.size = rhs.data.data.size;
310 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
312 lhs.alignment = rhs.alignment;
314 if (rhs.elements == NULL)
318 while (rhs.elements[count] != NULL)
321 lhs.elements = new(pool) ffi_type *[count + 1];
322 lhs.elements[count] = NULL;
324 for (size_t index(0); index != count; ++index) {
325 // XXX: if these are libffi native then you can just take them
326 ffi_type *ffi(new(pool) ffi_type);
327 lhs.elements[index] = ffi;
328 sig::Copy(pool, *ffi, *rhs.elements[index]);
335 struct CStringMapLess :
336 std::binary_function<const char *, const char *, bool>
338 _finline bool operator ()(const char *lhs, const char *rhs) const {
339 return strcmp(lhs, rhs) < 0;
343 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
348 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
349 switch ([[entry objectAtIndex:0] intValue]) {
351 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
355 sig::Signature signature;
356 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
357 type = signature.elements[0].type;
363 struct Type_privateData :
366 static Type_privateData *Object;
367 static Type_privateData *Selector;
372 void Set(sig::Type *type) {
373 type_ = new(pool_) sig::Type;
374 sig::Copy(pool_, *type_, *type);
377 Type_privateData(apr_pool_t *pool, const char *type) :
383 sig::Signature signature;
384 sig::Parse(pool_, &signature, type, &Structor_);
385 type_ = signature.elements[0].type;
388 Type_privateData(sig::Type *type) :
395 Type_privateData(sig::Type *type, ffi_type *ffi) {
396 ffi_ = new(pool_) ffi_type;
397 sig::Copy(pool_, *ffi_, *ffi);
403 ffi_ = new(pool_) ffi_type;
405 sig::Element element;
407 element.type = type_;
410 sig::Signature signature;
411 signature.elements = &element;
415 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
423 Type_privateData *Type_privateData::Object;
424 Type_privateData *Type_privateData::Selector;
426 Type_privateData *Instance::GetType() const {
427 return Type_privateData::Object;
430 Type_privateData *Selector_privateData::GetType() const {
431 return Type_privateData::Selector;
438 Type_privateData *type_;
440 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
443 type_(new(pool_) Type_privateData(type))
448 struct Struct_privateData :
452 Type_privateData *type_;
454 Struct_privateData(JSObjectRef owner) :
460 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
461 static TypeMap Types_;
463 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
464 Struct_privateData *internal(new Struct_privateData(owner));
465 apr_pool_t *pool(internal->pool_);
466 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
467 internal->type_ = typical;
470 internal->value_ = data;
472 size_t size(typical->GetFFI()->size);
473 void *copy(apr_palloc(internal->pool_, size));
474 memcpy(copy, data, size);
475 internal->value_ = copy;
478 return JSObjectMake(context, Struct_, internal);
481 struct Functor_privateData :
484 sig::Signature signature_;
487 Functor_privateData(const char *type, void (*value)()) :
488 CYValue(reinterpret_cast<void *>(value))
490 sig::Parse(pool_, &signature_, type, &Structor_);
491 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
498 JSContextRef context_;
499 JSObjectRef function_;
501 ffoData(const char *type) :
502 Functor_privateData(type, NULL)
507 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
508 Instance::Flags flags;
511 flags = Instance::Transient;
513 flags = Instance::None;
514 object = [object retain];
517 return Instance::Make(context, object, flags);
520 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
522 return [value UTF8String];
524 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
525 char *string(new(pool) char[size]);
526 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
527 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
532 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
533 return JSValueMakeBoolean(context, value);
536 JSValueRef CYCastJSValue(JSContextRef context, double value) {
537 return JSValueMakeNumber(context, value);
540 #define CYCastJSValue_(Type_) \
541 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
542 return JSValueMakeNumber(context, static_cast<double>(value)); \
546 CYCastJSValue_(unsigned int)
547 CYCastJSValue_(long int)
548 CYCastJSValue_(long unsigned int)
549 CYCastJSValue_(long long int)
550 CYCastJSValue_(long long unsigned int)
552 JSValueRef CYJSUndefined(JSContextRef context) {
553 return JSValueMakeUndefined(context);
556 bool CYGetIndex(const char *value, ssize_t &index) {
557 if (value[0] != '0') {
559 index = strtol(value, &end, 10);
560 if (value + strlen(value) == end)
562 } else if (value[1] == '\0') {
570 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
571 return CYGetIndex(CYPoolCString(pool, value), index);
574 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
576 @interface NSMethodSignature (Cycript)
577 - (NSString *) _typeString;
580 @interface NSObject (Cycript)
582 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
583 - (JSType) cy$JSType;
585 - (NSObject *) cy$toJSON:(NSString *)key;
586 - (NSString *) cy$toCYON;
587 - (NSString *) cy$toKey;
589 - (bool) cy$hasProperty:(NSString *)name;
590 - (NSObject *) cy$getProperty:(NSString *)name;
591 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
592 - (bool) cy$deleteProperty:(NSString *)name;
597 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
600 @interface NSString (Cycript)
601 - (void *) cy$symbol;
604 struct PropertyAttributes {
609 const char *variable;
622 PropertyAttributes(objc_property_t property) :
634 name = property_getName(property);
635 const char *attributes(property_getAttributes(property));
637 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
639 case 'R': readonly = true; break;
640 case 'C': copy = true; break;
641 case '&': retain = true; break;
642 case 'N': nonatomic = true; break;
643 case 'G': getter_ = token + 1; break;
644 case 'S': setter_ = token + 1; break;
645 case 'V': variable = token + 1; break;
649 /*if (variable == NULL) {
650 variable = property_getName(property);
651 size_t size(strlen(variable));
652 char *name(new(pool_) char[size + 2]);
654 memcpy(name + 1, variable, size);
655 name[size + 1] = '\0';
660 const char *Getter() {
662 getter_ = apr_pstrdup(pool_, name);
666 const char *Setter() {
667 if (setter_ == NULL && !readonly) {
668 size_t length(strlen(name));
670 char *temp(new(pool_) char[length + 5]);
676 temp[3] = toupper(name[0]);
677 memcpy(temp + 4, name + 1, length - 1);
680 temp[length + 3] = ':';
681 temp[length + 4] = '\0';
690 @implementation NSProxy (Cycript)
692 - (NSObject *) cy$toJSON:(NSString *)key {
693 return [self description];
696 - (NSString *) cy$toCYON {
697 return [[self cy$toJSON:@""] cy$toCYON];
702 @implementation NSObject (Cycript)
704 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
705 return CYMakeInstance(context, self, false);
708 - (JSType) cy$JSType {
709 return kJSTypeObject;
712 - (NSObject *) cy$toJSON:(NSString *)key {
713 return [self description];
716 - (NSString *) cy$toCYON {
717 return [[self cy$toJSON:@""] cy$toCYON];
720 - (NSString *) cy$toKey {
721 return [self cy$toCYON];
724 - (bool) cy$hasProperty:(NSString *)name {
728 - (NSObject *) cy$getProperty:(NSString *)name {
732 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
736 - (bool) cy$deleteProperty:(NSString *)name {
742 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
743 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
746 @implementation WebUndefined (Cycript)
748 - (JSType) cy$JSType {
749 return kJSTypeUndefined;
752 - (NSObject *) cy$toJSON:(NSString *)key {
756 - (NSString *) cy$toCYON {
760 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
761 return CYJSUndefined(context);
766 @implementation NSNull (Cycript)
768 - (JSType) cy$JSType {
772 - (NSObject *) cy$toJSON:(NSString *)key {
776 - (NSString *) cy$toCYON {
782 @implementation NSArray (Cycript)
784 - (NSString *) cy$toCYON {
785 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
786 [json appendString:@"["];
789 for (id object in self) {
791 [json appendString:@","];
794 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
795 [json appendString:CYPoolNSCYON(NULL, object)];
797 [json appendString:@","];
802 [json appendString:@"]"];
806 - (bool) cy$hasProperty:(NSString *)name {
807 if ([name isEqualToString:@"length"])
811 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
812 return [super cy$hasProperty:name];
817 - (NSObject *) cy$getProperty:(NSString *)name {
818 if ([name isEqualToString:@"length"])
819 return [NSNumber numberWithUnsignedInteger:[self count]];
822 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
823 return [super cy$getProperty:name];
825 return [self objectAtIndex:index];
830 @implementation NSMutableArray (Cycript)
832 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
834 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
835 return [super cy$setProperty:name to:value];
837 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
842 - (bool) cy$deleteProperty:(NSString *)name {
844 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
845 return [super cy$deleteProperty:name];
847 [self removeObjectAtIndex:index];
854 @implementation NSDictionary (Cycript)
856 - (NSString *) cy$toCYON {
857 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
858 [json appendString:@"{"];
861 for (id key in self) {
863 [json appendString:@","];
866 [json appendString:[key cy$toKey]];
867 [json appendString:@":"];
868 NSObject *object([self objectForKey:key]);
869 [json appendString:CYPoolNSCYON(NULL, object)];
872 [json appendString:@"}"];
876 - (bool) cy$hasProperty:(NSString *)name {
877 return [self objectForKey:name] != nil;
880 - (NSObject *) cy$getProperty:(NSString *)name {
881 return [self objectForKey:name];
886 @implementation NSMutableDictionary (Cycript)
888 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
889 [self setObject:(value ?: [NSNull null]) forKey:name];
893 - (bool) cy$deleteProperty:(NSString *)name {
894 if ([self objectForKey:name] == nil)
897 [self removeObjectForKey:name];
904 @implementation NSNumber (Cycript)
906 - (JSType) cy$JSType {
907 // XXX: this just seems stupid
908 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
911 - (NSObject *) cy$toJSON:(NSString *)key {
915 - (NSString *) cy$toCYON {
916 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
919 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
920 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
925 @implementation NSString (Cycript)
927 - (JSType) cy$JSType {
928 return kJSTypeString;
931 - (NSObject *) cy$toJSON:(NSString *)key {
935 - (NSString *) cy$toCYON {
936 // XXX: this should use the better code from Output.cpp
937 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
939 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
940 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
941 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
942 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
943 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
945 CFStringInsert(json, 0, CFSTR("\""));
946 CFStringAppend(json, CFSTR("\""));
948 return [reinterpret_cast<const NSString *>(json) autorelease];
951 - (NSString *) cy$toKey {
952 const char *value([self UTF8String]);
953 size_t size(strlen(value));
958 if (DigitRange_[value[0]]) {
960 if (!CYGetIndex(NULL, self, index) || index < 0)
963 if (!WordStartRange_[value[0]])
965 for (size_t i(1); i != size; ++i)
966 if (!WordEndRange_[value[i]])
973 return [self cy$toCYON];
976 - (void *) cy$symbol {
978 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
983 @interface CYJSObject : NSDictionary {
985 JSContextRef context_;
988 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
990 - (NSString *) cy$toJSON:(NSString *)key;
992 - (NSUInteger) count;
993 - (id) objectForKey:(id)key;
994 - (NSEnumerator *) keyEnumerator;
995 - (void) setObject:(id)object forKey:(id)key;
996 - (void) removeObjectForKey:(id)key;
1000 @interface CYJSArray : NSArray {
1001 JSObjectRef object_;
1002 JSContextRef context_;
1005 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1007 - (NSUInteger) count;
1008 - (id) objectAtIndex:(NSUInteger)index;
1012 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1013 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1014 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1019 @catch (id error) { \
1020 CYThrow(context, error, exception); \
1024 void CYThrow(JSContextRef context, JSValueRef value);
1026 apr_status_t CYPoolRelease_(void *data) {
1027 id object(reinterpret_cast<id>(data));
1032 id CYPoolRelease(apr_pool_t *pool, id object) {
1035 else if (pool == NULL)
1036 return [object autorelease];
1038 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1043 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1044 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1047 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1048 JSValueRef exception(NULL);
1049 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1050 CYThrow(context, exception);
1051 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1052 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1055 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1056 if (!JSValueIsObjectOfClass(context, object, Instance_))
1057 return CYCastNSObject_(pool, context, object);
1059 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1060 return data->GetValue();
1064 JSStringRef CYCopyJSString(id value) {
1065 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
1068 JSStringRef CYCopyJSString(const char *value) {
1069 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
1072 JSStringRef CYCopyJSString(JSStringRef value) {
1073 return value == NULL ? NULL : JSStringRetain(value);
1076 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
1077 if (JSValueIsNull(context, value))
1079 JSValueRef exception(NULL);
1080 JSStringRef string(JSValueToStringCopy(context, value, &exception));
1081 CYThrow(context, exception);
1087 JSStringRef string_;
1090 if (string_ != NULL)
1091 JSStringRelease(string_);
1095 CYJSString(const CYJSString &rhs) :
1096 string_(CYCopyJSString(rhs.string_))
1100 template <typename Arg0_>
1101 CYJSString(Arg0_ arg0) :
1102 string_(CYCopyJSString(arg0))
1106 template <typename Arg0_, typename Arg1_>
1107 CYJSString(Arg0_ arg0, Arg1_ arg1) :
1108 string_(CYCopyJSString(arg0, arg1))
1112 CYJSString &operator =(const CYJSString &rhs) {
1114 string_ = CYCopyJSString(rhs.string_);
1127 operator JSStringRef() const {
1132 CFStringRef CYCopyCFString(JSStringRef value) {
1133 return JSStringCopyCFString(kCFAllocatorDefault, value);
1136 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1137 return CYCopyCFString(CYJSString(context, value));
1140 double CYCastDouble(const char *value, size_t size) {
1142 double number(strtod(value, &end));
1143 if (end != value + size)
1148 double CYCastDouble(const char *value) {
1149 return CYCastDouble(value, strlen(value));
1152 double CYCastDouble(JSContextRef context, JSValueRef value) {
1153 JSValueRef exception(NULL);
1154 double number(JSValueToNumber(context, value, &exception));
1155 CYThrow(context, exception);
1159 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1160 double number(CYCastDouble(context, value));
1161 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1164 CFStringRef CYCopyCFString(const char *value) {
1165 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1168 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1169 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1172 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1173 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1176 bool CYCastBool(JSContextRef context, JSValueRef value) {
1177 return JSValueToBoolean(context, value);
1180 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1184 switch (JSType type = JSValueGetType(context, value)) {
1185 case kJSTypeUndefined:
1186 object = [WebUndefined undefined];
1194 case kJSTypeBoolean:
1195 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1200 object = CYCopyCFNumber(context, value);
1205 object = CYCopyCFString(context, value);
1210 // XXX: this might could be more efficient
1211 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1216 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1223 return CYPoolRelease(pool, object);
1225 return CFRetain(object);
1228 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1229 return CYCFType(pool, context, value, true);
1232 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1233 return CYCFType(pool, context, value, false);
1236 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1238 size_t size(JSPropertyNameArrayGetCount(names));
1239 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1240 for (size_t index(0); index != size; ++index)
1241 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1245 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1246 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1249 void CYThrow(JSContextRef context, JSValueRef value) {
1252 @throw CYCastNSObject(NULL, context, value);
1255 JSValueRef CYJSNull(JSContextRef context) {
1256 return JSValueMakeNull(context);
1259 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1260 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1263 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1264 return CYCastJSValue(context, CYJSString(value));
1267 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1269 return CYJSNull(context);
1270 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1271 return [value cy$JSValueInContext:context];
1273 return CYMakeInstance(context, value, false);
1276 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1277 JSValueRef exception(NULL);
1278 JSObjectRef object(JSValueToObject(context, value, &exception));
1279 CYThrow(context, exception);
1283 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1284 JSValueRef exception(NULL);
1285 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1286 CYThrow(context, exception);
1290 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1291 JSValueRef exception(NULL);
1292 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1293 CYThrow(context, exception);
1297 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1298 JSValueRef exception(NULL);
1299 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1300 CYThrow(context, exception);
1303 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1304 if (exception == NULL)
1306 *exception = CYCastJSValue(context, error);
1309 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1310 JSValueRef exception(NULL);
1311 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1312 CYThrow(context, exception);
1316 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1317 // XXX: this isn't actually correct
1318 return value != NULL && JSValueIsObject(context, value);
1321 @implementation CYJSObject
1323 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1324 if ((self = [super init]) != nil) {
1330 - (NSObject *) cy$toJSON:(NSString *)key {
1331 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1332 if (!CYIsCallable(context_, toJSON))
1333 return [super cy$toJSON:key];
1335 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1336 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1337 // XXX: do I really want an NSNull here?!
1338 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1342 - (NSString *) cy$toCYON {
1343 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1344 if (!CYIsCallable(context_, toCYON))
1345 return [super cy$toCYON];
1347 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1348 return CYCastNSString(NULL, CYJSString(context_, value));
1352 - (NSUInteger) count {
1353 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1354 size_t size(JSPropertyNameArrayGetCount(names));
1355 JSPropertyNameArrayRelease(names);
1359 - (id) objectForKey:(id)key {
1360 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1363 - (NSEnumerator *) keyEnumerator {
1364 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1365 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1366 JSPropertyNameArrayRelease(names);
1370 - (void) setObject:(id)object forKey:(id)key {
1371 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1374 - (void) removeObjectForKey:(id)key {
1375 JSValueRef exception(NULL);
1376 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1377 CYThrow(context_, exception);
1382 @implementation CYJSArray
1384 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1385 if ((self = [super init]) != nil) {
1391 - (NSUInteger) count {
1392 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1395 - (id) objectAtIndex:(NSUInteger)index {
1396 JSValueRef exception(NULL);
1397 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1398 CYThrow(context_, exception);
1399 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1404 NSString *CYCopyNSCYON(id value) {
1410 Class _class(object_getClass(value));
1411 SEL sel(@selector(cy$toCYON));
1413 if (Method toCYON = class_getInstanceMethod(_class, sel))
1414 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1415 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1416 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1417 string = [value cy$toCYON];
1420 if (value == NSZombie_)
1421 string = @"_NSZombie_";
1422 else if (_class == NSZombie_)
1423 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1424 // XXX: frowny /in/ the pants
1425 else if (value == NSMessageBuilder_ || value == Object_)
1428 string = [NSString stringWithFormat:@"%@", value];
1431 // XXX: frowny pants
1433 string = @"undefined";
1436 return [string retain];
1439 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1442 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1447 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1448 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1451 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1452 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1453 const char *string(CYPoolCString(pool, json));
1459 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1463 JSObjectRef object_;
1471 // XXX: delete object_? ;(
1474 static CYInternal *Get(id self) {
1475 CYInternal *internal(NULL);
1476 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1477 // XXX: do something epic? ;P
1483 static CYInternal *Set(id self) {
1484 CYInternal *internal(NULL);
1485 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1486 if (internal == NULL) {
1487 internal = new CYInternal();
1488 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1491 // XXX: do something epic? ;P
1497 bool HasProperty(JSContextRef context, JSStringRef name) {
1498 if (object_ == NULL)
1500 return JSObjectHasProperty(context, object_, name);
1503 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1504 if (object_ == NULL)
1506 return CYGetProperty(context, object_, name);
1509 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1510 if (object_ == NULL)
1511 object_ = JSObjectMake(context, NULL, NULL);
1512 CYSetProperty(context, object_, name, value);
1516 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1517 Selector_privateData *data(new Selector_privateData(sel));
1518 return JSObjectMake(context, Selector_, data);
1521 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1522 Pointer *data(new Pointer(pointer, type, owner));
1523 return JSObjectMake(context, Pointer_, data);
1526 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1527 Functor_privateData *data(new Functor_privateData(type, function));
1528 return JSObjectMake(context, Functor_, data);
1531 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1533 const char *string([CYCastNSString(NULL, value) UTF8String]);
1536 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1537 char *string(new(pool) char[size]);
1538 JSStringGetUTF8CString(value, string, size);
1543 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1544 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1547 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1548 return CYGetIndex(CYPoolCString(pool, value), index);
1551 // XXX: this macro is unhygenic
1552 #define CYCastCString(context, value) ({ \
1554 if (value == NULL) \
1556 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1557 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1558 utf8 = reinterpret_cast<char *>(alloca(size)); \
1559 JSStringGetUTF8CString(string, utf8, size); \
1560 JSStringRelease(string); \
1566 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1567 switch (JSValueGetType(context, value)) {
1570 /*case kJSTypeString:
1571 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1573 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1574 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1575 return data->value_;
1578 double number(CYCastDouble(context, value));
1579 if (std::isnan(number))
1580 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1581 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1585 template <typename Type_>
1586 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1587 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1590 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1591 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1592 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1593 return reinterpret_cast<SEL>(data->value_);
1595 return CYCastPointer<SEL>(context, value);
1598 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1599 switch (type->primitive) {
1600 case sig::boolean_P:
1601 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1604 #define CYPoolFFI_(primitive, native) \
1605 case sig::primitive ## _P: \
1606 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1609 CYPoolFFI_(uchar, unsigned char)
1610 CYPoolFFI_(char, char)
1611 CYPoolFFI_(ushort, unsigned short)
1612 CYPoolFFI_(short, short)
1613 CYPoolFFI_(ulong, unsigned long)
1614 CYPoolFFI_(long, long)
1615 CYPoolFFI_(uint, unsigned int)
1616 CYPoolFFI_(int, int)
1617 CYPoolFFI_(ulonglong, unsigned long long)
1618 CYPoolFFI_(longlong, long long)
1619 CYPoolFFI_(float, float)
1620 CYPoolFFI_(double, double)
1623 case sig::typename_P:
1624 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1627 case sig::selector_P:
1628 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1631 case sig::pointer_P:
1632 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1636 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1639 case sig::struct_P: {
1640 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1641 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1642 for (size_t index(0); index != type->data.signature.count; ++index) {
1643 sig::Element *element(&type->data.signature.elements[index]);
1644 ffi_type *field(ffi->elements[index]);
1647 if (aggregate == NULL)
1650 rhs = CYGetProperty(context, aggregate, index);
1651 if (JSValueIsUndefined(context, rhs)) {
1652 if (element->name != NULL)
1653 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1656 if (JSValueIsUndefined(context, rhs)) undefined:
1657 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1661 CYPoolFFI(pool, context, element->type, field, base, rhs);
1663 base += field->size;
1671 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1676 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1679 switch (type->primitive) {
1680 case sig::boolean_P:
1681 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1684 #define CYFromFFI_(primitive, native) \
1685 case sig::primitive ## _P: \
1686 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1689 CYFromFFI_(uchar, unsigned char)
1690 CYFromFFI_(char, char)
1691 CYFromFFI_(ushort, unsigned short)
1692 CYFromFFI_(short, short)
1693 CYFromFFI_(ulong, unsigned long)
1694 CYFromFFI_(long, long)
1695 CYFromFFI_(uint, unsigned int)
1696 CYFromFFI_(int, int)
1697 CYFromFFI_(ulonglong, unsigned long long)
1698 CYFromFFI_(longlong, long long)
1699 CYFromFFI_(float, float)
1700 CYFromFFI_(double, double)
1702 case sig::object_P: {
1703 if (id object = *reinterpret_cast<id *>(data)) {
1704 value = CYCastJSValue(context, object);
1710 case sig::typename_P:
1711 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1714 case sig::selector_P:
1715 if (SEL sel = *reinterpret_cast<SEL *>(data))
1716 value = CYMakeSelector(context, sel);
1720 case sig::pointer_P:
1721 if (void *pointer = *reinterpret_cast<void **>(data))
1722 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1727 if (char *utf8 = *reinterpret_cast<char **>(data))
1728 value = CYCastJSValue(context, utf8);
1733 value = CYMakeStruct(context, data, type, ffi, owner);
1737 value = CYJSUndefined(context);
1741 value = CYJSNull(context);
1745 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1752 static bool CYImplements(id object, Class _class, SEL selector) {
1753 // XXX: possibly use a more "awesome" check?
1754 return class_getInstanceMethod(_class, selector) != NULL;
1757 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1758 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1759 id self(internal->GetValue());
1761 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1765 NSString *name(CYCastNSString(pool, property));
1767 if (CYInternal *internal = CYInternal::Get(self))
1768 if (internal->HasProperty(context, property))
1772 if ([self cy$hasProperty:name])
1774 } CYPoolCatch(false)
1776 const char *string(CYPoolCString(pool, name));
1777 Class _class(object_getClass(self));
1779 if (class_getProperty(_class, string) != NULL)
1782 if (SEL sel = sel_getUid(string))
1783 if (CYImplements(self, _class, sel))
1789 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1790 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1791 id self(internal->GetValue());
1793 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1794 return Internal::Make(context, self, object);
1798 NSString *name(CYCastNSString(pool, property));
1800 if (CYInternal *internal = CYInternal::Get(self))
1801 if (JSValueRef value = internal->GetProperty(context, property))
1805 if (NSObject *data = [self cy$getProperty:name])
1806 return CYCastJSValue(context, data);
1809 const char *string(CYPoolCString(pool, name));
1810 Class _class(object_getClass(self));
1812 if (objc_property_t property = class_getProperty(_class, string)) {
1813 PropertyAttributes attributes(property);
1814 SEL sel(sel_registerName(attributes.Getter()));
1815 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
1818 if (SEL sel = sel_getUid(string))
1819 if (CYImplements(self, _class, sel))
1820 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
1826 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1830 id self(CYCastNSObject(pool, context, object));
1831 NSString *name(CYCastNSString(pool, property));
1832 NSString *data(CYCastNSObject(pool, context, value));
1835 if ([self cy$setProperty:name to:data])
1839 const char *string(CYPoolCString(pool, name));
1840 Class _class(object_getClass(self));
1842 if (objc_property_t property = class_getProperty(_class, string)) {
1843 PropertyAttributes attributes(property);
1844 if (const char *setter = attributes.Setter()) {
1845 SEL sel(sel_registerName(setter));
1846 JSValueRef arguments[1] = {value};
1847 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
1852 size_t length(strlen(string));
1854 char set[length + 5];
1860 if (string[0] != '\0') {
1861 set[3] = toupper(string[0]);
1862 memcpy(set + 4, string + 1, length - 1);
1865 set[length + 3] = ':';
1866 set[length + 4] = '\0';
1868 if (SEL sel = sel_getUid(set))
1869 if (CYImplements(self, _class, sel)) {
1870 JSValueRef arguments[1] = {value};
1871 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
1874 if (CYInternal *internal = CYInternal::Set(self)) {
1875 internal->SetProperty(context, property, value);
1883 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1886 id self(CYCastNSObject(NULL, context, object));
1887 NSString *name(CYCastNSString(NULL, property));
1888 return [self cy$deleteProperty:name];
1893 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1895 NSString *self(CYCastNSObject(pool, context, object));
1896 Class _class(object_getClass(self));
1900 objc_property_t *data(class_copyPropertyList(_class, &size));
1901 for (size_t i(0); i != size; ++i)
1902 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1907 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1909 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1910 JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
1915 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1916 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1919 id self(internal->GetValue());
1920 const char *name(CYPoolCString(pool, property));
1922 if (object_getInstanceVariable(self, name, NULL) != NULL)
1928 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1929 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1933 id self(internal->GetValue());
1934 const char *name(CYPoolCString(pool, property));
1936 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
1937 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1938 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1945 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1946 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1950 id self(internal->GetValue());
1951 const char *name(CYPoolCString(pool, property));
1953 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
1954 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1955 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1963 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1964 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1967 id self(internal->GetValue());
1968 Class _class(object_getClass(self));
1970 for (Class super(_class); super != NULL; super = class_getSuperclass(super)) {
1972 Ivar *data(class_copyIvarList(super, &size));
1973 for (size_t i(0); i != size; ++i)
1974 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1979 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1980 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1981 return internal->owner_;
1984 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1985 Type_privateData *typical(internal->type_);
1986 sig::Type *type(typical->type_);
1990 const char *name(CYPoolCString(pool, property));
1991 size_t length(strlen(name));
1992 double number(CYCastDouble(name, length));
1994 size_t count(type->data.signature.count);
1996 if (std::isnan(number)) {
1997 if (property == NULL)
2000 sig::Element *elements(type->data.signature.elements);
2002 for (size_t local(0); local != count; ++local) {
2003 sig::Element *element(&elements[local]);
2004 if (element->name != NULL && strcmp(name, element->name) == 0) {
2012 index = static_cast<ssize_t>(number);
2013 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2018 ffi_type **elements(typical->GetFFI()->elements);
2020 base = reinterpret_cast<uint8_t *>(internal->value_);
2021 for (ssize_t local(0); local != index; ++local)
2022 base += elements[local]->size;
2027 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2028 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2029 Type_privateData *typical(internal->type_);
2031 ffi_type *ffi(typical->GetFFI());
2033 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2034 base += ffi->size * index;
2036 JSObjectRef owner(internal->owner_ ?: object);
2039 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2043 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2045 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2046 Type_privateData *typical(internal->type_);
2048 if (typical->type_ == NULL)
2052 if (!CYGetIndex(pool, property, index))
2055 return Pointer_getIndex(context, object, index, exception);
2058 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2059 return Pointer_getIndex(context, object, 0, exception);
2062 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2063 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2064 Type_privateData *typical(internal->type_);
2066 ffi_type *ffi(typical->GetFFI());
2068 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2069 base += ffi->size * index;
2072 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2077 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2079 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2080 Type_privateData *typical(internal->type_);
2082 if (typical->type_ == NULL)
2086 if (!CYGetIndex(pool, property, index))
2089 return Pointer_setIndex(context, object, 0, value, exception);
2092 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2093 return Pointer_setIndex(context, object, 0, value, exception);
2096 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2097 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2098 Type_privateData *typical(internal->type_);
2099 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2102 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2104 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2105 Type_privateData *typical(internal->type_);
2110 if (!Index_(pool, internal, property, index, base))
2113 JSObjectRef owner(internal->owner_ ?: object);
2116 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2120 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2122 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2123 Type_privateData *typical(internal->type_);
2128 if (!Index_(pool, internal, property, index, base))
2132 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2137 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2138 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2139 Type_privateData *typical(internal->type_);
2140 sig::Type *type(typical->type_);
2145 size_t count(type->data.signature.count);
2146 sig::Element *elements(type->data.signature.elements);
2150 for (size_t index(0); index != count; ++index) {
2152 name = elements[index].name;
2155 sprintf(number, "%lu", index);
2159 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2163 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)()) {
2165 if (setups + count != signature->count - 1)
2166 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2168 size_t size(setups + count);
2170 memcpy(values, setup, sizeof(void *) * setups);
2172 for (size_t index(setups); index != size; ++index) {
2173 sig::Element *element(&signature->elements[index + 1]);
2174 ffi_type *ffi(cif->arg_types[index]);
2176 values[index] = new(pool) uint8_t[ffi->size];
2177 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2180 uint8_t value[cif->rtype->size];
2181 ffi_call(cif, function, value, values);
2183 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2187 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2188 ffoData *data(reinterpret_cast<ffoData *>(arg));
2190 JSContextRef context(data->context_);
2192 size_t count(data->cif_.nargs);
2193 JSValueRef values[count];
2195 for (size_t index(0); index != count; ++index)
2196 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
2198 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
2199 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
2202 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2203 // XXX: in case of exceptions this will leak
2204 ffoData *data(new ffoData(type));
2206 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2207 NULL, sizeof(ffi_closure),
2208 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2212 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
2213 _assert(status == FFI_OK);
2215 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2217 data->value_ = closure;
2219 data->context_ = CYGetJSContext();
2220 data->function_ = function;
2222 return JSObjectMake(context, Functor_, data);
2225 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2228 NSString *name(CYCastNSString(pool, property));
2229 if (Class _class = NSClassFromString(name))
2230 return CYMakeInstance(context, _class, true);
2235 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2236 size_t size(objc_getClassList(NULL, 0));
2237 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2240 size_t writ(objc_getClassList(data, size));
2243 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2249 for (size_t i(0); i != writ; ++i)
2250 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2256 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2257 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2261 const char *name(CYPoolCString(pool, property));
2263 const char **data(objc_copyClassNamesForImage(internal, &size));
2265 for (size_t i(0); i != size; ++i)
2266 if (strcmp(name, data[i]) == 0) {
2267 if (Class _class = objc_getClass(name)) {
2268 value = CYMakeInstance(context, _class, true);
2280 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2281 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2283 const char **data(objc_copyClassNamesForImage(internal, &size));
2284 for (size_t i(0); i != size; ++i)
2285 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2289 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2292 const char *name(CYPoolCString(pool, property));
2294 const char **data(objc_copyImageNames(&size));
2295 for (size_t i(0); i != size; ++i)
2296 if (strcmp(name, data[i]) == 0) {
2305 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2306 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2311 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2313 const char **data(objc_copyImageNames(&size));
2314 for (size_t i(0); i != size; ++i)
2315 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2319 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2322 NSString *name(CYCastNSString(pool, property));
2323 if (Protocol *protocol = NSProtocolFromString(name))
2324 return CYMakeInstance(context, protocol, true);
2329 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2331 Protocol **data(objc_copyProtocolList(&size));
2332 for (size_t i(0); i != size; ++i)
2333 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2337 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2338 if (JSStringIsEqualToUTF8CString(property, "nil"))
2339 return Instance::Make(context, nil, Instance::None);
2343 NSString *name(CYCastNSString(pool, property));
2344 if (Class _class = NSClassFromString(name))
2345 return CYMakeInstance(context, _class, true);
2346 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2347 switch ([[entry objectAtIndex:0] intValue]) {
2349 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2351 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2353 // XXX: this is horrendously inefficient
2354 sig::Signature signature;
2355 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2357 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2358 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2364 bool stret(ffi_type *ffi_type) {
2365 return ffi_type->type == FFI_TYPE_STRUCT && (
2366 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2367 struct_forward_array[ffi_type->size] != 0
2372 int *_NSGetArgc(void);
2373 char ***_NSGetArgv(void);
2374 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2377 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2379 NSLog(@"%s", CYCastCString(context, arguments[0]));
2380 return CYJSUndefined(context);
2384 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2387 Class _class(object_getClass(self));
2388 if (Method method = class_getInstanceMethod(_class, _cmd))
2389 type = method_getTypeEncoding(method);
2393 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2395 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2396 type = CYPoolCString(pool, [method _typeString]);
2405 sig::Signature signature;
2406 sig::Parse(pool, &signature, type, &Structor_);
2409 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2411 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2412 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2415 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2425 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2427 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2428 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2429 self = data->GetValue();
2430 uninitialized = data->IsUninitialized();
2434 self = CYCastNSObject(pool, context, arguments[0]);
2435 uninitialized = false;
2439 return CYJSNull(context);
2441 _cmd = CYCastSEL(context, arguments[1]);
2444 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2447 MSHook(void, CYDealloc, id self, SEL sel) {
2448 CYInternal *internal;
2449 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2450 if (internal != NULL)
2452 _CYDealloc(self, sel);
2455 MSHook(void, objc_registerClassPair, Class _class) {
2456 Class super(class_getSuperclass(_class));
2457 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2458 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2459 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2462 _objc_registerClassPair(_class);
2465 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2468 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2470 Class _class(CYCastNSObject(pool, context, arguments[0]));
2471 $objc_registerClassPair(_class);
2472 return CYJSUndefined(context);
2476 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2477 JSValueRef setup[count + 2];
2480 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2481 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2484 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2486 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2487 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
2490 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2493 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2494 const char *name(CYCastCString(context, arguments[0]));
2495 return CYMakeSelector(context, sel_registerName(name));
2499 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2502 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2504 void *value(CYCastPointer<void *>(context, arguments[0]));
2505 const char *type(CYCastCString(context, arguments[1]));
2509 sig::Signature signature;
2510 sig::Parse(pool, &signature, type, &Structor_);
2512 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2516 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2517 Type_privateData *internal(new Type_privateData(NULL, type));
2518 return JSObjectMake(context, Type_, internal);
2521 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2524 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2525 const char *type(CYCastCString(context, arguments[0]));
2526 return CYMakeType(context, object, type);
2530 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2533 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2534 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2535 sig::Type *type(internal->type_);
2536 ffi_type *ffi(internal->GetFFI());
2538 uint8_t value[ffi->size];
2540 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2541 return CYFromFFI(context, type, ffi, value);
2545 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2548 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2549 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2550 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2552 void *value(malloc(internal->GetFFI()->size * size));
2553 return CYMakePointer(context, value, internal->type_, internal->ffi_, NULL);
2557 JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2560 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
2561 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2562 return Instance::Make(context, self, Instance::None);
2566 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2569 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2570 const char *type(CYCastCString(context, arguments[1]));
2571 JSValueRef exception(NULL);
2572 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
2573 JSObjectRef function(CYCastJSObject(context, arguments[0]));
2574 return CYMakeFunctor(context, function, type);
2575 } else if (exception != NULL) {
2578 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
2579 return CYMakeFunctor(context, function, type);
2584 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2585 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2586 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2589 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2593 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2594 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2595 Type_privateData *typical(internal->GetType());
2600 if (typical == NULL) {
2604 type = typical->type_;
2605 ffi = typical->ffi_;
2608 return CYMakePointer(context, &internal->value_, type, ffi, object);
2611 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2612 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2615 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2619 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2620 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2623 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2624 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2626 sprintf(string, "%p", internal->value_);
2629 return CYCastJSValue(context, string);
2633 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2634 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2638 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
2643 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2644 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2648 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2649 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
2654 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2655 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2659 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
2664 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2665 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2668 return CYCastJSValue(context, sel_getName(data->GetValue()));
2672 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2673 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2676 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2677 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2678 const char *name(sel_getName(internal->GetValue()));
2682 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2687 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2690 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2692 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2693 Class _class(CYCastNSObject(pool, context, arguments[0]));
2694 SEL sel(internal->GetValue());
2695 if (Method method = class_getInstanceMethod(_class, sel))
2696 return CYCastJSValue(context, method_getTypeEncoding(method));
2697 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2698 return CYCastJSValue(context, CYJSString(type));
2700 return CYJSNull(context);
2704 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2706 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2708 const char *type(sig::Unparse(pool, internal->type_));
2710 return CYCastJSValue(context, CYJSString(type));
2715 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2717 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2719 const char *type(sig::Unparse(pool, internal->type_));
2721 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
2726 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2727 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
2730 static JSStaticValue CYValue_staticValues[2] = {
2731 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2732 {NULL, NULL, NULL, 0}
2735 static JSStaticValue Pointer_staticValues[2] = {
2736 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2737 {NULL, NULL, NULL, 0}
2740 static JSStaticFunction Pointer_staticFunctions[4] = {
2741 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2742 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2743 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2747 static JSStaticFunction Struct_staticFunctions[2] = {
2748 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2752 static JSStaticFunction Functor_staticFunctions[4] = {
2753 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2754 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2755 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2759 /*static JSStaticValue Selector_staticValues[2] = {
2760 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2761 {NULL, NULL, NULL, 0}
2764 static JSStaticValue Instance_staticValues[2] = {
2765 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2766 {NULL, NULL, NULL, 0}
2769 static JSStaticFunction Instance_staticFunctions[5] = {
2770 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2771 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2772 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2773 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2777 static JSStaticFunction Internal_staticFunctions[2] = {
2778 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2782 static JSStaticFunction Selector_staticFunctions[5] = {
2783 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2784 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2785 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2786 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2790 static JSStaticFunction Type_staticFunctions[4] = {
2791 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2792 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2793 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2797 CYDriver::CYDriver(const std::string &filename) :
2801 filename_(filename),
2807 CYDriver::~CYDriver() {
2811 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2812 CYDriver::Error error;
2813 error.location_ = location;
2814 error.message_ = message;
2815 driver.errors_.push_back(error);
2818 void CYSetArgs(int argc, const char *argv[]) {
2819 JSContextRef context(CYGetJSContext());
2820 JSValueRef args[argc];
2821 for (int i(0); i != argc; ++i)
2822 args[i] = CYCastJSValue(context, argv[i]);
2823 JSValueRef exception(NULL);
2824 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
2825 CYThrow(context, exception);
2826 CYSetProperty(context, System_, CYJSString("args"), array);
2829 JSObjectRef CYGetGlobalObject(JSContextRef context) {
2830 return JSContextGetGlobalObject(context);
2833 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
2834 JSContextRef context(CYGetJSContext());
2835 JSValueRef exception(NULL), result;
2838 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
2839 } catch (const char *error) {
2843 if (exception != NULL) { error:
2848 if (JSValueIsUndefined(context, result))
2851 const char *json(CYPoolCCYON(pool, context, result, &exception));
2852 if (exception != NULL)
2855 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
2859 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
2860 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
2868 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
2869 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
2882 const char * volatile data_;
2885 // XXX: this is "tre lame"
2886 @interface CYClient_ : NSObject {
2889 - (void) execute:(NSValue *)value;
2893 @implementation CYClient_
2895 - (void) execute:(NSValue *)value {
2896 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
2897 const char *data(execute->data_);
2898 execute->data_ = NULL;
2899 execute->data_ = CYExecute(execute->pool_, data);
2908 apr_thread_t *thread_;
2910 CYClient(int socket) :
2916 _syscall(close(socket_));
2919 void Handle() { _pooled
2920 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
2924 if (!CYRecvAll(socket_, &size, sizeof(size)))
2928 char *data(new(pool) char[size + 1]);
2929 if (!CYRecvAll(socket_, data, size))
2933 CYDriver driver("");
2934 cy::parser parser(driver);
2936 driver.data_ = data;
2937 driver.size_ = size;
2940 if (parser.parse() != 0 || !driver.errors_.empty()) {
2942 size = _not(size_t);
2944 std::ostringstream str;
2945 driver.source_->Show(str);
2946 std::string code(str.str());
2947 CYExecute_ execute = {pool, code.c_str()};
2948 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
2949 json = execute.data_;
2950 size = json == NULL ? _not(size_t) : strlen(json);
2953 if (!CYSendAll(socket_, &size, sizeof(size)))
2956 if (!CYSendAll(socket_, json, size))
2962 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
2963 CYClient *client(reinterpret_cast<CYClient *>(data));
2969 static void * APR_THREAD_FUNC Cyrver(apr_thread_t *thread, void *data) {
2971 int socket(_syscall(accept(Socket_, NULL, NULL)));
2972 CYClient *client(new CYClient(socket));
2973 apr_threadattr_t *attr;
2974 _aprcall(apr_threadattr_create(&attr, Pool_));
2975 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
2982 pid_t pid(getpid());
2984 sprintf(path, "/tmp/.s.cy.%u", pid);
2988 MSInitialize { _pooled
2989 _aprcall(apr_initialize());
2990 _aprcall(apr_pool_create(&Pool_, NULL));
2992 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
2993 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
2995 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2997 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2998 NSCFType_ = objc_getClass("NSCFType");
2999 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3000 NSZombie_ = objc_getClass("_NSZombie_");
3001 Object_ = objc_getClass("Object");
3003 Socket_ = _syscall(socket(PF_UNIX, SOCK_STREAM, 0));
3005 struct sockaddr_un address;
3006 memset(&address, 0, sizeof(address));
3007 address.sun_family = AF_UNIX;
3009 pid_t pid(getpid());
3010 sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
3013 _syscall(bind(Socket_, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
3015 _syscall(listen(Socket_, 0));
3017 apr_threadattr_t *attr;
3018 _aprcall(apr_threadattr_create(&attr, Pool_));
3020 apr_thread_t *thread;
3021 _aprcall(apr_thread_create(&thread, attr, &Cyrver, NULL, Pool_));
3023 NSLog(@"failed to setup Cyrver");
3027 JSGlobalContextRef CYGetJSContext() {
3028 if (Context_ == NULL) {
3029 JSClassDefinition definition;
3031 definition = kJSClassDefinitionEmpty;
3032 definition.className = "Functor";
3033 definition.staticFunctions = Functor_staticFunctions;
3034 definition.callAsFunction = &Functor_callAsFunction;
3035 definition.finalize = &CYData::Finalize;
3036 Functor_ = JSClassCreate(&definition);
3038 definition = kJSClassDefinitionEmpty;
3039 definition.className = "Instance";
3040 definition.staticValues = Instance_staticValues;
3041 definition.staticFunctions = Instance_staticFunctions;
3042 definition.hasProperty = &Instance_hasProperty;
3043 definition.getProperty = &Instance_getProperty;
3044 definition.setProperty = &Instance_setProperty;
3045 definition.deleteProperty = &Instance_deleteProperty;
3046 definition.getPropertyNames = &Instance_getPropertyNames;
3047 definition.callAsConstructor = &Instance_callAsConstructor;
3048 definition.finalize = &CYData::Finalize;
3049 Instance_ = JSClassCreate(&definition);
3051 definition = kJSClassDefinitionEmpty;
3052 definition.className = "Internal";
3053 definition.staticFunctions = Internal_staticFunctions;
3054 definition.hasProperty = &Internal_hasProperty;
3055 definition.getProperty = &Internal_getProperty;
3056 definition.setProperty = &Internal_setProperty;
3057 definition.getPropertyNames = &Internal_getPropertyNames;
3058 definition.finalize = &CYData::Finalize;
3059 Internal_ = JSClassCreate(&definition);
3061 definition = kJSClassDefinitionEmpty;
3062 definition.className = "Pointer";
3063 definition.staticValues = Pointer_staticValues;
3064 definition.staticFunctions = Pointer_staticFunctions;
3065 definition.getProperty = &Pointer_getProperty;
3066 definition.setProperty = &Pointer_setProperty;
3067 definition.finalize = &CYData::Finalize;
3068 Pointer_ = JSClassCreate(&definition);
3070 definition = kJSClassDefinitionEmpty;
3071 definition.className = "Selector";
3072 definition.staticValues = CYValue_staticValues;
3073 //definition.staticValues = Selector_staticValues;
3074 definition.staticFunctions = Selector_staticFunctions;
3075 definition.callAsFunction = &Selector_callAsFunction;
3076 definition.finalize = &CYData::Finalize;
3077 Selector_ = JSClassCreate(&definition);
3079 definition = kJSClassDefinitionEmpty;
3080 definition.className = "Struct";
3081 definition.staticFunctions = Struct_staticFunctions;
3082 definition.getProperty = &Struct_getProperty;
3083 definition.setProperty = &Struct_setProperty;
3084 definition.getPropertyNames = &Struct_getPropertyNames;
3085 definition.finalize = &CYData::Finalize;
3086 Struct_ = JSClassCreate(&definition);
3088 definition = kJSClassDefinitionEmpty;
3089 definition.className = "Type";
3090 definition.staticFunctions = Type_staticFunctions;
3091 //definition.getProperty = &Type_getProperty;
3092 definition.callAsFunction = &Type_callAsFunction;
3093 definition.callAsConstructor = &Type_callAsConstructor;
3094 definition.finalize = &CYData::Finalize;
3095 Type_ = JSClassCreate(&definition);
3097 definition = kJSClassDefinitionEmpty;
3098 definition.className = "Runtime";
3099 definition.getProperty = &Runtime_getProperty;
3100 Runtime_ = JSClassCreate(&definition);
3102 definition = kJSClassDefinitionEmpty;
3103 definition.className = "ObjectiveC::Classes";
3104 definition.getProperty = &ObjectiveC_Classes_getProperty;
3105 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3106 ObjectiveC_Classes_ = JSClassCreate(&definition);
3108 definition = kJSClassDefinitionEmpty;
3109 definition.className = "ObjectiveC::Images";
3110 definition.getProperty = &ObjectiveC_Images_getProperty;
3111 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3112 ObjectiveC_Images_ = JSClassCreate(&definition);
3114 definition = kJSClassDefinitionEmpty;
3115 definition.className = "ObjectiveC::Image::Classes";
3116 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3117 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3118 definition.finalize = &CYData::Finalize;
3119 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3121 definition = kJSClassDefinitionEmpty;
3122 definition.className = "ObjectiveC::Protocols";
3123 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3124 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3125 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3127 definition = kJSClassDefinitionEmpty;
3128 //definition.getProperty = &Global_getProperty;
3129 JSClassRef Global(JSClassCreate(&definition));
3131 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3134 JSObjectRef global(CYGetGlobalObject(context));
3136 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3137 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3138 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3140 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3141 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3142 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3144 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
3145 CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, &Instance_new));
3146 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3147 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
3148 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3150 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3152 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3154 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3155 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3157 System_ = JSObjectMake(context, NULL, NULL);
3158 CYSetProperty(context, global, CYJSString("system"), System_);
3159 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3160 //CYSetProperty(context, System_, CYJSString("global"), global);
3162 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3164 Result_ = JSStringCreateWithUTF8CString("_");
3166 length_ = JSStringCreateWithUTF8CString("length");
3167 message_ = JSStringCreateWithUTF8CString("message");
3168 name_ = JSStringCreateWithUTF8CString("name");
3169 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3170 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3172 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3173 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));