1 /* Cycript - Remote 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.
40 #include <substrate.h>
41 #include "cycript.hpp"
43 #include "sig/parse.hpp"
44 #include "sig/ffi_type.hpp"
46 #include "Pooling.hpp"
50 #include <CoreFoundation/CoreFoundation.h>
51 #include <CoreFoundation/CFLogUtilities.h>
52 #include <JavaScriptCore/JSStringRefCF.h>
53 #include <WebKit/WebScriptObject.h>
56 #include <Foundation/Foundation.h>
61 #include <ext/stdio_filebuf.h>
69 #include "Cycript.tab.hh"
71 #include <apr_thread_proc.h>
76 #define _assert(test) do { \
78 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
81 #define _trace() do { \
82 fprintf(stderr, "_trace():%u\n", __LINE__); \
87 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
89 #define CYPoolCatch(value) \
90 @catch (NSException *error) { \
91 _saved = [error retain]; \
97 [_saved autorelease]; \
101 void CYThrow(JSContextRef context, JSValueRef value);
103 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception);
104 JSStringRef CYCopyJSString(const char *value);
106 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value);
108 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)());
109 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
111 /* JavaScript Properties {{{ */
112 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
113 JSValueRef exception(NULL);
114 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
115 CYThrow(context, exception);
119 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
120 JSValueRef exception(NULL);
121 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
122 CYThrow(context, exception);
126 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
127 JSValueRef exception(NULL);
128 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
129 CYThrow(context, exception);
132 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
133 JSValueRef exception(NULL);
134 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
135 CYThrow(context, exception);
138 /* JavaScript Strings {{{ */
139 JSStringRef CYCopyJSString(const char *value) {
140 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
143 JSStringRef CYCopyJSString(JSStringRef value) {
144 return value == NULL ? NULL : JSStringRetain(value);
147 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
148 if (JSValueIsNull(context, value))
150 JSValueRef exception(NULL);
151 JSStringRef string(JSValueToStringCopy(context, value, &exception));
152 CYThrow(context, exception);
162 JSStringRelease(string_);
166 CYJSString(const CYJSString &rhs) :
167 string_(CYCopyJSString(rhs.string_))
171 template <typename Arg0_>
172 CYJSString(Arg0_ arg0) :
173 string_(CYCopyJSString(arg0))
177 template <typename Arg0_, typename Arg1_>
178 CYJSString(Arg0_ arg0, Arg1_ arg1) :
179 string_(CYCopyJSString(arg0, arg1))
183 CYJSString &operator =(const CYJSString &rhs) {
185 string_ = CYCopyJSString(rhs.string_);
198 operator JSStringRef() const {
203 /* Objective-C Strings {{{ */
204 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
206 return [value UTF8String];
208 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
209 char *string(new(pool) char[size]);
210 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
211 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
216 JSStringRef CYCopyJSString_(NSString *value) {
218 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
221 return CYCopyJSString(CYPoolCString(pool, value));
225 JSStringRef CYCopyJSString(id value) {
228 // XXX: this definition scares me; is anyone using this?!
229 NSString *string([value description]);
230 return CYCopyJSString_(string);
234 CFStringRef CYCopyCFString(JSStringRef value) {
235 return JSStringCopyCFString(kCFAllocatorDefault, value);
238 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
239 return CYCopyCFString(CYJSString(context, value));
244 static JSGlobalContextRef Context_;
245 static JSObjectRef System_;
246 static JSObjectRef ObjectiveC_;
248 static JSClassRef Functor_;
249 static JSClassRef Instance_;
250 static JSClassRef Internal_;
251 static JSClassRef Message_;
252 static JSClassRef Messages_;
253 static JSClassRef NSArrayPrototype_;
254 static JSClassRef Pointer_;
255 static JSClassRef Runtime_;
256 static JSClassRef Selector_;
257 static JSClassRef Struct_;
259 static JSClassRef ObjectiveC_Classes_;
260 static JSClassRef ObjectiveC_Image_Classes_;
261 static JSClassRef ObjectiveC_Images_;
262 static JSClassRef ObjectiveC_Protocols_;
264 static JSObjectRef Array_;
265 static JSObjectRef Function_;
266 static JSObjectRef String_;
268 static JSStringRef Result_;
270 static JSStringRef length_;
271 static JSStringRef message_;
272 static JSStringRef name_;
273 static JSStringRef prototype_;
274 static JSStringRef toCYON_;
275 static JSStringRef toJSON_;
277 static JSObjectRef Instance_prototype_;
278 static JSObjectRef Object_prototype_;
280 static JSObjectRef Array_prototype_;
281 static JSObjectRef Array_pop_;
282 static JSObjectRef Array_push_;
283 static JSObjectRef Array_splice_;
286 static Class NSCFBoolean_;
287 static Class NSCFType_;
290 static Class NSArray_;
291 static Class NSDictionary_;
292 static Class NSMessageBuilder_;
293 static Class NSZombie_;
294 static Class Object_;
296 static NSArray *Bridge_;
298 static void Finalize(JSObjectRef object) {
299 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
302 class Type_privateData;
312 CYValue(const void *value) :
313 value_(const_cast<void *>(value))
317 CYValue(const CYValue &rhs) :
322 virtual Type_privateData *GetType() const {
327 struct Selector_privateData :
330 Selector_privateData(SEL value) :
335 SEL GetValue() const {
336 return reinterpret_cast<SEL>(value_);
339 virtual Type_privateData *GetType() const;
342 // XXX: trick this out with associated objects!
343 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
345 return Instance_prototype_;
347 // XXX: I need to think through multi-context
348 typedef std::map<id, JSValueRef> CacheMap;
349 static CacheMap cache_;
351 JSValueRef &value(cache_[self]);
355 JSClassRef _class(NULL);
356 JSValueRef prototype;
358 if (self == NSArray_)
359 prototype = Array_prototype_;
360 else if (self == NSDictionary_)
361 prototype = Object_prototype_;
363 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
365 JSObjectRef object(JSObjectMake(context, _class, NULL));
366 JSObjectSetPrototype(context, object, prototype);
368 JSValueProtect(context, object);
378 Transient = (1 << 0),
379 Uninitialized = (1 << 1),
384 Instance(id value, Flags flags) :
390 virtual ~Instance() {
391 if ((flags_ & Transient) == 0)
392 // XXX: does this handle background threads correctly?
393 // XXX: this simply does not work on the console because I'm stupid
394 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
397 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
398 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
399 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object == nil ? nil : object_getClass(object)));
403 id GetValue() const {
404 return reinterpret_cast<id>(value_);
407 bool IsUninitialized() const {
408 return (flags_ & Uninitialized) != 0;
411 virtual Type_privateData *GetType() const;
417 Messages(Class value) :
422 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
423 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
424 if (_class == NSArray_)
426 if (Class super = class_getSuperclass(_class))
427 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
429 JSObjectSetPrototype(context, value, Array_prototype_);*/
433 Class GetValue() const {
434 return reinterpret_cast<Class>(value_);
442 JSContextRef context_;
446 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
451 JSValueProtect(context_, owner_);
455 JSValueUnprotect(context_, owner_);
458 JSObjectRef GetOwner() const {
466 Internal(id value, JSContextRef context, JSObjectRef owner) :
467 CYOwned(value, context, owner)
471 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
472 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
475 id GetValue() const {
476 return reinterpret_cast<id>(value_);
482 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
484 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
485 lhs.name = apr_pstrdup(pool, rhs.name);
486 if (rhs.type == NULL)
489 lhs.type = new(pool) Type;
490 Copy(pool, *lhs.type, *rhs.type);
492 lhs.offset = rhs.offset;
495 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
496 size_t count(rhs.count);
498 lhs.elements = new(pool) Element[count];
499 for (size_t index(0); index != count; ++index)
500 Copy(pool, lhs.elements[index], rhs.elements[index]);
503 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
504 lhs.primitive = rhs.primitive;
505 lhs.name = apr_pstrdup(pool, rhs.name);
506 lhs.flags = rhs.flags;
508 if (sig::IsAggregate(rhs.primitive))
509 Copy(pool, lhs.data.signature, rhs.data.signature);
511 sig::Type *&lht(lhs.data.data.type);
512 sig::Type *&rht(rhs.data.data.type);
517 lht = new(pool) Type;
518 Copy(pool, *lht, *rht);
521 lhs.data.data.size = rhs.data.data.size;
525 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
527 lhs.alignment = rhs.alignment;
529 if (rhs.elements == NULL)
533 while (rhs.elements[count] != NULL)
536 lhs.elements = new(pool) ffi_type *[count + 1];
537 lhs.elements[count] = NULL;
539 for (size_t index(0); index != count; ++index) {
540 // XXX: if these are libffi native then you can just take them
541 ffi_type *ffi(new(pool) ffi_type);
542 lhs.elements[index] = ffi;
543 sig::Copy(pool, *ffi, *rhs.elements[index]);
550 struct CStringMapLess :
551 std::binary_function<const char *, const char *, bool>
553 _finline bool operator ()(const char *lhs, const char *rhs) const {
554 return strcmp(lhs, rhs) < 0;
558 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
563 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
564 switch ([[entry objectAtIndex:0] intValue]) {
566 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
570 sig::Signature signature;
571 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
572 type = signature.elements[0].type;
578 struct Type_privateData :
581 static Type_privateData *Object;
582 static Type_privateData *Selector;
584 static JSClassRef Class_;
589 void Set(sig::Type *type) {
590 type_ = new(pool_) sig::Type;
591 sig::Copy(pool_, *type_, *type);
594 Type_privateData(apr_pool_t *pool, const char *type) :
600 sig::Signature signature;
601 sig::Parse(pool_, &signature, type, &Structor_);
602 type_ = signature.elements[0].type;
605 Type_privateData(sig::Type *type) :
612 Type_privateData(sig::Type *type, ffi_type *ffi) {
613 ffi_ = new(pool_) ffi_type;
614 sig::Copy(pool_, *ffi_, *ffi);
620 ffi_ = new(pool_) ffi_type;
622 sig::Element element;
624 element.type = type_;
627 sig::Signature signature;
628 signature.elements = &element;
632 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
640 JSClassRef Type_privateData::Class_;
641 Type_privateData *Type_privateData::Object;
642 Type_privateData *Type_privateData::Selector;
644 Type_privateData *Instance::GetType() const {
645 return Type_privateData::Object;
648 Type_privateData *Selector_privateData::GetType() const {
649 return Type_privateData::Selector;
655 Type_privateData *type_;
657 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
658 CYOwned(value, context, owner),
659 type_(new(pool_) Type_privateData(type))
664 struct Struct_privateData :
667 Type_privateData *type_;
669 Struct_privateData(JSContextRef context, JSObjectRef owner) :
670 CYOwned(NULL, context, owner)
675 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
676 static TypeMap Types_;
678 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
679 Struct_privateData *internal(new Struct_privateData(context, owner));
680 apr_pool_t *pool(internal->pool_);
681 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
682 internal->type_ = typical;
685 internal->value_ = data;
687 size_t size(typical->GetFFI()->size);
688 void *copy(apr_palloc(internal->pool_, size));
689 memcpy(copy, data, size);
690 internal->value_ = copy;
693 return JSObjectMake(context, Struct_, internal);
696 struct Functor_privateData :
699 sig::Signature signature_;
703 Functor_privateData(const char *type, void (*value)()) :
704 CYValue(reinterpret_cast<void *>(value))
706 sig::Parse(pool_, &signature_, type, &Structor_);
707 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
710 void (*GetValue())() const {
711 return reinterpret_cast<void (*)()>(value_);
715 struct Closure_privateData :
718 JSContextRef context_;
719 JSObjectRef function_;
721 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
722 Functor_privateData(type, NULL),
726 JSValueProtect(context_, function_);
729 virtual ~Closure_privateData() {
730 JSValueUnprotect(context_, function_);
734 struct Message_privateData :
739 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
740 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
746 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
747 Instance::Flags flags;
750 flags = Instance::Transient;
752 flags = Instance::None;
753 object = [object retain];
756 return Instance::Make(context, object, flags);
759 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
760 return JSValueMakeBoolean(context, value);
763 JSValueRef CYCastJSValue(JSContextRef context, double value) {
764 return JSValueMakeNumber(context, value);
767 #define CYCastJSValue_(Type_) \
768 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
769 return JSValueMakeNumber(context, static_cast<double>(value)); \
773 CYCastJSValue_(unsigned int)
774 CYCastJSValue_(long int)
775 CYCastJSValue_(long unsigned int)
776 CYCastJSValue_(long long int)
777 CYCastJSValue_(long long unsigned int)
779 JSValueRef CYJSUndefined(JSContextRef context) {
780 return JSValueMakeUndefined(context);
783 size_t CYGetIndex(const char *value) {
784 if (value[0] != '0') {
786 size_t index(strtoul(value, &end, 10));
787 if (value + strlen(value) == end)
789 } else if (value[1] == '\0')
795 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value);
797 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
798 return CYGetIndex(CYPoolCString(pool, value));
801 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
802 return CYGetIndex(CYPoolCString(pool, value));
805 bool CYGetOffset(const char *value, ssize_t &index) {
806 if (value[0] != '0') {
808 index = strtol(value, &end, 10);
809 if (value + strlen(value) == end)
811 } else if (value[1] == '\0') {
819 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
820 return CYGetOffset(CYPoolCString(pool, value), index);
823 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
825 @interface NSMethodSignature (Cycript)
826 - (NSString *) _typeString;
829 @interface NSObject (Cycript)
831 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
832 - (JSType) cy$JSType;
834 - (NSObject *) cy$toJSON:(NSString *)key;
835 - (NSString *) cy$toCYON;
836 - (NSString *) cy$toKey;
838 - (bool) cy$hasProperty:(NSString *)name;
839 - (NSObject *) cy$getProperty:(NSString *)name;
840 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
841 - (bool) cy$deleteProperty:(NSString *)name;
846 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
849 @interface NSString (Cycript)
850 - (void *) cy$symbol;
854 struct PropertyAttributes {
859 const char *variable;
872 PropertyAttributes(objc_property_t property) :
884 name = property_getName(property);
885 const char *attributes(property_getAttributes(property));
887 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
889 case 'R': readonly = true; break;
890 case 'C': copy = true; break;
891 case '&': retain = true; break;
892 case 'N': nonatomic = true; break;
893 case 'G': getter_ = token + 1; break;
894 case 'S': setter_ = token + 1; break;
895 case 'V': variable = token + 1; break;
899 /*if (variable == NULL) {
900 variable = property_getName(property);
901 size_t size(strlen(variable));
902 char *name(new(pool_) char[size + 2]);
904 memcpy(name + 1, variable, size);
905 name[size + 1] = '\0';
910 const char *Getter() {
912 getter_ = apr_pstrdup(pool_, name);
916 const char *Setter() {
917 if (setter_ == NULL && !readonly) {
918 size_t length(strlen(name));
920 char *temp(new(pool_) char[length + 5]);
926 temp[3] = toupper(name[0]);
927 memcpy(temp + 4, name + 1, length - 1);
930 temp[length + 3] = ':';
931 temp[length + 4] = '\0';
942 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
943 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
948 @interface CYWebUndefined : NSObject {
951 + (CYWebUndefined *) undefined;
955 @implementation CYWebUndefined
957 + (CYWebUndefined *) undefined {
958 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
964 #define WebUndefined CYWebUndefined
967 /* Bridge: NSArray {{{ */
968 @implementation NSArray (Cycript)
970 - (NSString *) cy$toCYON {
971 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
972 [json appendString:@"["];
976 for (id object in self) {
979 for (size_t index(0), count([self count]); index != count; ++index) {
980 object = [self objectAtIndex:index];
983 [json appendString:@","];
986 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
987 [json appendString:CYPoolNSCYON(NULL, object)];
989 [json appendString:@","];
994 [json appendString:@"]"];
998 - (bool) cy$hasProperty:(NSString *)name {
999 if ([name isEqualToString:@"length"])
1002 size_t index(CYGetIndex(NULL, name));
1003 if (index == _not(size_t) || index >= [self count])
1004 return [super cy$hasProperty:name];
1009 - (NSObject *) cy$getProperty:(NSString *)name {
1010 if ([name isEqualToString:@"length"]) {
1011 NSUInteger count([self count]);
1013 return [NSNumber numberWithUnsignedInteger:count];
1015 return [NSNumber numberWithUnsignedInt:count];
1019 size_t index(CYGetIndex(NULL, name));
1020 if (index == _not(size_t) || index >= [self count])
1021 return [super cy$getProperty:name];
1023 return [self objectAtIndex:index];
1028 /* Bridge: NSDictionary {{{ */
1029 @implementation NSDictionary (Cycript)
1031 - (NSString *) cy$toCYON {
1032 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1033 [json appendString:@"{"];
1037 for (id key in self) {
1039 NSEnumerator *keys([self keyEnumerator]);
1040 while (id key = [keys nextObject]) {
1043 [json appendString:@","];
1046 [json appendString:[key cy$toKey]];
1047 [json appendString:@":"];
1048 NSObject *object([self objectForKey:key]);
1049 [json appendString:CYPoolNSCYON(NULL, object)];
1052 [json appendString:@"}"];
1056 - (bool) cy$hasProperty:(NSString *)name {
1057 return [self objectForKey:name] != nil;
1060 - (NSObject *) cy$getProperty:(NSString *)name {
1061 return [self objectForKey:name];
1066 /* Bridge: NSMutableArray {{{ */
1067 @implementation NSMutableArray (Cycript)
1069 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1070 if ([name isEqualToString:@"length"]) {
1071 // XXX: is this not intelligent?
1072 NSNumber *number(reinterpret_cast<NSNumber *>(value));
1074 NSUInteger size([number unsignedIntegerValue]);
1076 NSUInteger size([number unsignedIntValue]);
1078 NSUInteger count([self count]);
1080 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1081 else if (size != count) {
1082 WebUndefined *undefined([WebUndefined undefined]);
1083 for (size_t i(count); i != size; ++i)
1084 [self addObject:undefined];
1089 size_t index(CYGetIndex(NULL, name));
1090 if (index == _not(size_t))
1091 return [super cy$setProperty:name to:value];
1093 id object(value ?: [NSNull null]);
1095 size_t count([self count]);
1097 [self replaceObjectAtIndex:index withObject:object];
1099 if (index != count) {
1100 WebUndefined *undefined([WebUndefined undefined]);
1101 for (size_t i(count); i != index; ++i)
1102 [self addObject:undefined];
1105 [self addObject:object];
1111 - (bool) cy$deleteProperty:(NSString *)name {
1112 size_t index(CYGetIndex(NULL, name));
1113 if (index == _not(size_t) || index >= [self count])
1114 return [super cy$deleteProperty:name];
1115 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1121 /* Bridge: NSMutableDictionary {{{ */
1122 @implementation NSMutableDictionary (Cycript)
1124 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1125 [self setObject:(value ?: [NSNull null]) forKey:name];
1129 - (bool) cy$deleteProperty:(NSString *)name {
1130 if ([self objectForKey:name] == nil)
1133 [self removeObjectForKey:name];
1140 /* Bridge: NSNumber {{{ */
1141 @implementation NSNumber (Cycript)
1143 - (JSType) cy$JSType {
1145 // XXX: this just seems stupid
1146 if ([self class] == NSCFBoolean_)
1147 return kJSTypeBoolean;
1149 return kJSTypeNumber;
1152 - (NSObject *) cy$toJSON:(NSString *)key {
1156 - (NSString *) cy$toCYON {
1157 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1160 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1161 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1166 /* Bridge: NSNull {{{ */
1167 @implementation NSNull (Cycript)
1169 - (JSType) cy$JSType {
1173 - (NSObject *) cy$toJSON:(NSString *)key {
1177 - (NSString *) cy$toCYON {
1183 /* Bridge: NSObject {{{ */
1184 @implementation NSObject (Cycript)
1186 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1187 return CYMakeInstance(context, self, false);
1190 - (JSType) cy$JSType {
1191 return kJSTypeObject;
1194 - (NSObject *) cy$toJSON:(NSString *)key {
1195 return [self description];
1198 - (NSString *) cy$toCYON {
1199 return [[self cy$toJSON:@""] cy$toCYON];
1202 - (NSString *) cy$toKey {
1203 return [self cy$toCYON];
1206 - (bool) cy$hasProperty:(NSString *)name {
1210 - (NSObject *) cy$getProperty:(NSString *)name {
1214 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1218 - (bool) cy$deleteProperty:(NSString *)name {
1224 /* Bridge: NSProxy {{{ */
1225 @implementation NSProxy (Cycript)
1227 - (NSObject *) cy$toJSON:(NSString *)key {
1228 return [self description];
1231 - (NSString *) cy$toCYON {
1232 return [[self cy$toJSON:@""] cy$toCYON];
1237 /* Bridge: NSString {{{ */
1238 @implementation NSString (Cycript)
1240 - (JSType) cy$JSType {
1241 return kJSTypeString;
1244 - (NSObject *) cy$toJSON:(NSString *)key {
1248 - (NSString *) cy$toCYON {
1249 // XXX: this should use the better code from Output.cpp
1251 NSMutableString *json([self mutableCopy]);
1253 [json replaceOccurrencesOfString:@"\\" withString:@"\\\\" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
1254 [json replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
1255 [json replaceOccurrencesOfString:@"\t" withString:@"\\t" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
1256 [json replaceOccurrencesOfString:@"\r" withString:@"\\r" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
1257 [json replaceOccurrencesOfString:@"\n" withString:@"\\n" options:NSLiteralSearch range:NSMakeRange(0, [json length])];
1259 [json appendString:@"\""];
1260 [json insertString:@"\"" atIndex:0];
1265 - (NSString *) cy$toKey {
1266 const char *value([self UTF8String]);
1267 size_t size(strlen(value));
1272 if (DigitRange_[value[0]]) {
1273 size_t index(CYGetIndex(NULL, self));
1274 if (index == _not(size_t))
1277 if (!WordStartRange_[value[0]])
1279 for (size_t i(1); i != size; ++i)
1280 if (!WordEndRange_[value[i]])
1287 return [self cy$toCYON];
1290 - (void *) cy$symbol {
1292 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1297 /* Bridge: WebUndefined {{{ */
1298 @implementation WebUndefined (Cycript)
1300 - (JSType) cy$JSType {
1301 return kJSTypeUndefined;
1304 - (NSObject *) cy$toJSON:(NSString *)key {
1308 - (NSString *) cy$toCYON {
1309 return @"undefined";
1312 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1313 return CYJSUndefined(context);
1319 /* Bridge: CYJSObject {{{ */
1320 @interface CYJSObject : NSMutableDictionary {
1321 JSObjectRef object_;
1322 JSContextRef context_;
1325 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1327 - (NSObject *) cy$toJSON:(NSString *)key;
1329 - (NSUInteger) count;
1330 - (id) objectForKey:(id)key;
1331 - (NSEnumerator *) keyEnumerator;
1332 - (void) setObject:(id)object forKey:(id)key;
1333 - (void) removeObjectForKey:(id)key;
1337 /* Bridge: CYJSArray {{{ */
1338 @interface CYJSArray : NSMutableArray {
1339 JSObjectRef object_;
1340 JSContextRef context_;
1343 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1345 - (NSUInteger) count;
1346 - (id) objectAtIndex:(NSUInteger)index;
1348 - (void) addObject:(id)anObject;
1349 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1350 - (void) removeLastObject;
1351 - (void) removeObjectAtIndex:(NSUInteger)index;
1352 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1360 @catch (id error) { \
1361 CYThrow(context, error, exception); \
1365 apr_status_t CYPoolRelease_(void *data) {
1366 id object(reinterpret_cast<id>(data));
1371 id CYPoolRelease_(apr_pool_t *pool, id object) {
1374 else if (pool == NULL)
1375 return [object autorelease];
1377 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1382 template <typename Type_>
1383 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
1384 return (Type_) CYPoolRelease_(pool, (id) object);
1387 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1388 JSValueRef exception(NULL);
1389 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1390 CYThrow(context, exception);
1391 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1392 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1395 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1396 if (!JSValueIsObjectOfClass(context, object, Instance_))
1397 return CYCastNSObject_(pool, context, object);
1399 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1400 return internal->GetValue();
1404 double CYCastDouble(const char *value, size_t size) {
1406 double number(strtod(value, &end));
1407 if (end != value + size)
1412 double CYCastDouble(const char *value) {
1413 return CYCastDouble(value, strlen(value));
1416 double CYCastDouble(JSContextRef context, JSValueRef value) {
1417 JSValueRef exception(NULL);
1418 double number(JSValueToNumber(context, value, &exception));
1419 CYThrow(context, exception);
1424 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1425 double number(CYCastDouble(context, value));
1426 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1429 CFStringRef CYCopyCFString(const char *value) {
1430 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1433 template <typename Type_>
1434 NSString *CYCopyNSString(Type_ value) {
1435 return (NSString *) CYCopyCFString(value);
1438 NSString *CYCopyNSString(const char *value {
1439 return [NSString stringWithUTF8String:value];
1442 NSString *CYCopyNSString(JSStringRef value) {
1443 return CYCopyNSString(CYCastCString_(value));
1447 template <typename Type_>
1448 NSString *CYCastNSString(apr_pool_t *pool, Type_ value) {
1449 return CYPoolRelease(pool, CYCopyNSString(value));
1452 bool CYCastBool(JSContextRef context, JSValueRef value) {
1453 return JSValueToBoolean(context, value);
1457 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1461 switch (JSType type = JSValueGetType(context, value)) {
1462 case kJSTypeUndefined:
1463 object = [WebUndefined undefined];
1471 case kJSTypeBoolean:
1472 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1477 object = CYCopyCFNumber(context, value);
1482 object = CYCopyCFString(context, value);
1487 // XXX: this might could be more efficient
1488 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1493 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1500 return CYPoolRelease(pool, object);
1502 return CFRetain(object);
1505 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1506 return CYCFType(pool, context, value, true);
1509 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1510 return CYCFType(pool, context, value, false);
1514 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1516 size_t size(JSPropertyNameArrayGetCount(names));
1517 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1518 for (size_t index(0); index != size; ++index)
1519 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1523 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1524 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1527 void CYThrow(JSContextRef context, JSValueRef value) {
1530 @throw CYCastNSObject(NULL, context, value);
1533 JSValueRef CYJSNull(JSContextRef context) {
1534 return JSValueMakeNull(context);
1537 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1538 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1541 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1542 return CYCastJSValue(context, CYJSString(value));
1545 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1547 return CYJSNull(context);
1548 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1549 return [value cy$JSValueInContext:context];
1551 return CYMakeInstance(context, value, false);
1554 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1555 JSValueRef exception(NULL);
1556 JSObjectRef object(JSValueToObject(context, value, &exception));
1557 CYThrow(context, exception);
1561 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1562 if (exception == NULL)
1564 *exception = CYCastJSValue(context, error);
1567 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1568 JSValueRef exception(NULL);
1569 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1570 CYThrow(context, exception);
1574 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1575 // XXX: this isn't actually correct
1576 return value != NULL && JSValueIsObject(context, value);
1579 @implementation CYJSObject
1581 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1582 if ((self = [super init]) != nil) {
1585 JSValueProtect(context_, object_);
1590 JSValueUnprotect(context_, object_);
1594 - (NSObject *) cy$toJSON:(NSString *)key {
1595 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1596 if (!CYIsCallable(context_, toJSON))
1597 return [super cy$toJSON:key];
1599 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1600 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1601 // XXX: do I really want an NSNull here?!
1602 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1606 - (NSString *) cy$toCYON {
1607 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1608 if (!CYIsCallable(context_, toCYON)) super:
1609 return [super cy$toCYON];
1610 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1611 return CYCastNSString(NULL, CYJSString(context_, value));
1615 - (NSUInteger) count {
1616 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1617 size_t size(JSPropertyNameArrayGetCount(names));
1618 JSPropertyNameArrayRelease(names);
1622 - (id) objectForKey:(id)key {
1623 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1624 if (JSValueIsUndefined(context_, value))
1626 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1629 - (NSEnumerator *) keyEnumerator {
1630 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1631 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1632 JSPropertyNameArrayRelease(names);
1636 - (void) setObject:(id)object forKey:(id)key {
1637 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1640 - (void) removeObjectForKey:(id)key {
1641 JSValueRef exception(NULL);
1642 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1643 CYThrow(context_, exception);
1648 @implementation CYJSArray
1650 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1651 if ((self = [super init]) != nil) {
1654 JSValueProtect(context_, object_);
1659 JSValueUnprotect(context_, object_);
1663 - (NSUInteger) count {
1664 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1667 - (id) objectAtIndex:(NSUInteger)index {
1668 size_t bounds([self count]);
1669 if (index >= bounds)
1670 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1671 JSValueRef exception(NULL);
1672 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1673 CYThrow(context_, exception);
1674 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1677 - (void) addObject:(id)object {
1678 JSValueRef exception(NULL);
1679 JSValueRef arguments[1];
1680 arguments[0] = CYCastJSValue(context_, object);
1681 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1682 CYThrow(context_, exception);
1685 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1686 size_t bounds([self count] + 1);
1687 if (index >= bounds)
1688 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1689 JSValueRef exception(NULL);
1690 JSValueRef arguments[3];
1691 arguments[0] = CYCastJSValue(context_, index);
1692 arguments[1] = CYCastJSValue(context_, 0);
1693 arguments[2] = CYCastJSValue(context_, object);
1694 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1695 CYThrow(context_, exception);
1698 - (void) removeLastObject {
1699 JSValueRef exception(NULL);
1700 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1701 CYThrow(context_, exception);
1704 - (void) removeObjectAtIndex:(NSUInteger)index {
1705 size_t bounds([self count]);
1706 if (index >= bounds)
1707 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1708 JSValueRef exception(NULL);
1709 JSValueRef arguments[2];
1710 arguments[0] = CYCastJSValue(context_, index);
1711 arguments[1] = CYCastJSValue(context_, 1);
1712 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1713 CYThrow(context_, exception);
1716 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1717 size_t bounds([self count]);
1718 if (index >= bounds)
1719 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1720 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1725 NSString *CYCopyNSCYON(id value) {
1731 Class _class(object_getClass(value));
1732 SEL sel(@selector(cy$toCYON));
1734 if (Method toCYON = class_getInstanceMethod(_class, sel))
1735 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1736 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1737 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1738 string = [value cy$toCYON];
1741 if (value == NSZombie_)
1742 string = @"_NSZombie_";
1743 else if (_class == NSZombie_)
1744 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1745 // XXX: frowny /in/ the pants
1746 else if (value == NSMessageBuilder_ || value == Object_)
1749 string = [NSString stringWithFormat:@"%@", value];
1752 // XXX: frowny pants
1754 string = @"undefined";
1757 return [string retain];
1760 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1761 if (JSValueIsNull(context, value))
1762 return [@"null" retain];
1766 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1771 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1772 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1775 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1776 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1777 const char *string(CYPoolCString(pool, json));
1783 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1787 JSObjectRef object_;
1795 // XXX: delete object_? ;(
1798 static CYInternal *Get(id self) {
1799 CYInternal *internal(NULL);
1800 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1801 // XXX: do something epic? ;P
1807 static CYInternal *Set(id self) {
1808 CYInternal *internal(NULL);
1809 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1810 if (internal == NULL) {
1811 internal = new CYInternal();
1812 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1815 // XXX: do something epic? ;P
1821 bool HasProperty(JSContextRef context, JSStringRef name) {
1822 if (object_ == NULL)
1824 return JSObjectHasProperty(context, object_, name);
1827 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1828 if (object_ == NULL)
1830 return CYGetProperty(context, object_, name);
1833 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1834 if (object_ == NULL)
1835 object_ = JSObjectMake(context, NULL, NULL);
1836 CYSetProperty(context, object_, name, value);
1840 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1841 Selector_privateData *internal(new Selector_privateData(sel));
1842 return JSObjectMake(context, Selector_, internal);
1845 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1846 Pointer *internal(new Pointer(pointer, context, owner, type));
1847 return JSObjectMake(context, Pointer_, internal);
1850 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1851 Functor_privateData *internal(new Functor_privateData(type, function));
1852 return JSObjectMake(context, Functor_, internal);
1855 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1857 // XXX: this could be much more efficient
1858 const char *string([CYCastNSString(NULL, value) UTF8String]);
1861 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1862 char *string(new(pool) char[size]);
1863 JSStringGetUTF8CString(value, string, size);
1868 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1869 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1872 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1873 return CYGetOffset(CYPoolCString(pool, value), index);
1876 // XXX: this macro is unhygenic
1877 #define CYCastCString_(string) ({ \
1879 if (string == NULL) \
1882 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1883 utf8 = reinterpret_cast<char *>(alloca(size)); \
1884 JSStringGetUTF8CString(string, utf8, size); \
1889 // XXX: this macro is unhygenic
1890 #define CYCastCString(context, value) ({ \
1892 if (value == NULL) \
1894 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1895 utf8 = CYCastCString_(string); \
1896 JSStringRelease(string); \
1902 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1903 switch (JSValueGetType(context, value)) {
1906 /*case kJSTypeString:
1907 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1909 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1910 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1911 return internal->value_;
1914 double number(CYCastDouble(context, value));
1915 if (std::isnan(number))
1916 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1917 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1921 template <typename Type_>
1922 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1923 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1926 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1927 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1928 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1929 return reinterpret_cast<SEL>(internal->value_);
1931 return CYCastPointer<SEL>(context, value);
1934 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1935 switch (type->primitive) {
1936 case sig::boolean_P:
1937 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1940 #define CYPoolFFI_(primitive, native) \
1941 case sig::primitive ## _P: \
1942 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1945 CYPoolFFI_(uchar, unsigned char)
1946 CYPoolFFI_(char, char)
1947 CYPoolFFI_(ushort, unsigned short)
1948 CYPoolFFI_(short, short)
1949 CYPoolFFI_(ulong, unsigned long)
1950 CYPoolFFI_(long, long)
1951 CYPoolFFI_(uint, unsigned int)
1952 CYPoolFFI_(int, int)
1953 CYPoolFFI_(ulonglong, unsigned long long)
1954 CYPoolFFI_(longlong, long long)
1955 CYPoolFFI_(float, float)
1956 CYPoolFFI_(double, double)
1959 case sig::typename_P:
1960 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1963 case sig::selector_P:
1964 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1967 case sig::pointer_P:
1968 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1972 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1975 case sig::struct_P: {
1976 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1977 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1978 for (size_t index(0); index != type->data.signature.count; ++index) {
1979 sig::Element *element(&type->data.signature.elements[index]);
1980 ffi_type *field(ffi->elements[index]);
1983 if (aggregate == NULL)
1986 rhs = CYGetProperty(context, aggregate, index);
1987 if (JSValueIsUndefined(context, rhs)) {
1988 if (element->name != NULL)
1989 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1992 if (JSValueIsUndefined(context, rhs)) undefined:
1993 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1997 CYPoolFFI(pool, context, element->type, field, base, rhs);
1999 base += field->size;
2007 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
2012 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
2015 switch (type->primitive) {
2016 case sig::boolean_P:
2017 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
2020 #define CYFromFFI_(primitive, native) \
2021 case sig::primitive ## _P: \
2022 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
2025 CYFromFFI_(uchar, unsigned char)
2026 CYFromFFI_(char, char)
2027 CYFromFFI_(ushort, unsigned short)
2028 CYFromFFI_(short, short)
2029 CYFromFFI_(ulong, unsigned long)
2030 CYFromFFI_(long, long)
2031 CYFromFFI_(uint, unsigned int)
2032 CYFromFFI_(int, int)
2033 CYFromFFI_(ulonglong, unsigned long long)
2034 CYFromFFI_(longlong, long long)
2035 CYFromFFI_(float, float)
2036 CYFromFFI_(double, double)
2038 case sig::object_P: {
2039 if (id object = *reinterpret_cast<id *>(data)) {
2040 value = CYCastJSValue(context, object);
2046 case sig::typename_P:
2047 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
2050 case sig::selector_P:
2051 if (SEL sel = *reinterpret_cast<SEL *>(data))
2052 value = CYMakeSelector(context, sel);
2056 case sig::pointer_P:
2057 if (void *pointer = *reinterpret_cast<void **>(data))
2058 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
2063 if (char *utf8 = *reinterpret_cast<char **>(data))
2064 value = CYCastJSValue(context, utf8);
2069 value = CYMakeStruct(context, data, type, ffi, owner);
2073 value = CYJSUndefined(context);
2077 value = CYJSNull(context);
2081 NSLog(@"CYFromFFI(%c)\n", type->primitive);
2088 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
2089 if (Method method = class_getInstanceMethod(_class, selector)) {
2093 method_getReturnType(method, type, sizeof(type));
2098 // XXX: possibly use a more "awesome" check?
2102 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
2104 return method_getTypeEncoding(method);
2105 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2106 return CYPoolCString(pool, type);
2111 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2112 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2114 JSContextRef context(internal->context_);
2116 size_t count(internal->cif_.nargs);
2117 JSValueRef values[count];
2119 for (size_t index(0); index != count; ++index)
2120 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2122 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2123 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2126 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2127 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2129 JSContextRef context(internal->context_);
2131 size_t count(internal->cif_.nargs);
2132 JSValueRef values[count];
2134 for (size_t index(0); index != count; ++index)
2135 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2137 JSObjectRef _this(CYCastJSObject(context, values[0]));
2139 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2140 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2143 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2144 // XXX: in case of exceptions this will leak
2145 // XXX: in point of fact, this may /need/ to leak :(
2146 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2148 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2149 NULL, sizeof(ffi_closure),
2150 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2154 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2155 _assert(status == FFI_OK);
2157 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2159 internal->value_ = closure;
2164 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2165 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2166 return JSObjectMake(context, Functor_, internal);
2169 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2170 JSValueRef exception(NULL);
2171 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2172 CYThrow(context, exception);
2175 JSObjectRef function(CYCastJSObject(context, value));
2176 return CYMakeFunctor(context, function, type);
2178 void (*function)()(CYCastPointer<void (*)()>(context, value));
2179 return CYMakeFunctor(context, function, type);
2183 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2184 Message_privateData *internal(new Message_privateData(sel, type, imp));
2185 return JSObjectMake(context, Message_, internal);
2188 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2189 JSObjectRef function(CYCastJSObject(context, value));
2190 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2191 return reinterpret_cast<IMP>(internal->GetValue());
2194 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2195 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2196 Class _class(internal->GetValue());
2199 const char *name(CYPoolCString(pool, property));
2201 if (SEL sel = sel_getUid(name))
2202 if (class_getInstanceMethod(_class, sel) != NULL)
2208 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2209 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2210 Class _class(internal->GetValue());
2213 const char *name(CYPoolCString(pool, property));
2215 if (SEL sel = sel_getUid(name))
2216 if (Method method = class_getInstanceMethod(_class, sel))
2217 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2222 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2223 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2224 Class _class(internal->GetValue());
2227 const char *name(CYPoolCString(pool, property));
2229 SEL sel(sel_registerName(name));
2231 Method method(class_getInstanceMethod(_class, sel));
2236 if (JSValueIsObjectOfClass(context, value, Message_)) {
2237 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2238 type = sig::Unparse(pool, &message->signature_);
2239 imp = reinterpret_cast<IMP>(message->GetValue());
2241 type = CYPoolTypeEncoding(pool, _class, sel, method);
2242 imp = CYMakeMessage(context, value, type);
2246 method_setImplementation(method, imp);
2248 class_replaceMethod(_class, sel, imp, type);
2254 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2255 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2256 Class _class(internal->GetValue());
2259 const char *name(CYPoolCString(pool, property));
2261 if (SEL sel = sel_getUid(name))
2262 if (Method method = class_getInstanceMethod(_class, sel)) {
2263 objc_method_list list = {NULL, 1, {method}};
2264 class_removeMethods(_class, &list);
2272 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2273 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2274 Class _class(internal->GetValue());
2277 Method *data(class_copyMethodList(_class, &size));
2278 for (size_t i(0); i != size; ++i)
2279 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2283 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2284 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2285 id self(internal->GetValue());
2287 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2291 NSString *name(CYCastNSString(pool, property));
2293 if (CYInternal *internal = CYInternal::Get(self))
2294 if (internal->HasProperty(context, property))
2297 Class _class(object_getClass(self));
2300 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2301 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2302 if ([self cy$hasProperty:name])
2304 } CYPoolCatch(false)
2306 const char *string(CYPoolCString(pool, name));
2308 if (class_getProperty(_class, string) != NULL)
2311 if (SEL sel = sel_getUid(string))
2312 if (CYImplements(self, _class, sel, true))
2318 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2319 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2320 id self(internal->GetValue());
2322 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2323 return Internal::Make(context, self, object);
2327 NSString *name(CYCastNSString(pool, property));
2329 if (CYInternal *internal = CYInternal::Get(self))
2330 if (JSValueRef value = internal->GetProperty(context, property))
2334 if (NSObject *data = [self cy$getProperty:name])
2335 return CYCastJSValue(context, data);
2338 const char *string(CYPoolCString(pool, name));
2339 Class _class(object_getClass(self));
2342 if (objc_property_t property = class_getProperty(_class, string)) {
2343 PropertyAttributes attributes(property);
2344 SEL sel(sel_registerName(attributes.Getter()));
2345 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2349 if (SEL sel = sel_getUid(string))
2350 if (CYImplements(self, _class, sel, true))
2351 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2357 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2358 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2359 id self(internal->GetValue());
2364 NSString *name(CYCastNSString(pool, property));
2365 NSString *data(CYCastNSObject(pool, context, value));
2368 if ([self cy$setProperty:name to:data])
2372 const char *string(CYPoolCString(pool, name));
2373 Class _class(object_getClass(self));
2376 if (objc_property_t property = class_getProperty(_class, string)) {
2377 PropertyAttributes attributes(property);
2378 if (const char *setter = attributes.Setter()) {
2379 SEL sel(sel_registerName(setter));
2380 JSValueRef arguments[1] = {value};
2381 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2387 size_t length(strlen(string));
2389 char set[length + 5];
2395 if (string[0] != '\0') {
2396 set[3] = toupper(string[0]);
2397 memcpy(set + 4, string + 1, length - 1);
2400 set[length + 3] = ':';
2401 set[length + 4] = '\0';
2403 if (SEL sel = sel_getUid(set))
2404 if (CYImplements(self, _class, sel, false)) {
2405 JSValueRef arguments[1] = {value};
2406 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2409 if (CYInternal *internal = CYInternal::Set(self)) {
2410 internal->SetProperty(context, property, value);
2418 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2419 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2420 id self(internal->GetValue());
2424 NSString *name(CYCastNSString(NULL, property));
2425 return [self cy$deleteProperty:name];
2430 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2431 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2432 id self(internal->GetValue());
2435 Class _class(object_getClass(self));
2439 objc_property_t *data(class_copyPropertyList(_class, &size));
2440 for (size_t i(0); i != size; ++i)
2441 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2446 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2448 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2449 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2454 static bool CYIsClass(id self) {
2455 // XXX: this is a lame object_isClass
2456 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2459 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2460 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2461 Class _class(internal->GetValue());
2462 if (!CYIsClass(_class))
2465 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2466 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2467 // XXX: this isn't always safe
2469 return [linternal->GetValue() isKindOfClass:_class];
2476 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2477 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2480 id self(internal->GetValue());
2481 const char *name(CYPoolCString(pool, property));
2483 if (object_getInstanceVariable(self, name, NULL) != NULL)
2489 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2490 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2494 id self(internal->GetValue());
2495 const char *name(CYPoolCString(pool, property));
2497 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2498 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2499 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2506 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2507 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2511 id self(internal->GetValue());
2512 const char *name(CYPoolCString(pool, property));
2514 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2515 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2516 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2524 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2525 if (Class super = class_getSuperclass(_class))
2526 Internal_getPropertyNames_(super, names);
2529 Ivar *data(class_copyIvarList(_class, &size));
2530 for (size_t i(0); i != size; ++i)
2531 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2535 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2536 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2539 id self(internal->GetValue());
2540 Class _class(object_getClass(self));
2542 Internal_getPropertyNames_(_class, names);
2545 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2546 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2547 return internal->GetOwner();
2550 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2551 Type_privateData *typical(internal->type_);
2552 sig::Type *type(typical->type_);
2556 const char *name(CYPoolCString(pool, property));
2557 size_t length(strlen(name));
2558 double number(CYCastDouble(name, length));
2560 size_t count(type->data.signature.count);
2562 if (std::isnan(number)) {
2563 if (property == NULL)
2566 sig::Element *elements(type->data.signature.elements);
2568 for (size_t local(0); local != count; ++local) {
2569 sig::Element *element(&elements[local]);
2570 if (element->name != NULL && strcmp(name, element->name) == 0) {
2578 index = static_cast<ssize_t>(number);
2579 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2584 ffi_type **elements(typical->GetFFI()->elements);
2586 base = reinterpret_cast<uint8_t *>(internal->value_);
2587 for (ssize_t local(0); local != index; ++local)
2588 base += elements[local]->size;
2593 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2594 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2595 Type_privateData *typical(internal->type_);
2597 ffi_type *ffi(typical->GetFFI());
2599 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2600 base += ffi->size * index;
2602 JSObjectRef owner(internal->GetOwner() ?: object);
2605 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2609 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2611 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2612 Type_privateData *typical(internal->type_);
2614 if (typical->type_ == NULL)
2618 if (!CYGetOffset(pool, property, offset))
2621 return Pointer_getIndex(context, object, offset, exception);
2624 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2625 return Pointer_getIndex(context, object, 0, exception);
2628 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2629 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2630 Type_privateData *typical(internal->type_);
2632 ffi_type *ffi(typical->GetFFI());
2634 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2635 base += ffi->size * index;
2638 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2643 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2645 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2646 Type_privateData *typical(internal->type_);
2648 if (typical->type_ == NULL)
2652 if (!CYGetOffset(pool, property, offset))
2655 return Pointer_setIndex(context, object, offset, value, exception);
2658 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2659 return Pointer_setIndex(context, object, 0, value, exception);
2662 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2663 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2664 Type_privateData *typical(internal->type_);
2665 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2668 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2670 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2671 Type_privateData *typical(internal->type_);
2676 if (!Index_(pool, internal, property, index, base))
2679 JSObjectRef owner(internal->GetOwner() ?: object);
2682 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2686 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2688 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2689 Type_privateData *typical(internal->type_);
2694 if (!Index_(pool, internal, property, index, base))
2698 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2703 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2704 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2705 Type_privateData *typical(internal->type_);
2706 sig::Type *type(typical->type_);
2711 size_t count(type->data.signature.count);
2712 sig::Element *elements(type->data.signature.elements);
2716 for (size_t index(0); index != count; ++index) {
2718 name = elements[index].name;
2721 sprintf(number, "%lu", index);
2725 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2729 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)()) {
2731 if (setups + count != signature->count - 1)
2732 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2734 size_t size(setups + count);
2736 memcpy(values, setup, sizeof(void *) * setups);
2738 for (size_t index(setups); index != size; ++index) {
2739 sig::Element *element(&signature->elements[index + 1]);
2740 ffi_type *ffi(cif->arg_types[index]);
2742 values[index] = new(pool) uint8_t[ffi->size];
2743 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2746 uint8_t value[cif->rtype->size];
2747 ffi_call(cif, function, value, values);
2749 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2753 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2756 NSString *name(CYCastNSString(pool, property));
2757 if (Class _class = NSClassFromString(name))
2758 return CYMakeInstance(context, _class, true);
2763 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2764 size_t size(objc_getClassList(NULL, 0));
2765 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2768 size_t writ(objc_getClassList(data, size));
2771 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2777 for (size_t i(0); i != writ; ++i)
2778 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2784 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2785 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2789 const char *name(CYPoolCString(pool, property));
2791 const char **data(objc_copyClassNamesForImage(internal, &size));
2793 for (size_t i(0); i != size; ++i)
2794 if (strcmp(name, data[i]) == 0) {
2795 if (Class _class = objc_getClass(name)) {
2796 value = CYMakeInstance(context, _class, true);
2808 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2809 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2811 const char **data(objc_copyClassNamesForImage(internal, &size));
2812 for (size_t i(0); i != size; ++i)
2813 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2817 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2820 const char *name(CYPoolCString(pool, property));
2822 const char **data(objc_copyImageNames(&size));
2823 for (size_t i(0); i != size; ++i)
2824 if (strcmp(name, data[i]) == 0) {
2833 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2834 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2839 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2841 const char **data(objc_copyImageNames(&size));
2842 for (size_t i(0); i != size; ++i)
2843 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2847 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2850 NSString *name(CYCastNSString(pool, property));
2851 if (Protocol *protocol = NSProtocolFromString(name))
2852 return CYMakeInstance(context, protocol, true);
2857 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2859 Protocol **data(objc_copyProtocolList(&size));
2860 for (size_t i(0); i != size; ++i)
2861 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2865 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
2866 Type_privateData *internal(new Type_privateData(NULL, type));
2867 return JSObjectMake(context, Type_privateData::Class_, internal);
2870 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
2871 Type_privateData *internal(new Type_privateData(type));
2872 return JSObjectMake(context, Type_privateData::Class_, internal);
2875 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2876 if (JSStringIsEqualToUTF8CString(property, "nil"))
2877 return Instance::Make(context, nil);
2881 NSString *name(CYCastNSString(pool, property));
2882 if (Class _class = NSClassFromString(name))
2883 return CYMakeInstance(context, _class, true);
2884 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2885 switch ([[entry objectAtIndex:0] intValue]) {
2887 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2889 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2891 // XXX: this is horrendously inefficient
2892 sig::Signature signature;
2893 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2895 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2896 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2898 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
2899 switch ([[entry objectAtIndex:0] intValue]) {
2900 // XXX: implement case 0
2902 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
2908 static bool stret(ffi_type *ffi_type) {
2909 return ffi_type->type == FFI_TYPE_STRUCT && (
2910 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2911 struct_forward_array[ffi_type->size] != 0
2916 int *_NSGetArgc(void);
2917 char ***_NSGetArgv(void);
2920 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2925 NSLog(@"%s", CYCastCString(context, arguments[0]));
2926 return CYJSUndefined(context);
2930 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2933 Class _class(object_getClass(self));
2934 if (Method method = class_getInstanceMethod(_class, _cmd))
2935 type = method_getTypeEncoding(method);
2939 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2941 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2942 type = CYPoolCString(pool, [method _typeString]);
2951 sig::Signature signature;
2952 sig::Parse(pool, &signature, type, &Structor_);
2955 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2957 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2958 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2961 static size_t Nonce_(0);
2963 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2965 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
2966 return CYCastJSValue(context, name);
2969 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2979 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2981 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2982 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2983 self = internal->GetValue();
2984 uninitialized = internal->IsUninitialized();
2986 internal->value_ = nil;
2988 self = CYCastNSObject(pool, context, arguments[0]);
2989 uninitialized = false;
2993 return CYJSNull(context);
2995 _cmd = CYCastSEL(context, arguments[1]);
2998 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
3001 /* Hook: objc_registerClassPair {{{ */
3002 // XXX: replace this with associated objects
3004 MSHook(void, CYDealloc, id self, SEL sel) {
3005 CYInternal *internal;
3006 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
3007 if (internal != NULL)
3009 _CYDealloc(self, sel);
3012 MSHook(void, objc_registerClassPair, Class _class) {
3013 Class super(class_getSuperclass(_class));
3014 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
3015 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
3016 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
3019 _objc_registerClassPair(_class);
3022 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3025 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
3027 Class _class(CYCastNSObject(pool, context, arguments[0]));
3028 $objc_registerClassPair(_class);
3029 return CYJSUndefined(context);
3034 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3035 JSGarbageCollect(context);
3036 return CYJSUndefined(context);
3039 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3040 JSValueRef setup[count + 2];
3043 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
3044 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
3047 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3049 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
3051 // XXX: handle Instance::Uninitialized?
3052 id self(CYCastNSObject(pool, context, _this));
3056 setup[1] = &internal->sel_;
3058 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3061 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3063 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
3064 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3067 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3070 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
3071 const char *name(CYCastCString(context, arguments[0]));
3072 return CYMakeSelector(context, sel_registerName(name));
3076 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3079 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
3081 void *value(CYCastPointer<void *>(context, arguments[0]));
3082 const char *type(CYCastCString(context, arguments[1]));
3086 sig::Signature signature;
3087 sig::Parse(pool, &signature, type, &Structor_);
3089 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
3093 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3096 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
3097 const char *type(CYCastCString(context, arguments[0]));
3098 return CYMakeType(context, type);
3102 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3103 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3108 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3109 type.primitive = sig::pointer_P;
3110 type.data.data.size = 0;
3112 size_t index(CYGetIndex(NULL, property));
3113 if (index == _not(size_t))
3115 type.primitive = sig::array_P;
3116 type.data.data.size = index;
3122 type.data.data.type = internal->type_;
3124 return CYMakeType(context, &type);
3128 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3129 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3133 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3134 sig::Type *type(internal->type_);
3135 ffi_type *ffi(internal->GetFFI());
3137 uint8_t value[ffi->size];
3139 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3140 return CYFromFFI(context, type, ffi, value);
3144 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3147 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3148 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3150 sig::Type *type(internal->type_);
3153 if (type->primitive != sig::array_P)
3156 size = type->data.data.size;
3157 type = type->data.data.type;
3160 void *value(malloc(internal->GetFFI()->size));
3161 return CYMakePointer(context, value, type, NULL, NULL);
3165 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3168 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
3169 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3170 return Instance::Make(context, self);
3174 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3177 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
3178 const char *type(CYCastCString(context, arguments[1]));
3179 return CYMakeFunctor(context, arguments[0], type);
3183 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3184 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3185 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3188 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3189 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3190 Type_privateData *typical(internal->GetType());
3195 if (typical == NULL) {
3199 type = typical->type_;
3200 ffi = typical->ffi_;
3203 return CYMakePointer(context, &internal->value_, type, ffi, object);
3206 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3207 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3210 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3214 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3215 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3218 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3219 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3221 sprintf(string, "%p", internal->value_);
3224 return CYCastJSValue(context, string);
3228 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3229 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3230 return Instance::Make(context, object_getClass(internal->GetValue()));
3233 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3234 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3235 id self(internal->GetValue());
3236 if (!CYIsClass(self))
3237 return CYJSUndefined(context);
3239 return CYGetClassPrototype(context, self);
3243 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3244 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3245 id self(internal->GetValue());
3246 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3247 return CYJSUndefined(context);
3248 return Messages::Make(context, self);
3251 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3252 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3255 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3259 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
3264 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3265 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3268 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3272 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3273 // XXX: check for support of cy$toJSON?
3274 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3279 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3280 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3283 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3287 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3292 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3293 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3296 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3300 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3301 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3304 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3305 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3306 const char *name(sel_getName(internal->GetValue()));
3310 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3315 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3318 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
3320 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3321 Class _class(CYCastNSObject(pool, context, arguments[0]));
3322 SEL sel(internal->GetValue());
3323 Method method(class_getInstanceMethod(_class, sel));
3324 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3325 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3329 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3331 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3333 const char *type(sig::Unparse(pool, internal->type_));
3335 return CYCastJSValue(context, CYJSString(type));
3340 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3342 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3344 const char *type(sig::Unparse(pool, internal->type_));
3346 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
3351 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3352 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3355 static JSStaticValue CYValue_staticValues[2] = {
3356 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3357 {NULL, NULL, NULL, 0}
3360 static JSStaticValue Pointer_staticValues[2] = {
3361 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3362 {NULL, NULL, NULL, 0}
3365 static JSStaticFunction Pointer_staticFunctions[4] = {
3366 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3367 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3368 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3372 static JSStaticFunction Struct_staticFunctions[2] = {
3373 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3377 static JSStaticFunction Functor_staticFunctions[4] = {
3378 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3379 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3380 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3384 static JSStaticValue Instance_staticValues[5] = {
3385 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3386 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3387 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3388 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3389 {NULL, NULL, NULL, 0}
3392 static JSStaticFunction Instance_staticFunctions[5] = {
3393 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3394 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3395 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3396 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3400 static JSStaticFunction Internal_staticFunctions[2] = {
3401 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3405 static JSStaticFunction Selector_staticFunctions[5] = {
3406 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3407 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3408 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3409 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3413 static JSStaticFunction Type_staticFunctions[4] = {
3414 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3415 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3416 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3420 void CYSetArgs(int argc, const char *argv[]) {
3421 JSContextRef context(CYGetJSContext());
3422 JSValueRef args[argc];
3423 for (int i(0); i != argc; ++i)
3424 args[i] = CYCastJSValue(context, argv[i]);
3425 JSValueRef exception(NULL);
3426 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3427 CYThrow(context, exception);
3428 CYSetProperty(context, System_, CYJSString("args"), array);
3431 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3432 return JSContextGetGlobalObject(context);
3435 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3436 JSContextRef context(CYGetJSContext());
3437 JSValueRef exception(NULL), result;
3440 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3441 } catch (const char *error) {
3445 if (exception != NULL) { error:
3450 if (JSValueIsUndefined(context, result))
3456 json = CYPoolCCYON(pool, context, result, &exception);
3457 } catch (const char *error) {
3461 if (exception != NULL)
3464 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3468 static apr_pool_t *Pool_;
3472 const char * volatile data_;
3475 // XXX: this is "tre lame"
3476 @interface CYClient_ : NSObject {
3479 - (void) execute:(NSValue *)value;
3483 @implementation CYClient_
3485 - (void) execute:(NSValue *)value {
3486 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3487 const char *data(execute->data_);
3488 execute->data_ = NULL;
3489 execute->data_ = CYExecute(execute->pool_, data);
3498 apr_thread_t *thread_;
3500 CYClient(int socket) :
3506 _syscall(close(socket_));
3509 void Handle() { _pooled
3510 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3514 if (!CYRecvAll(socket_, &size, sizeof(size)))
3518 char *data(new(pool) char[size + 1]);
3519 if (!CYRecvAll(socket_, data, size))
3523 CYDriver driver("");
3524 cy::parser parser(driver);
3526 driver.data_ = data;
3527 driver.size_ = size;
3530 if (parser.parse() != 0 || !driver.errors_.empty()) {
3532 size = _not(size_t);
3534 CYContext context(driver.pool_);
3535 driver.program_->Replace(context);
3536 std::ostringstream str;
3538 out << *driver.program_;
3539 std::string code(str.str());
3540 CYExecute_ execute = {pool, code.c_str()};
3541 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3542 json = execute.data_;
3543 size = json == NULL ? _not(size_t) : strlen(json);
3546 if (!CYSendAll(socket_, &size, sizeof(size)))
3549 if (!CYSendAll(socket_, json, size))
3555 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3556 CYClient *client(reinterpret_cast<CYClient *>(data));
3562 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3563 CYClient *client(new(pool) CYClient(socket));
3564 apr_threadattr_t *attr;
3565 _aprcall(apr_threadattr_create(&attr, client->pool_));
3566 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3569 MSInitialize { _pooled
3570 _aprcall(apr_initialize());
3571 _aprcall(apr_pool_create(&Pool_, NULL));
3573 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3574 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3576 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3579 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3580 NSCFType_ = objc_getClass("NSCFType");
3583 NSArray_ = objc_getClass("NSArray");
3584 NSDictionary_ = objc_getClass("NSDictonary");
3585 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3586 NSZombie_ = objc_getClass("_NSZombie_");
3587 Object_ = objc_getClass("Object");
3590 JSGlobalContextRef CYGetJSContext() {
3591 if (Context_ == NULL) {
3592 JSClassDefinition definition;
3594 definition = kJSClassDefinitionEmpty;
3595 definition.className = "Functor";
3596 definition.staticFunctions = Functor_staticFunctions;
3597 definition.callAsFunction = &Functor_callAsFunction;
3598 definition.finalize = &Finalize;
3599 Functor_ = JSClassCreate(&definition);
3601 definition = kJSClassDefinitionEmpty;
3602 definition.className = "Instance";
3603 definition.staticValues = Instance_staticValues;
3604 definition.staticFunctions = Instance_staticFunctions;
3605 definition.hasProperty = &Instance_hasProperty;
3606 definition.getProperty = &Instance_getProperty;
3607 definition.setProperty = &Instance_setProperty;
3608 definition.deleteProperty = &Instance_deleteProperty;
3609 definition.getPropertyNames = &Instance_getPropertyNames;
3610 definition.callAsConstructor = &Instance_callAsConstructor;
3611 definition.hasInstance = &Instance_hasInstance;
3612 definition.finalize = &Finalize;
3613 Instance_ = JSClassCreate(&definition);
3615 definition = kJSClassDefinitionEmpty;
3616 definition.className = "Internal";
3617 definition.staticFunctions = Internal_staticFunctions;
3618 definition.hasProperty = &Internal_hasProperty;
3619 definition.getProperty = &Internal_getProperty;
3620 definition.setProperty = &Internal_setProperty;
3621 definition.getPropertyNames = &Internal_getPropertyNames;
3622 definition.finalize = &Finalize;
3623 Internal_ = JSClassCreate(&definition);
3625 definition = kJSClassDefinitionEmpty;
3626 definition.className = "Message";
3627 definition.staticFunctions = Functor_staticFunctions;
3628 definition.callAsFunction = &Message_callAsFunction;
3629 definition.finalize = &Finalize;
3630 Message_ = JSClassCreate(&definition);
3632 definition = kJSClassDefinitionEmpty;
3633 definition.className = "Messages";
3634 definition.hasProperty = &Messages_hasProperty;
3635 definition.getProperty = &Messages_getProperty;
3636 definition.setProperty = &Messages_setProperty;
3638 definition.deleteProperty = &Messages_deleteProperty;
3640 definition.getPropertyNames = &Messages_getPropertyNames;
3641 definition.finalize = &Finalize;
3642 Messages_ = JSClassCreate(&definition);
3644 definition = kJSClassDefinitionEmpty;
3645 definition.className = "NSArrayPrototype";
3646 //definition.hasProperty = &NSArrayPrototype_hasProperty;
3647 //definition.getProperty = &NSArrayPrototype_getProperty;
3648 //definition.setProperty = &NSArrayPrototype_setProperty;
3649 //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
3650 //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
3651 NSArrayPrototype_ = JSClassCreate(&definition);
3653 definition = kJSClassDefinitionEmpty;
3654 definition.className = "Pointer";
3655 definition.staticValues = Pointer_staticValues;
3656 definition.staticFunctions = Pointer_staticFunctions;
3657 definition.getProperty = &Pointer_getProperty;
3658 definition.setProperty = &Pointer_setProperty;
3659 definition.finalize = &Finalize;
3660 Pointer_ = JSClassCreate(&definition);
3662 definition = kJSClassDefinitionEmpty;
3663 definition.className = "Selector";
3664 definition.staticValues = CYValue_staticValues;
3665 definition.staticFunctions = Selector_staticFunctions;
3666 definition.callAsFunction = &Selector_callAsFunction;
3667 definition.finalize = &Finalize;
3668 Selector_ = JSClassCreate(&definition);
3670 definition = kJSClassDefinitionEmpty;
3671 definition.className = "Struct";
3672 definition.staticFunctions = Struct_staticFunctions;
3673 definition.getProperty = &Struct_getProperty;
3674 definition.setProperty = &Struct_setProperty;
3675 definition.getPropertyNames = &Struct_getPropertyNames;
3676 definition.finalize = &Finalize;
3677 Struct_ = JSClassCreate(&definition);
3679 definition = kJSClassDefinitionEmpty;
3680 definition.className = "Type";
3681 definition.staticFunctions = Type_staticFunctions;
3682 definition.getProperty = &Type_getProperty;
3683 definition.callAsFunction = &Type_callAsFunction;
3684 definition.callAsConstructor = &Type_callAsConstructor;
3685 definition.finalize = &Finalize;
3686 Type_privateData::Class_ = JSClassCreate(&definition);
3688 definition = kJSClassDefinitionEmpty;
3689 definition.className = "Runtime";
3690 definition.getProperty = &Runtime_getProperty;
3691 Runtime_ = JSClassCreate(&definition);
3693 definition = kJSClassDefinitionEmpty;
3694 definition.className = "ObjectiveC::Classes";
3695 definition.getProperty = &ObjectiveC_Classes_getProperty;
3696 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3697 ObjectiveC_Classes_ = JSClassCreate(&definition);
3699 definition = kJSClassDefinitionEmpty;
3700 definition.className = "ObjectiveC::Images";
3701 definition.getProperty = &ObjectiveC_Images_getProperty;
3702 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3703 ObjectiveC_Images_ = JSClassCreate(&definition);
3705 definition = kJSClassDefinitionEmpty;
3706 definition.className = "ObjectiveC::Image::Classes";
3707 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3708 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3709 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3711 definition = kJSClassDefinitionEmpty;
3712 definition.className = "ObjectiveC::Protocols";
3713 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3714 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3715 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3717 definition = kJSClassDefinitionEmpty;
3718 //definition.getProperty = &Global_getProperty;
3719 JSClassRef Global(JSClassCreate(&definition));
3721 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3724 JSObjectRef global(CYGetGlobalObject(context));
3726 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3727 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3728 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3730 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3731 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3732 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3734 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3735 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3736 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3738 length_ = JSStringCreateWithUTF8CString("length");
3739 message_ = JSStringCreateWithUTF8CString("message");
3740 name_ = JSStringCreateWithUTF8CString("name");
3741 prototype_ = JSStringCreateWithUTF8CString("prototype");
3742 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3743 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3745 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3746 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3748 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3749 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3750 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3751 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3753 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3754 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3755 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3756 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3758 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3760 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3761 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3762 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3763 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3765 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3766 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3767 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3768 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3769 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
3771 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3774 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3777 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
3778 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
3779 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
3781 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3782 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3783 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3785 System_ = JSObjectMake(context, NULL, NULL);
3786 CYSetProperty(context, global, CYJSString("system"), System_);
3787 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3788 //CYSetProperty(context, System_, CYJSString("global"), global);
3790 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3792 Result_ = JSStringCreateWithUTF8CString("_");
3794 JSValueProtect(context, Array_);
3795 JSValueProtect(context, Function_);
3796 JSValueProtect(context, String_);
3798 JSValueProtect(context, Instance_prototype_);
3799 JSValueProtect(context, Object_prototype_);
3801 JSValueProtect(context, Array_prototype_);
3802 JSValueProtect(context, Array_pop_);
3803 JSValueProtect(context, Array_push_);
3804 JSValueProtect(context, Array_splice_);