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>
55 #include <Foundation/Foundation.h>
57 #include <WebKit/WebScriptObject.h>
62 #include <ext/stdio_filebuf.h>
70 #include "Cycript.tab.hh"
72 #include <apr_thread_proc.h>
77 #define _assert(test) do { \
79 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
82 #define _trace() do { \
83 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
88 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
90 #define CYPoolCatch(value) \
91 @catch (NSException *error) { \
92 _saved = [error retain]; \
98 [_saved autorelease]; \
102 void CYThrow(JSContextRef context, JSValueRef value);
104 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception);
105 JSStringRef CYCopyJSString(const char *value);
107 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value);
109 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)());
110 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
112 /* JavaScript Properties {{{ */
113 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
114 JSValueRef exception(NULL);
115 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
116 CYThrow(context, exception);
120 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
121 JSValueRef exception(NULL);
122 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
123 CYThrow(context, exception);
127 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
128 JSValueRef exception(NULL);
129 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
130 CYThrow(context, exception);
133 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
134 JSValueRef exception(NULL);
135 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
136 CYThrow(context, exception);
139 /* JavaScript Strings {{{ */
140 JSStringRef CYCopyJSString(const char *value) {
141 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
144 JSStringRef CYCopyJSString(JSStringRef value) {
145 return value == NULL ? NULL : JSStringRetain(value);
148 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
149 if (JSValueIsNull(context, value))
151 JSValueRef exception(NULL);
152 JSStringRef string(JSValueToStringCopy(context, value, &exception));
153 CYThrow(context, exception);
163 JSStringRelease(string_);
167 CYJSString(const CYJSString &rhs) :
168 string_(CYCopyJSString(rhs.string_))
172 template <typename Arg0_>
173 CYJSString(Arg0_ arg0) :
174 string_(CYCopyJSString(arg0))
178 template <typename Arg0_, typename Arg1_>
179 CYJSString(Arg0_ arg0, Arg1_ arg1) :
180 string_(CYCopyJSString(arg0, arg1))
184 CYJSString &operator =(const CYJSString &rhs) {
186 string_ = CYCopyJSString(rhs.string_);
199 operator JSStringRef() const {
204 /* Objective-C Strings {{{ */
205 JSStringRef CYCopyJSString_(NSString *value) {
207 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
209 return CYCopyJSString([value UTF8String]);
213 JSStringRef CYCopyJSString(id value) {
216 // XXX: this definition scares me; is anyone using this?!
217 NSString *string([value description]);
218 return CYCopyJSString_(string);
222 CFStringRef CYCopyCFString(JSStringRef value) {
223 return JSStringCopyCFString(kCFAllocatorDefault, value);
226 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
227 return CYCopyCFString(CYJSString(context, value));
232 static JSGlobalContextRef Context_;
233 static JSObjectRef System_;
234 static JSObjectRef ObjectiveC_;
236 static JSClassRef Functor_;
237 static JSClassRef Instance_;
238 static JSClassRef Internal_;
239 static JSClassRef Message_;
240 static JSClassRef Messages_;
241 static JSClassRef NSArrayPrototype_;
242 static JSClassRef Pointer_;
243 static JSClassRef Runtime_;
244 static JSClassRef Selector_;
245 static JSClassRef Struct_;
247 static JSClassRef ObjectiveC_Classes_;
248 static JSClassRef ObjectiveC_Image_Classes_;
249 static JSClassRef ObjectiveC_Images_;
250 static JSClassRef ObjectiveC_Protocols_;
252 static JSObjectRef Array_;
253 static JSObjectRef Function_;
254 static JSObjectRef String_;
256 static JSStringRef Result_;
258 static JSStringRef length_;
259 static JSStringRef message_;
260 static JSStringRef name_;
261 static JSStringRef prototype_;
262 static JSStringRef toCYON_;
263 static JSStringRef toJSON_;
265 static JSObjectRef Instance_prototype_;
266 static JSObjectRef Object_prototype_;
268 static JSObjectRef Array_prototype_;
269 static JSObjectRef Array_pop_;
270 static JSObjectRef Array_push_;
271 static JSObjectRef Array_splice_;
273 static Class NSArray_;
274 static Class NSCFBoolean_;
275 static Class NSCFType_;
276 static Class NSDictionary_;
277 static Class NSMessageBuilder_;
278 static Class NSZombie_;
279 static Class Object_;
281 static NSArray *Bridge_;
283 static void Finalize(JSObjectRef object) {
284 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
287 class Type_privateData;
297 CYValue(const void *value) :
298 value_(const_cast<void *>(value))
302 CYValue(const CYValue &rhs) :
307 virtual Type_privateData *GetType() const {
312 struct Selector_privateData :
315 Selector_privateData(SEL value) :
320 SEL GetValue() const {
321 return reinterpret_cast<SEL>(value_);
324 virtual Type_privateData *GetType() const;
327 // XXX: trick this out with associated objects!
328 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
330 return Instance_prototype_;
332 // XXX: I need to think through multi-context
333 typedef std::map<id, JSValueRef> CacheMap;
334 static CacheMap cache_;
336 JSValueRef &value(cache_[self]);
340 JSClassRef _class(NULL);
341 JSValueRef prototype;
343 if (self == NSArray_)
344 prototype = Array_prototype_;
345 else if (self == NSDictionary_)
346 prototype = Object_prototype_;
348 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
350 JSObjectRef object(JSObjectMake(context, _class, NULL));
351 JSObjectSetPrototype(context, object, prototype);
353 JSValueProtect(context, object);
363 Transient = (1 << 0),
364 Uninitialized = (1 << 1),
369 Instance(id value, Flags flags) :
375 virtual ~Instance() {
376 if ((flags_ & Transient) == 0)
377 // XXX: does this handle background threads correctly?
378 // XXX: this simply does not work on the console because I'm stupid
379 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
382 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
383 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
384 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object == nil ? nil : object_getClass(object)));
388 id GetValue() const {
389 return reinterpret_cast<id>(value_);
392 bool IsUninitialized() const {
393 return (flags_ & Uninitialized) != 0;
396 virtual Type_privateData *GetType() const;
402 Messages(Class value) :
407 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
408 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
409 if (_class == NSArray_)
411 if (Class super = class_getSuperclass(_class))
412 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
414 JSObjectSetPrototype(context, value, Array_prototype_);*/
418 Class GetValue() const {
419 return reinterpret_cast<Class>(value_);
427 JSContextRef context_;
431 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
436 JSValueProtect(context_, owner_);
440 JSValueUnprotect(context_, owner_);
443 JSObjectRef GetOwner() const {
451 Internal(id value, JSContextRef context, JSObjectRef owner) :
452 CYOwned(value, context, owner)
456 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
457 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
460 id GetValue() const {
461 return reinterpret_cast<id>(value_);
467 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
469 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
470 lhs.name = apr_pstrdup(pool, rhs.name);
471 if (rhs.type == NULL)
474 lhs.type = new(pool) Type;
475 Copy(pool, *lhs.type, *rhs.type);
477 lhs.offset = rhs.offset;
480 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
481 size_t count(rhs.count);
483 lhs.elements = new(pool) Element[count];
484 for (size_t index(0); index != count; ++index)
485 Copy(pool, lhs.elements[index], rhs.elements[index]);
488 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
489 lhs.primitive = rhs.primitive;
490 lhs.name = apr_pstrdup(pool, rhs.name);
491 lhs.flags = rhs.flags;
493 if (sig::IsAggregate(rhs.primitive))
494 Copy(pool, lhs.data.signature, rhs.data.signature);
496 sig::Type *&lht(lhs.data.data.type);
497 sig::Type *&rht(rhs.data.data.type);
502 lht = new(pool) Type;
503 Copy(pool, *lht, *rht);
506 lhs.data.data.size = rhs.data.data.size;
510 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
512 lhs.alignment = rhs.alignment;
514 if (rhs.elements == NULL)
518 while (rhs.elements[count] != NULL)
521 lhs.elements = new(pool) ffi_type *[count + 1];
522 lhs.elements[count] = NULL;
524 for (size_t index(0); index != count; ++index) {
525 // XXX: if these are libffi native then you can just take them
526 ffi_type *ffi(new(pool) ffi_type);
527 lhs.elements[index] = ffi;
528 sig::Copy(pool, *ffi, *rhs.elements[index]);
535 struct CStringMapLess :
536 std::binary_function<const char *, const char *, bool>
538 _finline bool operator ()(const char *lhs, const char *rhs) const {
539 return strcmp(lhs, rhs) < 0;
543 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
548 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
549 switch ([[entry objectAtIndex:0] intValue]) {
551 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
555 sig::Signature signature;
556 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
557 type = signature.elements[0].type;
563 struct Type_privateData :
566 static Type_privateData *Object;
567 static Type_privateData *Selector;
569 static JSClassRef Class;
574 void Set(sig::Type *type) {
575 type_ = new(pool_) sig::Type;
576 sig::Copy(pool_, *type_, *type);
579 Type_privateData(apr_pool_t *pool, const char *type) :
585 sig::Signature signature;
586 sig::Parse(pool_, &signature, type, &Structor_);
587 type_ = signature.elements[0].type;
590 Type_privateData(sig::Type *type) :
597 Type_privateData(sig::Type *type, ffi_type *ffi) {
598 ffi_ = new(pool_) ffi_type;
599 sig::Copy(pool_, *ffi_, *ffi);
605 ffi_ = new(pool_) ffi_type;
607 sig::Element element;
609 element.type = type_;
612 sig::Signature signature;
613 signature.elements = &element;
617 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
625 Type_privateData *Type_privateData::Object;
626 Type_privateData *Type_privateData::Selector;
628 Type_privateData *Instance::GetType() const {
629 return Type_privateData::Object;
632 Type_privateData *Selector_privateData::GetType() const {
633 return Type_privateData::Selector;
639 Type_privateData *type_;
641 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
642 CYOwned(value, context, owner),
643 type_(new(pool_) Type_privateData(type))
648 struct Struct_privateData :
651 Type_privateData *type_;
653 Struct_privateData(JSContextRef context, JSObjectRef owner) :
654 CYOwned(NULL, context, owner)
659 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
660 static TypeMap Types_;
662 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
663 Struct_privateData *internal(new Struct_privateData(context, owner));
664 apr_pool_t *pool(internal->pool_);
665 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
666 internal->type_ = typical;
669 internal->value_ = data;
671 size_t size(typical->GetFFI()->size);
672 void *copy(apr_palloc(internal->pool_, size));
673 memcpy(copy, data, size);
674 internal->value_ = copy;
677 return JSObjectMake(context, Struct_, internal);
680 struct Functor_privateData :
683 sig::Signature signature_;
687 Functor_privateData(const char *type, void (*value)()) :
688 CYValue(reinterpret_cast<void *>(value))
690 sig::Parse(pool_, &signature_, type, &Structor_);
691 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
694 void (*GetValue())() const {
695 return reinterpret_cast<void (*)()>(value_);
699 struct Closure_privateData :
702 JSContextRef context_;
703 JSObjectRef function_;
705 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
706 Functor_privateData(type, NULL),
710 JSValueProtect(context_, function_);
713 virtual ~Closure_privateData() {
714 JSValueUnprotect(context_, function_);
718 struct Message_privateData :
723 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
724 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
730 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
731 Instance::Flags flags;
734 flags = Instance::Transient;
736 flags = Instance::None;
737 object = [object retain];
740 return Instance::Make(context, object, flags);
743 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
745 return [value UTF8String];
747 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
748 char *string(new(pool) char[size]);
749 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
750 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
755 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
756 return JSValueMakeBoolean(context, value);
759 JSValueRef CYCastJSValue(JSContextRef context, double value) {
760 return JSValueMakeNumber(context, value);
763 #define CYCastJSValue_(Type_) \
764 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
765 return JSValueMakeNumber(context, static_cast<double>(value)); \
769 CYCastJSValue_(unsigned int)
770 CYCastJSValue_(long int)
771 CYCastJSValue_(long unsigned int)
772 CYCastJSValue_(long long int)
773 CYCastJSValue_(long long unsigned int)
775 JSValueRef CYJSUndefined(JSContextRef context) {
776 return JSValueMakeUndefined(context);
779 size_t CYGetIndex(const char *value) {
780 if (value[0] != '0') {
782 size_t index(strtoul(value, &end, 10));
783 if (value + strlen(value) == end)
785 } else if (value[1] == '\0')
791 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value);
793 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
794 return CYGetIndex(CYPoolCString(pool, value));
797 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
798 return CYGetIndex(CYPoolCString(pool, value));
801 bool CYGetOffset(const char *value, ssize_t &index) {
802 if (value[0] != '0') {
804 index = strtol(value, &end, 10);
805 if (value + strlen(value) == end)
807 } else if (value[1] == '\0') {
815 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
816 return CYGetOffset(CYPoolCString(pool, value), index);
819 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
821 @interface NSMethodSignature (Cycript)
822 - (NSString *) _typeString;
825 @interface NSObject (Cycript)
827 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
828 - (JSType) cy$JSType;
830 - (NSObject *) cy$toJSON:(NSString *)key;
831 - (NSString *) cy$toCYON;
832 - (NSString *) cy$toKey;
834 - (bool) cy$hasProperty:(NSString *)name;
835 - (NSObject *) cy$getProperty:(NSString *)name;
836 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
837 - (bool) cy$deleteProperty:(NSString *)name;
842 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
845 @interface NSString (Cycript)
846 - (void *) cy$symbol;
850 struct PropertyAttributes {
855 const char *variable;
868 PropertyAttributes(objc_property_t property) :
880 name = property_getName(property);
881 const char *attributes(property_getAttributes(property));
883 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
885 case 'R': readonly = true; break;
886 case 'C': copy = true; break;
887 case '&': retain = true; break;
888 case 'N': nonatomic = true; break;
889 case 'G': getter_ = token + 1; break;
890 case 'S': setter_ = token + 1; break;
891 case 'V': variable = token + 1; break;
895 /*if (variable == NULL) {
896 variable = property_getName(property);
897 size_t size(strlen(variable));
898 char *name(new(pool_) char[size + 2]);
900 memcpy(name + 1, variable, size);
901 name[size + 1] = '\0';
906 const char *Getter() {
908 getter_ = apr_pstrdup(pool_, name);
912 const char *Setter() {
913 if (setter_ == NULL && !readonly) {
914 size_t length(strlen(name));
916 char *temp(new(pool_) char[length + 5]);
922 temp[3] = toupper(name[0]);
923 memcpy(temp + 4, name + 1, length - 1);
926 temp[length + 3] = ':';
927 temp[length + 4] = '\0';
938 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
939 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
943 /* Bridge: NSArray {{{ */
944 @implementation NSArray (Cycript)
946 - (NSString *) cy$toCYON {
947 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
948 [json appendString:@"["];
952 for (id object in self) {
955 for (size_t index(0), count([self count]); index != count; ++index) {
956 object = [self objectAtIndex:index];
959 [json appendString:@","];
962 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
963 [json appendString:CYPoolNSCYON(NULL, object)];
965 [json appendString:@","];
970 [json appendString:@"]"];
974 - (bool) cy$hasProperty:(NSString *)name {
975 if ([name isEqualToString:@"length"])
978 size_t index(CYGetIndex(NULL, name));
979 if (index == _not(size_t) || index >= [self count])
980 return [super cy$hasProperty:name];
985 - (NSObject *) cy$getProperty:(NSString *)name {
986 if ([name isEqualToString:@"length"]) {
987 NSUInteger count([self count]);
989 return [NSNumber numberWithUnsignedInteger:count];
991 return [NSNumber numberWithUnsignedInt:count];
995 size_t index(CYGetIndex(NULL, name));
996 if (index == _not(size_t) || index >= [self count])
997 return [super cy$getProperty:name];
999 return [self objectAtIndex:index];
1004 /* Bridge: NSDictionary {{{ */
1005 @implementation NSDictionary (Cycript)
1007 - (NSString *) cy$toCYON {
1008 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1009 [json appendString:@"{"];
1013 for (id key in self) {
1015 NSEnumerator *keys([self keyEnumerator]);
1016 while (id key = [keys nextObject]) {
1019 [json appendString:@","];
1022 [json appendString:[key cy$toKey]];
1023 [json appendString:@":"];
1024 NSObject *object([self objectForKey:key]);
1025 [json appendString:CYPoolNSCYON(NULL, object)];
1028 [json appendString:@"}"];
1032 - (bool) cy$hasProperty:(NSString *)name {
1033 return [self objectForKey:name] != nil;
1036 - (NSObject *) cy$getProperty:(NSString *)name {
1037 return [self objectForKey:name];
1042 /* Bridge: NSMutableArray {{{ */
1043 @implementation NSMutableArray (Cycript)
1045 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1046 if ([name isEqualToString:@"length"]) {
1047 // XXX: is this not intelligent?
1048 NSNumber *number(reinterpret_cast<NSNumber *>(value));
1050 NSUInteger size([number unsignedIntegerValue]);
1052 NSUInteger size([number unsignedIntValue]);
1054 NSUInteger count([self count]);
1056 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1057 else if (size != count) {
1058 WebUndefined *undefined([WebUndefined undefined]);
1059 for (size_t i(count); i != size; ++i)
1060 [self addObject:undefined];
1065 size_t index(CYGetIndex(NULL, name));
1066 if (index == _not(size_t))
1067 return [super cy$setProperty:name to:value];
1069 id object(value ?: [NSNull null]);
1071 size_t count([self count]);
1073 [self replaceObjectAtIndex:index withObject:object];
1075 if (index != count) {
1076 WebUndefined *undefined([WebUndefined undefined]);
1077 for (size_t i(count); i != index; ++i)
1078 [self addObject:undefined];
1081 [self addObject:object];
1087 - (bool) cy$deleteProperty:(NSString *)name {
1088 size_t index(CYGetIndex(NULL, name));
1089 if (index == _not(size_t) || index >= [self count])
1090 return [super cy$deleteProperty:name];
1091 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1097 /* Bridge: NSMutableDictionary {{{ */
1098 @implementation NSMutableDictionary (Cycript)
1100 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1101 [self setObject:(value ?: [NSNull null]) forKey:name];
1105 - (bool) cy$deleteProperty:(NSString *)name {
1106 if ([self objectForKey:name] == nil)
1109 [self removeObjectForKey:name];
1116 /* Bridge: NSNumber {{{ */
1117 @implementation NSNumber (Cycript)
1119 - (JSType) cy$JSType {
1120 // XXX: this just seems stupid
1121 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
1124 - (NSObject *) cy$toJSON:(NSString *)key {
1128 - (NSString *) cy$toCYON {
1129 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1132 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1133 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1138 /* Bridge: NSNull {{{ */
1139 @implementation NSNull (Cycript)
1141 - (JSType) cy$JSType {
1145 - (NSObject *) cy$toJSON:(NSString *)key {
1149 - (NSString *) cy$toCYON {
1155 /* Bridge: NSObject {{{ */
1156 @implementation NSObject (Cycript)
1158 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1159 return CYMakeInstance(context, self, false);
1162 - (JSType) cy$JSType {
1163 return kJSTypeObject;
1166 - (NSObject *) cy$toJSON:(NSString *)key {
1167 return [self description];
1170 - (NSString *) cy$toCYON {
1171 return [[self cy$toJSON:@""] cy$toCYON];
1174 - (NSString *) cy$toKey {
1175 return [self cy$toCYON];
1178 - (bool) cy$hasProperty:(NSString *)name {
1182 - (NSObject *) cy$getProperty:(NSString *)name {
1186 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1190 - (bool) cy$deleteProperty:(NSString *)name {
1196 /* Bridge: NSProxy {{{ */
1197 @implementation NSProxy (Cycript)
1199 - (NSObject *) cy$toJSON:(NSString *)key {
1200 return [self description];
1203 - (NSString *) cy$toCYON {
1204 return [[self cy$toJSON:@""] cy$toCYON];
1209 /* Bridge: NSString {{{ */
1210 @implementation NSString (Cycript)
1212 - (JSType) cy$JSType {
1213 return kJSTypeString;
1216 - (NSObject *) cy$toJSON:(NSString *)key {
1220 - (NSString *) cy$toCYON {
1221 // XXX: this should use the better code from Output.cpp
1222 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
1224 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
1225 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
1226 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
1227 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
1228 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
1230 CFStringInsert(json, 0, CFSTR("\""));
1231 CFStringAppend(json, CFSTR("\""));
1233 return [reinterpret_cast<const NSString *>(json) autorelease];
1236 - (NSString *) cy$toKey {
1237 const char *value([self UTF8String]);
1238 size_t size(strlen(value));
1243 if (DigitRange_[value[0]]) {
1244 size_t index(CYGetIndex(NULL, self));
1245 if (index == _not(size_t))
1248 if (!WordStartRange_[value[0]])
1250 for (size_t i(1); i != size; ++i)
1251 if (!WordEndRange_[value[i]])
1258 return [self cy$toCYON];
1261 - (void *) cy$symbol {
1263 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1268 /* Bridge: WebUndefined {{{ */
1269 @implementation WebUndefined (Cycript)
1271 - (JSType) cy$JSType {
1272 return kJSTypeUndefined;
1275 - (NSObject *) cy$toJSON:(NSString *)key {
1279 - (NSString *) cy$toCYON {
1280 return @"undefined";
1283 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1284 return CYJSUndefined(context);
1290 @interface CYJSObject : NSMutableDictionary {
1291 JSObjectRef object_;
1292 JSContextRef context_;
1295 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1297 - (NSString *) cy$toJSON:(NSString *)key;
1299 - (NSUInteger) count;
1300 - (id) objectForKey:(id)key;
1301 - (NSEnumerator *) keyEnumerator;
1302 - (void) setObject:(id)object forKey:(id)key;
1303 - (void) removeObjectForKey:(id)key;
1307 @interface CYJSArray : NSMutableArray {
1308 JSObjectRef object_;
1309 JSContextRef context_;
1312 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1314 - (NSUInteger) count;
1315 - (id) objectAtIndex:(NSUInteger)index;
1317 - (void) addObject:(id)anObject;
1318 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1319 - (void) removeLastObject;
1320 - (void) removeObjectAtIndex:(NSUInteger)index;
1321 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1328 @catch (id error) { \
1329 CYThrow(context, error, exception); \
1333 apr_status_t CYPoolRelease_(void *data) {
1334 id object(reinterpret_cast<id>(data));
1339 id CYPoolRelease(apr_pool_t *pool, id object) {
1342 else if (pool == NULL)
1343 return [object autorelease];
1345 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1350 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1351 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1354 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1355 JSValueRef exception(NULL);
1356 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1357 CYThrow(context, exception);
1358 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1359 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1362 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1363 if (!JSValueIsObjectOfClass(context, object, Instance_))
1364 return CYCastNSObject_(pool, context, object);
1366 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1367 return internal->GetValue();
1371 double CYCastDouble(const char *value, size_t size) {
1373 double number(strtod(value, &end));
1374 if (end != value + size)
1379 double CYCastDouble(const char *value) {
1380 return CYCastDouble(value, strlen(value));
1383 double CYCastDouble(JSContextRef context, JSValueRef value) {
1384 JSValueRef exception(NULL);
1385 double number(JSValueToNumber(context, value, &exception));
1386 CYThrow(context, exception);
1390 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1391 double number(CYCastDouble(context, value));
1392 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1395 CFStringRef CYCopyCFString(const char *value) {
1396 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1399 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1400 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1403 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1404 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1407 bool CYCastBool(JSContextRef context, JSValueRef value) {
1408 return JSValueToBoolean(context, value);
1411 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1415 switch (JSType type = JSValueGetType(context, value)) {
1416 case kJSTypeUndefined:
1417 object = [WebUndefined undefined];
1425 case kJSTypeBoolean:
1426 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1431 object = CYCopyCFNumber(context, value);
1436 object = CYCopyCFString(context, value);
1441 // XXX: this might could be more efficient
1442 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1447 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1454 return CYPoolRelease(pool, object);
1456 return CFRetain(object);
1459 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1460 return CYCFType(pool, context, value, true);
1463 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1464 return CYCFType(pool, context, value, false);
1467 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1469 size_t size(JSPropertyNameArrayGetCount(names));
1470 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1471 for (size_t index(0); index != size; ++index)
1472 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1476 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1477 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1480 void CYThrow(JSContextRef context, JSValueRef value) {
1483 @throw CYCastNSObject(NULL, context, value);
1486 JSValueRef CYJSNull(JSContextRef context) {
1487 return JSValueMakeNull(context);
1490 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1491 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1494 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1495 return CYCastJSValue(context, CYJSString(value));
1498 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1500 return CYJSNull(context);
1501 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1502 return [value cy$JSValueInContext:context];
1504 return CYMakeInstance(context, value, false);
1507 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1508 JSValueRef exception(NULL);
1509 JSObjectRef object(JSValueToObject(context, value, &exception));
1510 CYThrow(context, exception);
1514 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1515 if (exception == NULL)
1517 *exception = CYCastJSValue(context, error);
1520 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1521 JSValueRef exception(NULL);
1522 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1523 CYThrow(context, exception);
1527 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1528 // XXX: this isn't actually correct
1529 return value != NULL && JSValueIsObject(context, value);
1532 @implementation CYJSObject
1534 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1535 if ((self = [super init]) != nil) {
1538 JSValueProtect(context_, object_);
1543 JSValueUnprotect(context_, object_);
1547 - (NSObject *) cy$toJSON:(NSString *)key {
1548 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1549 if (!CYIsCallable(context_, toJSON))
1550 return [super cy$toJSON:key];
1552 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1553 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1554 // XXX: do I really want an NSNull here?!
1555 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1559 - (NSString *) cy$toCYON {
1560 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1561 if (!CYIsCallable(context_, toCYON)) super:
1562 return [super cy$toCYON];
1563 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1564 return CYCastNSString(NULL, CYJSString(context_, value));
1568 - (NSUInteger) count {
1569 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1570 size_t size(JSPropertyNameArrayGetCount(names));
1571 JSPropertyNameArrayRelease(names);
1575 - (id) objectForKey:(id)key {
1576 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1577 if (JSValueIsUndefined(context_, value))
1579 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1582 - (NSEnumerator *) keyEnumerator {
1583 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1584 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1585 JSPropertyNameArrayRelease(names);
1589 - (void) setObject:(id)object forKey:(id)key {
1590 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1593 - (void) removeObjectForKey:(id)key {
1594 JSValueRef exception(NULL);
1595 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1596 CYThrow(context_, exception);
1601 @implementation CYJSArray
1603 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1604 if ((self = [super init]) != nil) {
1607 JSValueProtect(context_, object_);
1612 JSValueUnprotect(context_, object_);
1616 - (NSUInteger) count {
1617 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1620 - (id) objectAtIndex:(NSUInteger)index {
1621 size_t bounds([self count]);
1622 if (index >= bounds)
1623 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1624 JSValueRef exception(NULL);
1625 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1626 CYThrow(context_, exception);
1627 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1630 - (void) addObject:(id)object {
1631 JSValueRef exception(NULL);
1632 JSValueRef arguments[1];
1633 arguments[0] = CYCastJSValue(context_, object);
1634 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1635 CYThrow(context_, exception);
1638 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1639 size_t bounds([self count] + 1);
1640 if (index >= bounds)
1641 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1642 JSValueRef exception(NULL);
1643 JSValueRef arguments[3];
1644 arguments[0] = CYCastJSValue(context_, index);
1645 arguments[1] = CYCastJSValue(context_, 0);
1646 arguments[2] = CYCastJSValue(context_, object);
1647 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1648 CYThrow(context_, exception);
1651 - (void) removeLastObject {
1652 JSValueRef exception(NULL);
1653 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1654 CYThrow(context_, exception);
1657 - (void) removeObjectAtIndex:(NSUInteger)index {
1658 size_t bounds([self count]);
1659 if (index >= bounds)
1660 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1661 JSValueRef exception(NULL);
1662 JSValueRef arguments[2];
1663 arguments[0] = CYCastJSValue(context_, index);
1664 arguments[1] = CYCastJSValue(context_, 1);
1665 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1666 CYThrow(context_, exception);
1669 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1670 size_t bounds([self count]);
1671 if (index >= bounds)
1672 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1673 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1678 NSString *CYCopyNSCYON(id value) {
1684 Class _class(object_getClass(value));
1685 SEL sel(@selector(cy$toCYON));
1687 if (Method toCYON = class_getInstanceMethod(_class, sel))
1688 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1689 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1690 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1691 string = [value cy$toCYON];
1694 if (value == NSZombie_)
1695 string = @"_NSZombie_";
1696 else if (_class == NSZombie_)
1697 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1698 // XXX: frowny /in/ the pants
1699 else if (value == NSMessageBuilder_ || value == Object_)
1702 string = [NSString stringWithFormat:@"%@", value];
1705 // XXX: frowny pants
1707 string = @"undefined";
1710 return [string retain];
1713 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1714 if (JSValueIsNull(context, value))
1715 return [@"null" retain];
1719 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1724 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1725 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1728 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1729 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1730 const char *string(CYPoolCString(pool, json));
1736 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1740 JSObjectRef object_;
1748 // XXX: delete object_? ;(
1751 static CYInternal *Get(id self) {
1752 CYInternal *internal(NULL);
1753 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1754 // XXX: do something epic? ;P
1760 static CYInternal *Set(id self) {
1761 CYInternal *internal(NULL);
1762 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1763 if (internal == NULL) {
1764 internal = new CYInternal();
1765 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1768 // XXX: do something epic? ;P
1774 bool HasProperty(JSContextRef context, JSStringRef name) {
1775 if (object_ == NULL)
1777 return JSObjectHasProperty(context, object_, name);
1780 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1781 if (object_ == NULL)
1783 return CYGetProperty(context, object_, name);
1786 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1787 if (object_ == NULL)
1788 object_ = JSObjectMake(context, NULL, NULL);
1789 CYSetProperty(context, object_, name, value);
1793 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1794 Selector_privateData *internal(new Selector_privateData(sel));
1795 return JSObjectMake(context, Selector_, internal);
1798 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1799 Pointer *internal(new Pointer(pointer, context, owner, type));
1800 return JSObjectMake(context, Pointer_, internal);
1803 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1804 Functor_privateData *internal(new Functor_privateData(type, function));
1805 return JSObjectMake(context, Functor_, internal);
1808 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1810 // XXX: this could be much more efficient
1811 const char *string([CYCastNSString(NULL, value) UTF8String]);
1814 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1815 char *string(new(pool) char[size]);
1816 JSStringGetUTF8CString(value, string, size);
1821 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1822 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1825 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1826 return CYGetOffset(CYPoolCString(pool, value), index);
1829 // XXX: this macro is unhygenic
1830 #define CYCastCString(context, value) ({ \
1832 if (value == NULL) \
1834 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1835 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1836 utf8 = reinterpret_cast<char *>(alloca(size)); \
1837 JSStringGetUTF8CString(string, utf8, size); \
1838 JSStringRelease(string); \
1844 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1845 switch (JSValueGetType(context, value)) {
1848 /*case kJSTypeString:
1849 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1851 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1852 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1853 return internal->value_;
1856 double number(CYCastDouble(context, value));
1857 if (std::isnan(number))
1858 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1859 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1863 template <typename Type_>
1864 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1865 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1868 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1869 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1870 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1871 return reinterpret_cast<SEL>(internal->value_);
1873 return CYCastPointer<SEL>(context, value);
1876 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1877 switch (type->primitive) {
1878 case sig::boolean_P:
1879 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1882 #define CYPoolFFI_(primitive, native) \
1883 case sig::primitive ## _P: \
1884 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1887 CYPoolFFI_(uchar, unsigned char)
1888 CYPoolFFI_(char, char)
1889 CYPoolFFI_(ushort, unsigned short)
1890 CYPoolFFI_(short, short)
1891 CYPoolFFI_(ulong, unsigned long)
1892 CYPoolFFI_(long, long)
1893 CYPoolFFI_(uint, unsigned int)
1894 CYPoolFFI_(int, int)
1895 CYPoolFFI_(ulonglong, unsigned long long)
1896 CYPoolFFI_(longlong, long long)
1897 CYPoolFFI_(float, float)
1898 CYPoolFFI_(double, double)
1901 case sig::typename_P:
1902 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1905 case sig::selector_P:
1906 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1909 case sig::pointer_P:
1910 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1914 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1917 case sig::struct_P: {
1918 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1919 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1920 for (size_t index(0); index != type->data.signature.count; ++index) {
1921 sig::Element *element(&type->data.signature.elements[index]);
1922 ffi_type *field(ffi->elements[index]);
1925 if (aggregate == NULL)
1928 rhs = CYGetProperty(context, aggregate, index);
1929 if (JSValueIsUndefined(context, rhs)) {
1930 if (element->name != NULL)
1931 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1934 if (JSValueIsUndefined(context, rhs)) undefined:
1935 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1939 CYPoolFFI(pool, context, element->type, field, base, rhs);
1941 base += field->size;
1949 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1954 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1957 switch (type->primitive) {
1958 case sig::boolean_P:
1959 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1962 #define CYFromFFI_(primitive, native) \
1963 case sig::primitive ## _P: \
1964 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1967 CYFromFFI_(uchar, unsigned char)
1968 CYFromFFI_(char, char)
1969 CYFromFFI_(ushort, unsigned short)
1970 CYFromFFI_(short, short)
1971 CYFromFFI_(ulong, unsigned long)
1972 CYFromFFI_(long, long)
1973 CYFromFFI_(uint, unsigned int)
1974 CYFromFFI_(int, int)
1975 CYFromFFI_(ulonglong, unsigned long long)
1976 CYFromFFI_(longlong, long long)
1977 CYFromFFI_(float, float)
1978 CYFromFFI_(double, double)
1980 case sig::object_P: {
1981 if (id object = *reinterpret_cast<id *>(data)) {
1982 value = CYCastJSValue(context, object);
1988 case sig::typename_P:
1989 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1992 case sig::selector_P:
1993 if (SEL sel = *reinterpret_cast<SEL *>(data))
1994 value = CYMakeSelector(context, sel);
1998 case sig::pointer_P:
1999 if (void *pointer = *reinterpret_cast<void **>(data))
2000 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
2005 if (char *utf8 = *reinterpret_cast<char **>(data))
2006 value = CYCastJSValue(context, utf8);
2011 value = CYMakeStruct(context, data, type, ffi, owner);
2015 value = CYJSUndefined(context);
2019 value = CYJSNull(context);
2023 NSLog(@"CYFromFFI(%c)\n", type->primitive);
2030 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
2031 if (Method method = class_getInstanceMethod(_class, selector)) {
2035 method_getReturnType(method, type, sizeof(type));
2040 // XXX: possibly use a more "awesome" check?
2044 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
2046 return method_getTypeEncoding(method);
2047 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2048 return CYPoolCString(pool, type);
2053 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2054 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2056 JSContextRef context(internal->context_);
2058 size_t count(internal->cif_.nargs);
2059 JSValueRef values[count];
2061 for (size_t index(0); index != count; ++index)
2062 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2064 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2065 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2068 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2069 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2071 JSContextRef context(internal->context_);
2073 size_t count(internal->cif_.nargs);
2074 JSValueRef values[count];
2076 for (size_t index(0); index != count; ++index)
2077 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2079 JSObjectRef _this(CYCastJSObject(context, values[0]));
2081 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2082 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2085 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2086 // XXX: in case of exceptions this will leak
2087 // XXX: in point of fact, this may /need/ to leak :(
2088 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2090 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2091 NULL, sizeof(ffi_closure),
2092 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2096 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2097 _assert(status == FFI_OK);
2099 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2101 internal->value_ = closure;
2106 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2107 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2108 return JSObjectMake(context, Functor_, internal);
2111 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2112 JSValueRef exception(NULL);
2113 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2114 CYThrow(context, exception);
2117 JSObjectRef function(CYCastJSObject(context, value));
2118 return CYMakeFunctor(context, function, type);
2120 void (*function)()(CYCastPointer<void (*)()>(context, value));
2121 return CYMakeFunctor(context, function, type);
2125 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2126 Message_privateData *internal(new Message_privateData(sel, type, imp));
2127 return JSObjectMake(context, Message_, internal);
2130 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2131 JSObjectRef function(CYCastJSObject(context, value));
2132 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2133 return reinterpret_cast<IMP>(internal->GetValue());
2136 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2137 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2138 Class _class(internal->GetValue());
2141 const char *name(CYPoolCString(pool, property));
2143 if (SEL sel = sel_getUid(name))
2144 if (class_getInstanceMethod(_class, sel) != NULL)
2150 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2151 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2152 Class _class(internal->GetValue());
2155 const char *name(CYPoolCString(pool, property));
2157 if (SEL sel = sel_getUid(name))
2158 if (Method method = class_getInstanceMethod(_class, sel))
2159 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2164 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2165 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2166 Class _class(internal->GetValue());
2169 const char *name(CYPoolCString(pool, property));
2171 SEL sel(sel_registerName(name));
2173 Method method(class_getInstanceMethod(_class, sel));
2178 if (JSValueIsObjectOfClass(context, value, Message_)) {
2179 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2180 type = sig::Unparse(pool, &message->signature_);
2181 imp = reinterpret_cast<IMP>(message->GetValue());
2183 type = CYPoolTypeEncoding(pool, _class, sel, method);
2184 imp = CYMakeMessage(context, value, type);
2188 method_setImplementation(method, imp);
2190 class_replaceMethod(_class, sel, imp, type);
2196 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2197 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2198 Class _class(internal->GetValue());
2201 const char *name(CYPoolCString(pool, property));
2203 if (SEL sel = sel_getUid(name))
2204 if (Method method = class_getInstanceMethod(_class, sel)) {
2205 objc_method_list list = {NULL, 1, {method}};
2206 class_removeMethods(_class, &list);
2214 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2215 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2216 Class _class(internal->GetValue());
2219 Method *data(class_copyMethodList(_class, &size));
2220 for (size_t i(0); i != size; ++i)
2221 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2225 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2226 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2227 id self(internal->GetValue());
2229 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2233 NSString *name(CYCastNSString(pool, property));
2235 if (CYInternal *internal = CYInternal::Get(self))
2236 if (internal->HasProperty(context, property))
2239 Class _class(object_getClass(self));
2242 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2243 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2244 if ([self cy$hasProperty:name])
2246 } CYPoolCatch(false)
2248 const char *string(CYPoolCString(pool, name));
2250 if (class_getProperty(_class, string) != NULL)
2253 if (SEL sel = sel_getUid(string))
2254 if (CYImplements(self, _class, sel, true))
2260 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2261 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2262 id self(internal->GetValue());
2264 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2265 return Internal::Make(context, self, object);
2269 NSString *name(CYCastNSString(pool, property));
2271 if (CYInternal *internal = CYInternal::Get(self))
2272 if (JSValueRef value = internal->GetProperty(context, property))
2276 if (NSObject *data = [self cy$getProperty:name])
2277 return CYCastJSValue(context, data);
2280 const char *string(CYPoolCString(pool, name));
2281 Class _class(object_getClass(self));
2284 if (objc_property_t property = class_getProperty(_class, string)) {
2285 PropertyAttributes attributes(property);
2286 SEL sel(sel_registerName(attributes.Getter()));
2287 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2291 if (SEL sel = sel_getUid(string))
2292 if (CYImplements(self, _class, sel, true))
2293 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2299 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2300 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2301 id self(internal->GetValue());
2306 NSString *name(CYCastNSString(pool, property));
2307 NSString *data(CYCastNSObject(pool, context, value));
2310 if ([self cy$setProperty:name to:data])
2314 const char *string(CYPoolCString(pool, name));
2315 Class _class(object_getClass(self));
2318 if (objc_property_t property = class_getProperty(_class, string)) {
2319 PropertyAttributes attributes(property);
2320 if (const char *setter = attributes.Setter()) {
2321 SEL sel(sel_registerName(setter));
2322 JSValueRef arguments[1] = {value};
2323 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2329 size_t length(strlen(string));
2331 char set[length + 5];
2337 if (string[0] != '\0') {
2338 set[3] = toupper(string[0]);
2339 memcpy(set + 4, string + 1, length - 1);
2342 set[length + 3] = ':';
2343 set[length + 4] = '\0';
2345 if (SEL sel = sel_getUid(set))
2346 if (CYImplements(self, _class, sel, false)) {
2347 JSValueRef arguments[1] = {value};
2348 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2351 if (CYInternal *internal = CYInternal::Set(self)) {
2352 internal->SetProperty(context, property, value);
2360 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2361 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2362 id self(internal->GetValue());
2366 NSString *name(CYCastNSString(NULL, property));
2367 return [self cy$deleteProperty:name];
2372 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2373 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2374 id self(internal->GetValue());
2377 Class _class(object_getClass(self));
2381 objc_property_t *data(class_copyPropertyList(_class, &size));
2382 for (size_t i(0); i != size; ++i)
2383 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2388 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2390 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2391 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2396 static bool CYIsClass(id self) {
2397 // XXX: this is a lame object_isClass
2398 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2401 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2402 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2403 Class _class(internal->GetValue());
2404 if (!CYIsClass(_class))
2407 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2408 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2409 // XXX: this isn't always safe
2411 return [linternal->GetValue() isKindOfClass:_class];
2418 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2419 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2422 id self(internal->GetValue());
2423 const char *name(CYPoolCString(pool, property));
2425 if (object_getInstanceVariable(self, name, NULL) != NULL)
2431 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2432 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2436 id self(internal->GetValue());
2437 const char *name(CYPoolCString(pool, property));
2439 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2440 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2441 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2448 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2449 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2453 id self(internal->GetValue());
2454 const char *name(CYPoolCString(pool, property));
2456 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2457 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2458 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2466 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2467 if (Class super = class_getSuperclass(_class))
2468 Internal_getPropertyNames_(super, names);
2471 Ivar *data(class_copyIvarList(_class, &size));
2472 for (size_t i(0); i != size; ++i)
2473 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2477 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2478 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2481 id self(internal->GetValue());
2482 Class _class(object_getClass(self));
2484 Internal_getPropertyNames_(_class, names);
2487 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2488 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2489 return internal->GetOwner();
2492 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2493 Type_privateData *typical(internal->type_);
2494 sig::Type *type(typical->type_);
2498 const char *name(CYPoolCString(pool, property));
2499 size_t length(strlen(name));
2500 double number(CYCastDouble(name, length));
2502 size_t count(type->data.signature.count);
2504 if (std::isnan(number)) {
2505 if (property == NULL)
2508 sig::Element *elements(type->data.signature.elements);
2510 for (size_t local(0); local != count; ++local) {
2511 sig::Element *element(&elements[local]);
2512 if (element->name != NULL && strcmp(name, element->name) == 0) {
2520 index = static_cast<ssize_t>(number);
2521 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2526 ffi_type **elements(typical->GetFFI()->elements);
2528 base = reinterpret_cast<uint8_t *>(internal->value_);
2529 for (ssize_t local(0); local != index; ++local)
2530 base += elements[local]->size;
2535 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2536 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2537 Type_privateData *typical(internal->type_);
2539 ffi_type *ffi(typical->GetFFI());
2541 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2542 base += ffi->size * index;
2544 JSObjectRef owner(internal->GetOwner() ?: object);
2547 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2551 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2553 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2554 Type_privateData *typical(internal->type_);
2556 if (typical->type_ == NULL)
2560 if (!CYGetOffset(pool, property, offset))
2563 return Pointer_getIndex(context, object, offset, exception);
2566 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2567 return Pointer_getIndex(context, object, 0, exception);
2570 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2571 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2572 Type_privateData *typical(internal->type_);
2574 ffi_type *ffi(typical->GetFFI());
2576 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2577 base += ffi->size * index;
2580 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2585 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2587 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2588 Type_privateData *typical(internal->type_);
2590 if (typical->type_ == NULL)
2594 if (!CYGetOffset(pool, property, offset))
2597 return Pointer_setIndex(context, object, offset, value, exception);
2600 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2601 return Pointer_setIndex(context, object, 0, value, exception);
2604 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2605 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2606 Type_privateData *typical(internal->type_);
2607 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2610 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2612 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2613 Type_privateData *typical(internal->type_);
2618 if (!Index_(pool, internal, property, index, base))
2621 JSObjectRef owner(internal->GetOwner() ?: object);
2624 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2628 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2630 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2631 Type_privateData *typical(internal->type_);
2636 if (!Index_(pool, internal, property, index, base))
2640 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2645 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2646 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2647 Type_privateData *typical(internal->type_);
2648 sig::Type *type(typical->type_);
2653 size_t count(type->data.signature.count);
2654 sig::Element *elements(type->data.signature.elements);
2658 for (size_t index(0); index != count; ++index) {
2660 name = elements[index].name;
2663 sprintf(number, "%lu", index);
2667 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2671 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)()) {
2673 if (setups + count != signature->count - 1)
2674 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2676 size_t size(setups + count);
2678 memcpy(values, setup, sizeof(void *) * setups);
2680 for (size_t index(setups); index != size; ++index) {
2681 sig::Element *element(&signature->elements[index + 1]);
2682 ffi_type *ffi(cif->arg_types[index]);
2684 values[index] = new(pool) uint8_t[ffi->size];
2685 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2688 uint8_t value[cif->rtype->size];
2689 ffi_call(cif, function, value, values);
2691 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2695 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2698 NSString *name(CYCastNSString(pool, property));
2699 if (Class _class = NSClassFromString(name))
2700 return CYMakeInstance(context, _class, true);
2705 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2706 size_t size(objc_getClassList(NULL, 0));
2707 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2710 size_t writ(objc_getClassList(data, size));
2713 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2719 for (size_t i(0); i != writ; ++i)
2720 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2726 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2727 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2731 const char *name(CYPoolCString(pool, property));
2733 const char **data(objc_copyClassNamesForImage(internal, &size));
2735 for (size_t i(0); i != size; ++i)
2736 if (strcmp(name, data[i]) == 0) {
2737 if (Class _class = objc_getClass(name)) {
2738 value = CYMakeInstance(context, _class, true);
2750 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2751 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2753 const char **data(objc_copyClassNamesForImage(internal, &size));
2754 for (size_t i(0); i != size; ++i)
2755 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2759 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2762 const char *name(CYPoolCString(pool, property));
2764 const char **data(objc_copyImageNames(&size));
2765 for (size_t i(0); i != size; ++i)
2766 if (strcmp(name, data[i]) == 0) {
2775 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2776 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2781 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2783 const char **data(objc_copyImageNames(&size));
2784 for (size_t i(0); i != size; ++i)
2785 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2789 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2792 NSString *name(CYCastNSString(pool, property));
2793 if (Protocol *protocol = NSProtocolFromString(name))
2794 return CYMakeInstance(context, protocol, true);
2799 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2801 Protocol **data(objc_copyProtocolList(&size));
2802 for (size_t i(0); i != size; ++i)
2803 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2807 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
2808 Type_privateData *internal(new Type_privateData(NULL, type));
2809 return JSObjectMake(context, Type_privateData::Class, internal);
2812 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
2813 Type_privateData *internal(new Type_privateData(type));
2814 return JSObjectMake(context, Type_privateData::Class, internal);
2817 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2818 if (JSStringIsEqualToUTF8CString(property, "nil"))
2819 return Instance::Make(context, nil);
2823 NSString *name(CYCastNSString(pool, property));
2824 if (Class _class = NSClassFromString(name))
2825 return CYMakeInstance(context, _class, true);
2826 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2827 switch ([[entry objectAtIndex:0] intValue]) {
2829 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2831 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2833 // XXX: this is horrendously inefficient
2834 sig::Signature signature;
2835 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2837 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2838 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2840 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
2841 switch ([[entry objectAtIndex:0] intValue]) {
2842 // XXX: implement case 0
2844 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
2850 static bool stret(ffi_type *ffi_type) {
2851 return ffi_type->type == FFI_TYPE_STRUCT && (
2852 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2853 struct_forward_array[ffi_type->size] != 0
2858 int *_NSGetArgc(void);
2859 char ***_NSGetArgv(void);
2862 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2867 NSLog(@"%s", CYCastCString(context, arguments[0]));
2868 return CYJSUndefined(context);
2872 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2875 Class _class(object_getClass(self));
2876 if (Method method = class_getInstanceMethod(_class, _cmd))
2877 type = method_getTypeEncoding(method);
2881 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2883 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2884 type = CYPoolCString(pool, [method _typeString]);
2893 sig::Signature signature;
2894 sig::Parse(pool, &signature, type, &Structor_);
2897 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2899 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2900 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2903 static size_t Nonce_(0);
2905 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2907 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
2908 return CYCastJSValue(context, name);
2911 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2921 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2923 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2924 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2925 self = internal->GetValue();
2926 uninitialized = internal->IsUninitialized();
2928 internal->value_ = nil;
2930 self = CYCastNSObject(pool, context, arguments[0]);
2931 uninitialized = false;
2935 return CYJSNull(context);
2937 _cmd = CYCastSEL(context, arguments[1]);
2940 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2943 /* Hook: objc_registerClassPair {{{ */
2944 // XXX: replace this with associated objects
2946 MSHook(void, CYDealloc, id self, SEL sel) {
2947 CYInternal *internal;
2948 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2949 if (internal != NULL)
2951 _CYDealloc(self, sel);
2954 MSHook(void, objc_registerClassPair, Class _class) {
2955 Class super(class_getSuperclass(_class));
2956 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2957 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2958 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2961 _objc_registerClassPair(_class);
2964 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2967 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2969 Class _class(CYCastNSObject(pool, context, arguments[0]));
2970 $objc_registerClassPair(_class);
2971 return CYJSUndefined(context);
2976 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2977 JSGarbageCollect(context);
2978 return CYJSUndefined(context);
2981 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2982 JSValueRef setup[count + 2];
2985 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2986 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2989 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2991 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2993 // XXX: handle Instance::Uninitialized?
2994 id self(CYCastNSObject(pool, context, _this));
2998 setup[1] = &internal->sel_;
3000 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3003 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3005 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
3006 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3009 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3012 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
3013 const char *name(CYCastCString(context, arguments[0]));
3014 return CYMakeSelector(context, sel_registerName(name));
3018 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3021 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
3023 void *value(CYCastPointer<void *>(context, arguments[0]));
3024 const char *type(CYCastCString(context, arguments[1]));
3028 sig::Signature signature;
3029 sig::Parse(pool, &signature, type, &Structor_);
3031 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
3035 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3038 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
3039 const char *type(CYCastCString(context, arguments[0]));
3040 return CYMakeType(context, type);
3044 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3045 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3050 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3051 type.primitive = sig::pointer_P;
3052 type.data.data.size = 0;
3054 size_t index(CYGetIndex(NULL, property));
3055 if (index == _not(size_t))
3057 type.primitive = sig::array_P;
3058 type.data.data.size = index;
3064 type.data.data.type = internal->type_;
3066 return CYMakeType(context, &type);
3070 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3071 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3075 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3076 sig::Type *type(internal->type_);
3077 ffi_type *ffi(internal->GetFFI());
3079 uint8_t value[ffi->size];
3081 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3082 return CYFromFFI(context, type, ffi, value);
3086 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3089 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3090 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3092 sig::Type *type(internal->type_);
3095 if (type->primitive != sig::array_P)
3098 size = type->data.data.size;
3099 type = type->data.data.type;
3102 void *value(malloc(internal->GetFFI()->size));
3103 return CYMakePointer(context, value, type, NULL, NULL);
3107 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3110 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
3111 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3112 return Instance::Make(context, self);
3116 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3119 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
3120 const char *type(CYCastCString(context, arguments[1]));
3121 return CYMakeFunctor(context, arguments[0], type);
3125 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3126 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3127 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3130 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3131 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3132 Type_privateData *typical(internal->GetType());
3137 if (typical == NULL) {
3141 type = typical->type_;
3142 ffi = typical->ffi_;
3145 return CYMakePointer(context, &internal->value_, type, ffi, object);
3148 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3149 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3152 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3156 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3157 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3160 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3161 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3163 sprintf(string, "%p", internal->value_);
3166 return CYCastJSValue(context, string);
3170 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3171 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3172 return Instance::Make(context, object_getClass(internal->GetValue()));
3175 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3176 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3177 id self(internal->GetValue());
3178 if (!CYIsClass(self))
3179 return CYJSUndefined(context);
3181 return CYGetClassPrototype(context, self);
3185 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3186 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3187 id self(internal->GetValue());
3188 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3189 return CYJSUndefined(context);
3190 return Messages::Make(context, self);
3193 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3194 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3197 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3201 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
3206 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3207 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3210 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3214 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3215 // XXX: check for support of cy$toJSON?
3216 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3221 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3222 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3225 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3229 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3234 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3235 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3238 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3242 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3243 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3246 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3247 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3248 const char *name(sel_getName(internal->GetValue()));
3252 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3257 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3260 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
3262 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3263 Class _class(CYCastNSObject(pool, context, arguments[0]));
3264 SEL sel(internal->GetValue());
3265 Method method(class_getInstanceMethod(_class, sel));
3266 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3267 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3271 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3273 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3275 const char *type(sig::Unparse(pool, internal->type_));
3277 return CYCastJSValue(context, CYJSString(type));
3282 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3284 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3286 const char *type(sig::Unparse(pool, internal->type_));
3288 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
3293 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3294 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3297 static JSStaticValue CYValue_staticValues[2] = {
3298 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3299 {NULL, NULL, NULL, 0}
3302 static JSStaticValue Pointer_staticValues[2] = {
3303 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3304 {NULL, NULL, NULL, 0}
3307 static JSStaticFunction Pointer_staticFunctions[4] = {
3308 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3309 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3310 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3314 static JSStaticFunction Struct_staticFunctions[2] = {
3315 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3319 static JSStaticFunction Functor_staticFunctions[4] = {
3320 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3321 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3322 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3326 static JSStaticValue Instance_staticValues[5] = {
3327 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3328 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3329 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3330 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3331 {NULL, NULL, NULL, 0}
3334 static JSStaticFunction Instance_staticFunctions[5] = {
3335 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3336 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3337 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3338 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3342 static JSStaticFunction Internal_staticFunctions[2] = {
3343 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3347 static JSStaticFunction Selector_staticFunctions[5] = {
3348 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3349 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3350 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3351 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3355 static JSStaticFunction Type_staticFunctions[4] = {
3356 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3357 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3358 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3362 void CYSetArgs(int argc, const char *argv[]) {
3363 JSContextRef context(CYGetJSContext());
3364 JSValueRef args[argc];
3365 for (int i(0); i != argc; ++i)
3366 args[i] = CYCastJSValue(context, argv[i]);
3367 JSValueRef exception(NULL);
3368 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3369 CYThrow(context, exception);
3370 CYSetProperty(context, System_, CYJSString("args"), array);
3373 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3374 return JSContextGetGlobalObject(context);
3377 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3378 JSContextRef context(CYGetJSContext());
3379 JSValueRef exception(NULL), result;
3382 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3383 } catch (const char *error) {
3387 if (exception != NULL) { error:
3392 if (JSValueIsUndefined(context, result))
3398 json = CYPoolCCYON(pool, context, result, &exception);
3399 } catch (const char *error) {
3403 if (exception != NULL)
3406 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3410 static apr_pool_t *Pool_;
3414 const char * volatile data_;
3417 // XXX: this is "tre lame"
3418 @interface CYClient_ : NSObject {
3421 - (void) execute:(NSValue *)value;
3425 @implementation CYClient_
3427 - (void) execute:(NSValue *)value {
3428 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3429 const char *data(execute->data_);
3430 execute->data_ = NULL;
3431 execute->data_ = CYExecute(execute->pool_, data);
3440 apr_thread_t *thread_;
3442 CYClient(int socket) :
3448 _syscall(close(socket_));
3451 void Handle() { _pooled
3452 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3456 if (!CYRecvAll(socket_, &size, sizeof(size)))
3460 char *data(new(pool) char[size + 1]);
3461 if (!CYRecvAll(socket_, data, size))
3465 CYDriver driver("");
3466 cy::parser parser(driver);
3468 driver.data_ = data;
3469 driver.size_ = size;
3472 if (parser.parse() != 0 || !driver.errors_.empty()) {
3474 size = _not(size_t);
3476 CYContext context(driver.pool_);
3477 driver.program_->Replace(context);
3478 std::ostringstream str;
3480 out << *driver.program_;
3481 std::string code(str.str());
3482 CYExecute_ execute = {pool, code.c_str()};
3483 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3484 json = execute.data_;
3485 size = json == NULL ? _not(size_t) : strlen(json);
3488 if (!CYSendAll(socket_, &size, sizeof(size)))
3491 if (!CYSendAll(socket_, json, size))
3497 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3498 CYClient *client(reinterpret_cast<CYClient *>(data));
3504 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3505 CYClient *client(new(pool) CYClient(socket));
3506 apr_threadattr_t *attr;
3507 _aprcall(apr_threadattr_create(&attr, client->pool_));
3508 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3511 MSInitialize { _pooled
3512 _aprcall(apr_initialize());
3513 _aprcall(apr_pool_create(&Pool_, NULL));
3515 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3516 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3518 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3520 NSArray_ = objc_getClass("NSArray");
3521 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3522 NSCFType_ = objc_getClass("NSCFType");
3523 NSDictionary_ = objc_getClass("NSDictonary");
3524 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3525 NSZombie_ = objc_getClass("_NSZombie_");
3526 Object_ = objc_getClass("Object");
3529 JSGlobalContextRef CYGetJSContext() {
3530 if (Context_ == NULL) {
3531 JSClassDefinition definition;
3533 definition = kJSClassDefinitionEmpty;
3534 definition.className = "Functor";
3535 definition.staticFunctions = Functor_staticFunctions;
3536 definition.callAsFunction = &Functor_callAsFunction;
3537 definition.finalize = &Finalize;
3538 Functor_ = JSClassCreate(&definition);
3540 definition = kJSClassDefinitionEmpty;
3541 definition.className = "Instance";
3542 definition.staticValues = Instance_staticValues;
3543 definition.staticFunctions = Instance_staticFunctions;
3544 definition.hasProperty = &Instance_hasProperty;
3545 definition.getProperty = &Instance_getProperty;
3546 definition.setProperty = &Instance_setProperty;
3547 definition.deleteProperty = &Instance_deleteProperty;
3548 definition.getPropertyNames = &Instance_getPropertyNames;
3549 definition.callAsConstructor = &Instance_callAsConstructor;
3550 definition.hasInstance = &Instance_hasInstance;
3551 definition.finalize = &Finalize;
3552 Instance_ = JSClassCreate(&definition);
3554 definition = kJSClassDefinitionEmpty;
3555 definition.className = "Internal";
3556 definition.staticFunctions = Internal_staticFunctions;
3557 definition.hasProperty = &Internal_hasProperty;
3558 definition.getProperty = &Internal_getProperty;
3559 definition.setProperty = &Internal_setProperty;
3560 definition.getPropertyNames = &Internal_getPropertyNames;
3561 definition.finalize = &Finalize;
3562 Internal_ = JSClassCreate(&definition);
3564 definition = kJSClassDefinitionEmpty;
3565 definition.className = "Message";
3566 definition.staticFunctions = Functor_staticFunctions;
3567 definition.callAsFunction = &Message_callAsFunction;
3568 definition.finalize = &Finalize;
3569 Message_ = JSClassCreate(&definition);
3571 definition = kJSClassDefinitionEmpty;
3572 definition.className = "Messages";
3573 definition.hasProperty = &Messages_hasProperty;
3574 definition.getProperty = &Messages_getProperty;
3575 definition.setProperty = &Messages_setProperty;
3577 definition.deleteProperty = &Messages_deleteProperty;
3579 definition.getPropertyNames = &Messages_getPropertyNames;
3580 definition.finalize = &Finalize;
3581 Messages_ = JSClassCreate(&definition);
3583 definition = kJSClassDefinitionEmpty;
3584 definition.className = "NSArrayPrototype";
3585 //definition.hasProperty = &NSArrayPrototype_hasProperty;
3586 //definition.getProperty = &NSArrayPrototype_getProperty;
3587 //definition.setProperty = &NSArrayPrototype_setProperty;
3588 //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
3589 //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
3590 NSArrayPrototype_ = JSClassCreate(&definition);
3592 definition = kJSClassDefinitionEmpty;
3593 definition.className = "Pointer";
3594 definition.staticValues = Pointer_staticValues;
3595 definition.staticFunctions = Pointer_staticFunctions;
3596 definition.getProperty = &Pointer_getProperty;
3597 definition.setProperty = &Pointer_setProperty;
3598 definition.finalize = &Finalize;
3599 Pointer_ = JSClassCreate(&definition);
3601 definition = kJSClassDefinitionEmpty;
3602 definition.className = "Selector";
3603 definition.staticValues = CYValue_staticValues;
3604 definition.staticFunctions = Selector_staticFunctions;
3605 definition.callAsFunction = &Selector_callAsFunction;
3606 definition.finalize = &Finalize;
3607 Selector_ = JSClassCreate(&definition);
3609 definition = kJSClassDefinitionEmpty;
3610 definition.className = "Struct";
3611 definition.staticFunctions = Struct_staticFunctions;
3612 definition.getProperty = &Struct_getProperty;
3613 definition.setProperty = &Struct_setProperty;
3614 definition.getPropertyNames = &Struct_getPropertyNames;
3615 definition.finalize = &Finalize;
3616 Struct_ = JSClassCreate(&definition);
3618 definition = kJSClassDefinitionEmpty;
3619 definition.className = "Type";
3620 definition.staticFunctions = Type_staticFunctions;
3621 definition.getProperty = &Type_getProperty;
3622 definition.callAsFunction = &Type_callAsFunction;
3623 definition.callAsConstructor = &Type_callAsConstructor;
3624 definition.finalize = &Finalize;
3625 // XXX: dude: just rename the damned variable
3626 (Type_privateData::Class) = JSClassCreate(&definition);
3628 definition = kJSClassDefinitionEmpty;
3629 definition.className = "Runtime";
3630 definition.getProperty = &Runtime_getProperty;
3631 Runtime_ = JSClassCreate(&definition);
3633 definition = kJSClassDefinitionEmpty;
3634 definition.className = "ObjectiveC::Classes";
3635 definition.getProperty = &ObjectiveC_Classes_getProperty;
3636 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3637 ObjectiveC_Classes_ = JSClassCreate(&definition);
3639 definition = kJSClassDefinitionEmpty;
3640 definition.className = "ObjectiveC::Images";
3641 definition.getProperty = &ObjectiveC_Images_getProperty;
3642 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3643 ObjectiveC_Images_ = JSClassCreate(&definition);
3645 definition = kJSClassDefinitionEmpty;
3646 definition.className = "ObjectiveC::Image::Classes";
3647 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3648 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3649 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3651 definition = kJSClassDefinitionEmpty;
3652 definition.className = "ObjectiveC::Protocols";
3653 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3654 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3655 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3657 definition = kJSClassDefinitionEmpty;
3658 //definition.getProperty = &Global_getProperty;
3659 JSClassRef Global(JSClassCreate(&definition));
3661 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3664 JSObjectRef global(CYGetGlobalObject(context));
3666 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3667 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3668 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3670 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3671 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3672 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3674 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3675 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3676 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3678 length_ = JSStringCreateWithUTF8CString("length");
3679 message_ = JSStringCreateWithUTF8CString("message");
3680 name_ = JSStringCreateWithUTF8CString("name");
3681 prototype_ = JSStringCreateWithUTF8CString("prototype");
3682 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3683 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3685 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3686 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3688 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3689 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3690 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3691 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3693 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3694 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3695 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3696 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3698 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3700 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3701 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3702 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3703 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3705 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3706 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3707 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3708 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3709 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class, &Type_new));
3711 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3714 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3717 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
3718 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
3719 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
3721 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3722 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3723 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3725 System_ = JSObjectMake(context, NULL, NULL);
3726 CYSetProperty(context, global, CYJSString("system"), System_);
3727 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3728 //CYSetProperty(context, System_, CYJSString("global"), global);
3730 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3732 Result_ = JSStringCreateWithUTF8CString("_");
3734 JSValueProtect(context, Array_);
3735 JSValueProtect(context, Function_);
3736 JSValueProtect(context, String_);
3738 JSValueProtect(context, Instance_prototype_);
3739 JSValueProtect(context, Object_prototype_);
3741 JSValueProtect(context, Array_prototype_);
3742 JSValueProtect(context, Array_pop_);
3743 JSValueProtect(context, Array_push_);
3744 JSValueProtect(context, Array_splice_);