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>
45 #include "cycript.hpp"
47 #include "sig/parse.hpp"
48 #include "sig/ffi_type.hpp"
50 #include "Pooling.hpp"
57 #include <CoreFoundation/CoreFoundation.h>
58 #include <CoreFoundation/CFLogUtilities.h>
59 #include <JavaScriptCore/JSStringRefCF.h>
64 #include <WebKit/WebScriptObject.h>
66 #include <Foundation/Foundation.h>
72 #include <ext/stdio_filebuf.h>
80 #include "Cycript.tab.hh"
86 #define _throw(name, args...) \
87 @throw [NSException exceptionWithName:name reason:[NSString stringWithFormat:@args] userInfo:nil]
89 #define _throw(name, args...) \
93 #define _assert(test) do { \
95 _throw(NSInternalInconsistencyException, "*** _assert(%s):%s(%u):%s [errno=%d]", #test, __FILE__, __LINE__, __FUNCTION__, errno); \
98 #define _trace() do { \
99 fprintf(stderr, "_trace():%u\n", __LINE__); \
105 catch (NSException *error) { \
106 CYThrow(context, error, exception); \
109 *exception = CYCastJSValue(context, "catch(...)"); \
114 #define CYPoolTry { \
116 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
118 #define CYPoolCatch(value) \
119 @catch (NSException *error) { \
120 _saved = [error retain]; \
126 [_saved autorelease]; \
131 #define CYPoolCatch }
135 #define class_getSuperclass GSObjCSuper
136 #define object_getClass GSObjCClass
139 void CYThrow(JSContextRef context, JSValueRef value);
141 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception);
142 JSStringRef CYCopyJSString(const char *value);
144 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value);
146 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)());
147 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
149 struct CYUTF8String {
153 CYUTF8String(const char *data, size_t size) :
160 struct CYUTF16String {
161 const uint16_t *data;
164 CYUTF16String(const uint16_t *data, size_t size) :
171 /* JavaScript Properties {{{ */
172 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
173 JSValueRef exception(NULL);
174 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
175 CYThrow(context, exception);
179 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
180 JSValueRef exception(NULL);
181 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
182 CYThrow(context, exception);
186 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
187 JSValueRef exception(NULL);
188 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
189 CYThrow(context, exception);
192 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
193 JSValueRef exception(NULL);
194 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
195 CYThrow(context, exception);
198 /* JavaScript Strings {{{ */
199 JSStringRef CYCopyJSString(const char *value) {
200 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
203 JSStringRef CYCopyJSString(JSStringRef value) {
204 return value == NULL ? NULL : JSStringRetain(value);
207 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
208 if (JSValueIsNull(context, value))
210 JSValueRef exception(NULL);
211 JSStringRef string(JSValueToStringCopy(context, value, &exception));
212 CYThrow(context, exception);
222 JSStringRelease(string_);
226 CYJSString(const CYJSString &rhs) :
227 string_(CYCopyJSString(rhs.string_))
231 template <typename Arg0_>
232 CYJSString(Arg0_ arg0) :
233 string_(CYCopyJSString(arg0))
237 template <typename Arg0_, typename Arg1_>
238 CYJSString(Arg0_ arg0, Arg1_ arg1) :
239 string_(CYCopyJSString(arg0, arg1))
243 CYJSString &operator =(const CYJSString &rhs) {
245 string_ = CYCopyJSString(rhs.string_);
258 operator JSStringRef() const {
264 // XXX: this macro is unhygenic
265 #define CYCastCString_(string) ({ \
267 if (string == NULL) \
270 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
271 utf8 = reinterpret_cast<char *>(alloca(size)); \
272 JSStringGetUTF8CString(string, utf8, size); \
277 // XXX: this macro is unhygenic
278 #define CYCastCString(context, value) ({ \
282 else if (JSStringRef string = CYCopyJSString(context, value)) { \
283 utf8 = CYCastCString_(string); \
284 JSStringRelease(string); \
293 /* Objective-C Pool Release {{{ */
294 apr_status_t CYPoolRelease_(void *data) {
295 id object(reinterpret_cast<id>(data));
300 id CYPoolRelease_(apr_pool_t *pool, id object) {
303 else if (pool == NULL)
304 return [object autorelease];
306 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
311 template <typename Type_>
312 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
313 return (Type_) CYPoolRelease_(pool, (id) object);
316 /* Objective-C Strings {{{ */
317 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
319 return [value UTF8String];
321 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
322 char *string(new(pool) char[size]);
323 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
324 _throw(NSInternalInconsistencyException, "[NSString getCString:maxLength:encoding:] == NO");
329 JSStringRef CYCopyJSString_(NSString *value) {
331 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
334 return CYCopyJSString(CYPoolCString(pool, value));
338 JSStringRef CYCopyJSString(id value) {
341 // XXX: this definition scares me; is anyone using this?!
342 NSString *string([value description]);
343 return CYCopyJSString_(string);
346 NSString *CYCopyNSString(const CYUTF8String &value) {
348 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
350 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
354 NSString *CYCopyNSString(JSStringRef value) {
356 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
358 return CYCopyNSString(CYCastCString_(value));
362 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
363 return CYCopyNSString(CYJSString(context, value));
366 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
367 return CYPoolRelease(pool, CYCopyNSString(value));
370 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
371 const char *name(sel_getName(sel));
372 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
375 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
376 return CYPoolRelease(pool, CYCopyNSString(value));
379 CYUTF8String CYCastUTF8String(NSString *value) {
380 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
381 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
386 /* JavaScript Stringify {{{ */
387 void CYStringify(std::ostringstream &str, const char *data, size_t size) {
388 unsigned quot(0), apos(0);
389 for (const char *value(data), *end(data + size); value != end; ++value)
392 else if (*value == '\'')
395 bool single(quot > apos);
397 str << (single ? '\'' : '"');
399 for (const char *value(data), *end(data + size); value != end; ++value)
401 case '\\': str << "\\\\"; break;
402 case '\b': str << "\\b"; break;
403 case '\f': str << "\\f"; break;
404 case '\n': str << "\\n"; break;
405 case '\r': str << "\\r"; break;
406 case '\t': str << "\\t"; break;
407 case '\v': str << "\\v"; break;
422 if (*value < 0x20 || *value >= 0x7f)
423 str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(*value);
428 str << (single ? '\'' : '"');
432 static JSGlobalContextRef Context_;
433 static JSObjectRef System_;
435 static JSClassRef Functor_;
436 static JSClassRef Pointer_;
437 static JSClassRef Runtime_;
438 static JSClassRef Struct_;
441 static JSObjectRef ObjectiveC_;
443 static JSClassRef Instance_;
444 static JSClassRef Internal_;
445 static JSClassRef Message_;
446 static JSClassRef Messages_;
447 static JSClassRef Selector_;
448 static JSClassRef Super_;
450 static JSClassRef ObjectiveC_Classes_;
451 static JSClassRef ObjectiveC_Image_Classes_;
452 static JSClassRef ObjectiveC_Images_;
453 static JSClassRef ObjectiveC_Protocols_;
455 static JSObjectRef Instance_prototype_;
458 static JSObjectRef Array_;
459 static JSObjectRef Function_;
460 static JSObjectRef String_;
462 static JSStringRef Result_;
464 static JSStringRef length_;
465 static JSStringRef message_;
466 static JSStringRef name_;
467 static JSStringRef prototype_;
468 static JSStringRef toCYON_;
469 static JSStringRef toJSON_;
471 static JSObjectRef Object_prototype_;
473 static JSObjectRef Array_prototype_;
474 static JSObjectRef Array_pop_;
475 static JSObjectRef Array_push_;
476 static JSObjectRef Array_splice_;
480 static Class NSCFBoolean_;
481 static Class NSCFType_;
484 static Class NSArray_;
485 static Class NSDictionary_;
486 static Class NSMessageBuilder_;
487 static Class NSZombie_;
488 static Class Object_;
491 static NSArray *Bridge_;
493 static void Finalize(JSObjectRef object) {
494 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
497 class Type_privateData;
507 CYValue(const void *value) :
508 value_(const_cast<void *>(value))
512 CYValue(const CYValue &rhs) :
517 virtual Type_privateData *GetType() const {
526 JSContextRef context_;
530 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
536 JSValueProtect(context_, owner_);
541 JSValueUnprotect(context_, owner_);
544 JSObjectRef GetOwner() const {
550 struct Selector_privateData :
553 Selector_privateData(SEL value) :
558 SEL GetValue() const {
559 return reinterpret_cast<SEL>(value_);
562 virtual Type_privateData *GetType() const;
565 // XXX: trick this out with associated objects!
566 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
568 return Instance_prototype_;
570 // XXX: I need to think through multi-context
571 typedef std::map<id, JSValueRef> CacheMap;
572 static CacheMap cache_;
574 JSValueRef &value(cache_[self]);
578 JSClassRef _class(NULL);
579 JSValueRef prototype;
581 if (self == NSArray_)
582 prototype = Array_prototype_;
583 else if (self == NSDictionary_)
584 prototype = Object_prototype_;
586 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
588 JSObjectRef object(JSObjectMake(context, _class, NULL));
589 JSObjectSetPrototype(context, object, prototype);
591 JSValueProtect(context, object);
601 Transient = (1 << 0),
602 Uninitialized = (1 << 1),
607 Instance(id value, Flags flags) :
613 virtual ~Instance() {
614 if ((flags_ & Transient) == 0)
615 // XXX: does this handle background threads correctly?
616 // XXX: this simply does not work on the console because I'm stupid
617 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
620 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
621 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
622 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
626 id GetValue() const {
627 return reinterpret_cast<id>(value_);
630 bool IsUninitialized() const {
631 return (flags_ & Uninitialized) != 0;
634 virtual Type_privateData *GetType() const;
642 Super(id value, Class _class) :
643 Instance(value, Instance::Transient),
648 static JSObjectRef Make(JSContextRef context, id object, Class _class) {
649 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
657 Messages(Class value) :
662 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
663 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
664 if (_class == NSArray_)
666 if (Class super = class_getSuperclass(_class))
667 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
669 JSObjectSetPrototype(context, value, Array_prototype_);*/
673 Class GetValue() const {
674 return reinterpret_cast<Class>(value_);
681 Internal(id value, JSContextRef context, JSObjectRef owner) :
682 CYOwned(value, context, owner)
686 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
687 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
690 id GetValue() const {
691 return reinterpret_cast<id>(value_);
698 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
700 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
701 lhs.name = apr_pstrdup(pool, rhs.name);
702 if (rhs.type == NULL)
705 lhs.type = new(pool) Type;
706 Copy(pool, *lhs.type, *rhs.type);
708 lhs.offset = rhs.offset;
711 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
712 size_t count(rhs.count);
714 lhs.elements = new(pool) Element[count];
715 for (size_t index(0); index != count; ++index)
716 Copy(pool, lhs.elements[index], rhs.elements[index]);
719 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
720 lhs.primitive = rhs.primitive;
721 lhs.name = apr_pstrdup(pool, rhs.name);
722 lhs.flags = rhs.flags;
724 if (sig::IsAggregate(rhs.primitive))
725 Copy(pool, lhs.data.signature, rhs.data.signature);
727 sig::Type *&lht(lhs.data.data.type);
728 sig::Type *&rht(rhs.data.data.type);
733 lht = new(pool) Type;
734 Copy(pool, *lht, *rht);
737 lhs.data.data.size = rhs.data.data.size;
741 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
743 lhs.alignment = rhs.alignment;
745 if (rhs.elements == NULL)
749 while (rhs.elements[count] != NULL)
752 lhs.elements = new(pool) ffi_type *[count + 1];
753 lhs.elements[count] = NULL;
755 for (size_t index(0); index != count; ++index) {
756 // XXX: if these are libffi native then you can just take them
757 ffi_type *ffi(new(pool) ffi_type);
758 lhs.elements[index] = ffi;
759 sig::Copy(pool, *ffi, *rhs.elements[index]);
766 struct CStringMapLess :
767 std::binary_function<const char *, const char *, bool>
769 _finline bool operator ()(const char *lhs, const char *rhs) const {
770 return strcmp(lhs, rhs) < 0;
774 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
779 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
780 switch ([[entry objectAtIndex:0] intValue]) {
782 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
786 sig::Signature signature;
787 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
788 type = signature.elements[0].type;
794 struct Type_privateData :
798 static Type_privateData *Object;
799 static Type_privateData *Selector;
802 static JSClassRef Class_;
807 void Set(sig::Type *type) {
808 type_ = new(pool_) sig::Type;
809 sig::Copy(pool_, *type_, *type);
812 Type_privateData(apr_pool_t *pool, const char *type) :
818 sig::Signature signature;
819 sig::Parse(pool_, &signature, type, &Structor_);
820 type_ = signature.elements[0].type;
823 Type_privateData(sig::Type *type) :
830 Type_privateData(sig::Type *type, ffi_type *ffi) {
831 ffi_ = new(pool_) ffi_type;
832 sig::Copy(pool_, *ffi_, *ffi);
838 ffi_ = new(pool_) ffi_type;
840 sig::Element element;
842 element.type = type_;
845 sig::Signature signature;
846 signature.elements = &element;
850 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
858 JSClassRef Type_privateData::Class_;
861 Type_privateData *Type_privateData::Object;
862 Type_privateData *Type_privateData::Selector;
864 Type_privateData *Instance::GetType() const {
865 return Type_privateData::Object;
868 Type_privateData *Selector_privateData::GetType() const {
869 return Type_privateData::Selector;
876 Type_privateData *type_;
878 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
879 CYOwned(value, context, owner),
880 type_(new(pool_) Type_privateData(type))
885 struct Struct_privateData :
888 Type_privateData *type_;
890 Struct_privateData(JSContextRef context, JSObjectRef owner) :
891 CYOwned(NULL, context, owner)
896 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
897 static TypeMap Types_;
899 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
900 Struct_privateData *internal(new Struct_privateData(context, owner));
901 apr_pool_t *pool(internal->pool_);
902 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
903 internal->type_ = typical;
906 internal->value_ = data;
908 size_t size(typical->GetFFI()->size);
909 void *copy(apr_palloc(internal->pool_, size));
910 memcpy(copy, data, size);
911 internal->value_ = copy;
914 return JSObjectMake(context, Struct_, internal);
917 struct Functor_privateData :
920 sig::Signature signature_;
924 Functor_privateData(const char *type, void (*value)()) :
925 CYValue(reinterpret_cast<void *>(value))
927 sig::Parse(pool_, &signature_, type, &Structor_);
928 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
931 void (*GetValue())() const {
932 return reinterpret_cast<void (*)()>(value_);
936 struct Closure_privateData :
939 JSContextRef context_;
940 JSObjectRef function_;
942 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
943 Functor_privateData(type, NULL),
947 JSValueProtect(context_, function_);
950 virtual ~Closure_privateData() {
951 JSValueUnprotect(context_, function_);
956 struct Message_privateData :
961 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
962 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
968 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
969 Instance::Flags flags;
972 flags = Instance::Transient;
974 flags = Instance::None;
975 object = [object retain];
978 return Instance::Make(context, object, flags);
982 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
983 return JSValueMakeBoolean(context, value);
986 JSValueRef CYCastJSValue(JSContextRef context, double value) {
987 return JSValueMakeNumber(context, value);
990 #define CYCastJSValue_(Type_) \
991 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
992 return JSValueMakeNumber(context, static_cast<double>(value)); \
996 CYCastJSValue_(unsigned int)
997 CYCastJSValue_(long int)
998 CYCastJSValue_(long unsigned int)
999 CYCastJSValue_(long long int)
1000 CYCastJSValue_(long long unsigned int)
1002 JSValueRef CYJSUndefined(JSContextRef context) {
1003 return JSValueMakeUndefined(context);
1006 size_t CYGetIndex(const CYUTF8String &value) {
1007 if (value.data[0] != '0') {
1009 size_t index(strtoul(value.data, &end, 10));
1010 if (value.data + value.size == end)
1012 } else if (value.data[1] == '\0')
1014 return _not(size_t);
1018 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value);
1020 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
1021 return CYGetIndex(CYPoolUTF8String(pool, value));
1024 bool CYGetOffset(const char *value, ssize_t &index) {
1025 if (value[0] != '0') {
1027 index = strtol(value, &end, 10);
1028 if (value + strlen(value) == end)
1030 } else if (value[1] == '\0') {
1039 size_t CYGetIndex(NSString *value) {
1040 return CYGetIndex(CYCastUTF8String(value));
1043 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
1044 return CYGetOffset(CYPoolCString(pool, value), index);
1049 @interface NSMethodSignature (Cycript)
1050 - (NSString *) _typeString;
1053 @interface NSObject (Cycript)
1055 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1056 - (JSType) cy$JSType;
1058 - (NSObject *) cy$toJSON:(NSString *)key;
1059 - (NSString *) cy$toCYON;
1060 - (NSString *) cy$toKey;
1062 - (bool) cy$hasProperty:(NSString *)name;
1063 - (NSObject *) cy$getProperty:(NSString *)name;
1064 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
1065 - (bool) cy$deleteProperty:(NSString *)name;
1070 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1073 @interface NSString (Cycript)
1074 - (void *) cy$symbol;
1079 NSString *CYCastNSCYON(id value) {
1085 Class _class(object_getClass(value));
1086 SEL sel(@selector(cy$toCYON));
1088 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
1089 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1090 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1091 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1092 string = [value cy$toCYON];
1095 if (value == NSZombie_)
1096 string = @"_NSZombie_";
1097 else if (_class == NSZombie_)
1098 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1099 // XXX: frowny /in/ the pants
1100 else if (value == NSMessageBuilder_ || value == Object_)
1103 string = [NSString stringWithFormat:@"%@", value];
1106 // XXX: frowny pants
1108 string = @"undefined";
1117 struct PropertyAttributes {
1122 const char *variable;
1124 const char *getter_;
1125 const char *setter_;
1135 PropertyAttributes(objc_property_t property) :
1147 name = property_getName(property);
1148 const char *attributes(property_getAttributes(property));
1150 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
1152 case 'R': readonly = true; break;
1153 case 'C': copy = true; break;
1154 case '&': retain = true; break;
1155 case 'N': nonatomic = true; break;
1156 case 'G': getter_ = token + 1; break;
1157 case 'S': setter_ = token + 1; break;
1158 case 'V': variable = token + 1; break;
1162 /*if (variable == NULL) {
1163 variable = property_getName(property);
1164 size_t size(strlen(variable));
1165 char *name(new(pool_) char[size + 2]);
1167 memcpy(name + 1, variable, size);
1168 name[size + 1] = '\0';
1173 const char *Getter() {
1174 if (getter_ == NULL)
1175 getter_ = apr_pstrdup(pool_, name);
1179 const char *Setter() {
1180 if (setter_ == NULL && !readonly) {
1181 size_t length(strlen(name));
1183 char *temp(new(pool_) char[length + 5]);
1189 temp[3] = toupper(name[0]);
1190 memcpy(temp + 4, name + 1, length - 1);
1193 temp[length + 3] = ':';
1194 temp[length + 4] = '\0';
1207 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
1208 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
1215 @interface CYWebUndefined : NSObject {
1218 + (CYWebUndefined *) undefined;
1222 @implementation CYWebUndefined
1224 + (CYWebUndefined *) undefined {
1225 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
1231 #define WebUndefined CYWebUndefined
1236 /* Bridge: NSArray {{{ */
1237 @implementation NSArray (Cycript)
1239 - (NSString *) cy$toCYON {
1240 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1241 [json appendString:@"["];
1245 for (id object in self) {
1248 for (size_t index(0), count([self count]); index != count; ++index) {
1249 object = [self objectAtIndex:index];
1252 [json appendString:@","];
1255 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
1256 [json appendString:CYCastNSCYON(object)];
1258 [json appendString:@","];
1263 [json appendString:@"]"];
1267 - (bool) cy$hasProperty:(NSString *)name {
1268 if ([name isEqualToString:@"length"])
1271 size_t index(CYGetIndex(name));
1272 if (index == _not(size_t) || index >= [self count])
1273 return [super cy$hasProperty:name];
1278 - (NSObject *) cy$getProperty:(NSString *)name {
1279 if ([name isEqualToString:@"length"]) {
1280 NSUInteger count([self count]);
1282 return [NSNumber numberWithUnsignedInteger:count];
1284 return [NSNumber numberWithUnsignedInt:count];
1288 size_t index(CYGetIndex(name));
1289 if (index == _not(size_t) || index >= [self count])
1290 return [super cy$getProperty:name];
1292 return [self objectAtIndex:index];
1297 /* Bridge: NSDictionary {{{ */
1298 @implementation NSDictionary (Cycript)
1300 - (NSString *) cy$toCYON {
1301 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1302 [json appendString:@"{"];
1306 for (id key in self) {
1308 NSEnumerator *keys([self keyEnumerator]);
1309 while (id key = [keys nextObject]) {
1312 [json appendString:@","];
1315 [json appendString:[key cy$toKey]];
1316 [json appendString:@":"];
1317 NSObject *object([self objectForKey:key]);
1318 [json appendString:CYCastNSCYON(object)];
1321 [json appendString:@"}"];
1325 - (bool) cy$hasProperty:(NSString *)name {
1326 return [self objectForKey:name] != nil;
1329 - (NSObject *) cy$getProperty:(NSString *)name {
1330 return [self objectForKey:name];
1335 /* Bridge: NSMutableArray {{{ */
1336 @implementation NSMutableArray (Cycript)
1338 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1339 if ([name isEqualToString:@"length"]) {
1340 // XXX: is this not intelligent?
1341 NSNumber *number(reinterpret_cast<NSNumber *>(value));
1343 NSUInteger size([number unsignedIntegerValue]);
1345 NSUInteger size([number unsignedIntValue]);
1347 NSUInteger count([self count]);
1349 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1350 else if (size != count) {
1351 WebUndefined *undefined([WebUndefined undefined]);
1352 for (size_t i(count); i != size; ++i)
1353 [self addObject:undefined];
1358 size_t index(CYGetIndex(name));
1359 if (index == _not(size_t))
1360 return [super cy$setProperty:name to:value];
1362 id object(value ?: [NSNull null]);
1364 size_t count([self count]);
1366 [self replaceObjectAtIndex:index withObject:object];
1368 if (index != count) {
1369 WebUndefined *undefined([WebUndefined undefined]);
1370 for (size_t i(count); i != index; ++i)
1371 [self addObject:undefined];
1374 [self addObject:object];
1380 - (bool) cy$deleteProperty:(NSString *)name {
1381 size_t index(CYGetIndex(name));
1382 if (index == _not(size_t) || index >= [self count])
1383 return [super cy$deleteProperty:name];
1384 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1390 /* Bridge: NSMutableDictionary {{{ */
1391 @implementation NSMutableDictionary (Cycript)
1393 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1394 [self setObject:(value ?: [NSNull null]) forKey:name];
1398 - (bool) cy$deleteProperty:(NSString *)name {
1399 if ([self objectForKey:name] == nil)
1402 [self removeObjectForKey:name];
1409 /* Bridge: NSNumber {{{ */
1410 @implementation NSNumber (Cycript)
1412 - (JSType) cy$JSType {
1414 // XXX: this just seems stupid
1415 if ([self class] == NSCFBoolean_)
1416 return kJSTypeBoolean;
1418 return kJSTypeNumber;
1421 - (NSObject *) cy$toJSON:(NSString *)key {
1425 - (NSString *) cy$toCYON {
1426 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1429 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1430 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1435 /* Bridge: NSNull {{{ */
1436 @implementation NSNull (Cycript)
1438 - (JSType) cy$JSType {
1442 - (NSObject *) cy$toJSON:(NSString *)key {
1446 - (NSString *) cy$toCYON {
1452 /* Bridge: NSObject {{{ */
1453 @implementation NSObject (Cycript)
1455 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1456 return CYMakeInstance(context, self, false);
1459 - (JSType) cy$JSType {
1460 return kJSTypeObject;
1463 - (NSObject *) cy$toJSON:(NSString *)key {
1464 return [self description];
1467 - (NSString *) cy$toCYON {
1468 return [[self cy$toJSON:@""] cy$toCYON];
1471 - (NSString *) cy$toKey {
1472 return [self cy$toCYON];
1475 - (bool) cy$hasProperty:(NSString *)name {
1479 - (NSObject *) cy$getProperty:(NSString *)name {
1483 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1487 - (bool) cy$deleteProperty:(NSString *)name {
1493 /* Bridge: NSProxy {{{ */
1494 @implementation NSProxy (Cycript)
1496 - (NSObject *) cy$toJSON:(NSString *)key {
1497 return [self description];
1500 - (NSString *) cy$toCYON {
1501 return [[self cy$toJSON:@""] cy$toCYON];
1506 /* Bridge: NSString {{{ */
1507 @implementation NSString (Cycript)
1509 - (JSType) cy$JSType {
1510 return kJSTypeString;
1513 - (NSObject *) cy$toJSON:(NSString *)key {
1517 - (NSString *) cy$toCYON {
1518 std::ostringstream str;
1519 CYUTF8String string(CYCastUTF8String(self));
1520 CYStringify(str, string.data, string.size);
1521 std::string value(str.str());
1522 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1525 - (NSString *) cy$toKey {
1526 const char *value([self UTF8String]);
1527 size_t size(strlen(value));
1532 if (DigitRange_[value[0]]) {
1533 size_t index(CYGetIndex(self));
1534 if (index == _not(size_t))
1537 if (!WordStartRange_[value[0]])
1539 for (size_t i(1); i != size; ++i)
1540 if (!WordEndRange_[value[i]])
1547 return [self cy$toCYON];
1550 - (void *) cy$symbol {
1552 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1557 /* Bridge: WebUndefined {{{ */
1558 @implementation WebUndefined (Cycript)
1560 - (JSType) cy$JSType {
1561 return kJSTypeUndefined;
1564 - (NSObject *) cy$toJSON:(NSString *)key {
1568 - (NSString *) cy$toCYON {
1569 return @"undefined";
1572 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1573 return CYJSUndefined(context);
1579 /* Bridge: CYJSObject {{{ */
1580 @interface CYJSObject : NSMutableDictionary {
1581 JSObjectRef object_;
1582 JSContextRef context_;
1585 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1587 - (NSObject *) cy$toJSON:(NSString *)key;
1589 - (NSUInteger) count;
1590 - (id) objectForKey:(id)key;
1591 - (NSEnumerator *) keyEnumerator;
1592 - (void) setObject:(id)object forKey:(id)key;
1593 - (void) removeObjectForKey:(id)key;
1597 /* Bridge: CYJSArray {{{ */
1598 @interface CYJSArray : NSMutableArray {
1599 JSObjectRef object_;
1600 JSContextRef context_;
1603 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1605 - (NSUInteger) count;
1606 - (id) objectAtIndex:(NSUInteger)index;
1608 - (void) addObject:(id)anObject;
1609 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1610 - (void) removeLastObject;
1611 - (void) removeObjectAtIndex:(NSUInteger)index;
1612 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1619 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1620 JSValueRef exception(NULL);
1621 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1622 CYThrow(context, exception);
1623 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1624 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1627 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1628 if (!JSValueIsObjectOfClass(context, object, Instance_))
1629 return CYCastNSObject_(pool, context, object);
1631 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1632 return internal->GetValue();
1637 double CYCastDouble(const char *value, size_t size) {
1639 double number(strtod(value, &end));
1640 if (end != value + size)
1645 double CYCastDouble(const char *value) {
1646 return CYCastDouble(value, strlen(value));
1649 double CYCastDouble(JSContextRef context, JSValueRef value) {
1650 JSValueRef exception(NULL);
1651 double number(JSValueToNumber(context, value, &exception));
1652 CYThrow(context, exception);
1657 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
1658 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
1662 bool CYCastBool(JSContextRef context, JSValueRef value) {
1663 return JSValueToBoolean(context, value);
1667 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1671 switch (JSType type = JSValueGetType(context, value)) {
1672 case kJSTypeUndefined:
1673 object = [WebUndefined undefined];
1681 case kJSTypeBoolean:
1683 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
1686 object = [[NSNumber alloc] initWithBool:CYCastBool(context, value)];
1692 object = CYCopyNSNumber(context, value);
1697 object = CYCopyNSString(context, value);
1702 // XXX: this might could be more efficient
1703 object = CYCastNSObject(pool, context, (JSObjectRef) value);
1708 _throw(NSInternalInconsistencyException, "JSValueGetType() == 0x%x", type);
1715 return CYPoolRelease(pool, object);
1717 return [object retain];
1720 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1721 return CYNSObject(pool, context, value, true);
1723 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1724 return CYNSObject(pool, context, value, false);
1727 static bool CYIsClass(id self) {
1728 // XXX: this is a lame object_isClass
1729 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1732 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1733 id self(CYCastNSObject(pool, context, value));
1734 if (CYIsClass(self))
1735 return (Class) self;
1736 _throw(NSInvalidArgumentException, "got something that is not a Class");
1740 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1742 size_t size(JSPropertyNameArrayGetCount(names));
1743 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1744 for (size_t index(0); index != size; ++index)
1745 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1750 void CYThrow(JSContextRef context, JSValueRef value) {
1754 @throw CYCastNSObject(NULL, context, value);
1761 JSValueRef CYJSNull(JSContextRef context) {
1762 return JSValueMakeNull(context);
1765 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1766 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1769 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1770 return CYCastJSValue(context, CYJSString(value));
1774 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1776 return CYJSNull(context);
1777 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1778 return [value cy$JSValueInContext:context];
1780 return CYMakeInstance(context, value, false);
1784 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1785 JSValueRef exception(NULL);
1786 JSObjectRef object(JSValueToObject(context, value, &exception));
1787 CYThrow(context, exception);
1791 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1792 if (exception == NULL)
1794 *exception = CYCastJSValue(context, error);
1797 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1798 JSValueRef exception(NULL);
1799 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1800 CYThrow(context, exception);
1804 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1805 // XXX: this isn't actually correct
1806 return value != NULL && JSValueIsObject(context, value);
1810 @implementation CYJSObject
1812 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1813 if ((self = [super init]) != nil) {
1816 JSValueProtect(context_, object_);
1821 JSValueUnprotect(context_, object_);
1825 - (NSObject *) cy$toJSON:(NSString *)key {
1826 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1827 if (!CYIsCallable(context_, toJSON))
1828 return [super cy$toJSON:key];
1830 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1831 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1832 // XXX: do I really want an NSNull here?!
1833 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1837 - (NSString *) cy$toCYON {
1838 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1839 if (!CYIsCallable(context_, toCYON)) super:
1840 return [super cy$toCYON];
1841 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1842 return CYCastNSString(NULL, CYJSString(context_, value));
1846 - (NSUInteger) count {
1847 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1848 size_t size(JSPropertyNameArrayGetCount(names));
1849 JSPropertyNameArrayRelease(names);
1853 - (id) objectForKey:(id)key {
1854 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1855 if (JSValueIsUndefined(context_, value))
1857 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1860 - (NSEnumerator *) keyEnumerator {
1861 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1862 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1863 JSPropertyNameArrayRelease(names);
1867 - (void) setObject:(id)object forKey:(id)key {
1868 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1871 - (void) removeObjectForKey:(id)key {
1872 JSValueRef exception(NULL);
1873 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1874 CYThrow(context_, exception);
1879 @implementation CYJSArray
1881 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1882 if ((self = [super init]) != nil) {
1885 JSValueProtect(context_, object_);
1890 JSValueUnprotect(context_, object_);
1894 - (NSUInteger) count {
1895 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1898 - (id) objectAtIndex:(NSUInteger)index {
1899 size_t bounds([self count]);
1900 if (index >= bounds)
1901 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1902 JSValueRef exception(NULL);
1903 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1904 CYThrow(context_, exception);
1905 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1908 - (void) addObject:(id)object {
1909 JSValueRef exception(NULL);
1910 JSValueRef arguments[1];
1911 arguments[0] = CYCastJSValue(context_, object);
1912 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1913 CYThrow(context_, exception);
1916 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1917 size_t bounds([self count] + 1);
1918 if (index >= bounds)
1919 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1920 JSValueRef exception(NULL);
1921 JSValueRef arguments[3];
1922 arguments[0] = CYCastJSValue(context_, index);
1923 arguments[1] = CYCastJSValue(context_, 0);
1924 arguments[2] = CYCastJSValue(context_, object);
1925 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1926 CYThrow(context_, exception);
1929 - (void) removeLastObject {
1930 JSValueRef exception(NULL);
1931 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1932 CYThrow(context_, exception);
1935 - (void) removeObjectAtIndex:(NSUInteger)index {
1936 size_t bounds([self count]);
1937 if (index >= bounds)
1938 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1939 JSValueRef exception(NULL);
1940 JSValueRef arguments[2];
1941 arguments[0] = CYCastJSValue(context_, index);
1942 arguments[1] = CYCastJSValue(context_, 1);
1943 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1944 CYThrow(context_, exception);
1947 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1948 size_t bounds([self count]);
1949 if (index >= bounds)
1950 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1951 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1957 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1958 if (JSValueIsNull(context, value))
1959 return [@"null" retain];
1963 return [CYCastNSCYON(CYCastNSObject(NULL, context, value)) retain];
1968 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1969 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1970 const char *string(CYPoolCString(pool, json));
1977 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1981 JSObjectRef object_;
1989 // XXX: delete object_? ;(
1992 static CYInternal *Get(id self) {
1993 CYInternal *internal(NULL);
1994 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1995 // XXX: do something epic? ;P
2001 static CYInternal *Set(id self) {
2002 CYInternal *internal(NULL);
2003 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
2004 if (internal == NULL) {
2005 internal = new CYInternal();
2006 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
2009 // XXX: do something epic? ;P
2015 bool HasProperty(JSContextRef context, JSStringRef name) {
2016 if (object_ == NULL)
2018 return JSObjectHasProperty(context, object_, name);
2021 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
2022 if (object_ == NULL)
2024 return CYGetProperty(context, object_, name);
2027 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
2028 if (object_ == NULL)
2029 object_ = JSObjectMake(context, NULL, NULL);
2030 CYSetProperty(context, object_, name, value);
2036 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
2037 Selector_privateData *internal(new Selector_privateData(sel));
2038 return JSObjectMake(context, Selector_, internal);
2042 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
2043 Pointer *internal(new Pointer(pointer, context, owner, type));
2044 return JSObjectMake(context, Pointer_, internal);
2047 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
2048 Functor_privateData *internal(new Functor_privateData(type, function));
2049 return JSObjectMake(context, Functor_, internal);
2052 static CYUTF16String CYCastUTF16String(JSStringRef value) {
2053 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
2056 // XXX: sometimes pool is null
2057 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value) {
2058 CYUTF16String utf16(CYCastUTF16String(value));
2059 const char *in(reinterpret_cast<const char *>(utf16.data));
2061 iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL")));
2063 size_t size(JSStringGetMaximumUTF8CStringSize(value));
2064 char *out(new(pool) char[size]);
2065 CYUTF8String utf8(out, size);
2067 size = utf16.size * 2;
2068 _syscall(iconv(conversion, const_cast<char **>(&in), &size, &out, &utf8.size));
2071 utf8.size = out - utf8.data;
2073 _syscall(iconv_close(conversion));
2078 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
2079 CYUTF8String utf8(CYPoolUTF8String(pool, value));
2080 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
2084 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
2085 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
2088 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
2089 return CYGetOffset(CYPoolCString(pool, value), index);
2092 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
2093 switch (JSValueGetType(context, value)) {
2096 /*case kJSTypeString:
2097 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
2099 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
2100 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
2101 return internal->value_;
2104 double number(CYCastDouble(context, value));
2105 if (std::isnan(number))
2106 _throw(NSInvalidArgumentException, "cannot convert value to pointer");
2107 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
2111 template <typename Type_>
2112 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
2113 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
2117 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
2118 if (JSValueIsObjectOfClass(context, value, Selector_)) {
2119 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2120 return reinterpret_cast<SEL>(internal->value_);
2122 return CYCastPointer<SEL>(context, value);
2126 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
2127 switch (type->primitive) {
2128 case sig::boolean_P:
2129 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
2132 #define CYPoolFFI_(primitive, native) \
2133 case sig::primitive ## _P: \
2134 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
2137 CYPoolFFI_(uchar, unsigned char)
2138 CYPoolFFI_(char, char)
2139 CYPoolFFI_(ushort, unsigned short)
2140 CYPoolFFI_(short, short)
2141 CYPoolFFI_(ulong, unsigned long)
2142 CYPoolFFI_(long, long)
2143 CYPoolFFI_(uint, unsigned int)
2144 CYPoolFFI_(int, int)
2145 CYPoolFFI_(ulonglong, unsigned long long)
2146 CYPoolFFI_(longlong, long long)
2147 CYPoolFFI_(float, float)
2148 CYPoolFFI_(double, double)
2152 case sig::typename_P:
2153 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
2156 case sig::selector_P:
2157 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
2161 case sig::pointer_P:
2162 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
2166 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
2169 case sig::struct_P: {
2170 uint8_t *base(reinterpret_cast<uint8_t *>(data));
2171 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
2172 for (size_t index(0); index != type->data.signature.count; ++index) {
2173 sig::Element *element(&type->data.signature.elements[index]);
2174 ffi_type *field(ffi->elements[index]);
2177 if (aggregate == NULL)
2180 rhs = CYGetProperty(context, aggregate, index);
2181 if (JSValueIsUndefined(context, rhs)) {
2182 if (element->name != NULL)
2183 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
2186 if (JSValueIsUndefined(context, rhs)) undefined:
2187 _throw(NSInvalidArgumentException, "unable to extract structure value");
2191 CYPoolFFI(pool, context, element->type, field, base, rhs);
2193 base += field->size;
2201 fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
2206 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
2209 switch (type->primitive) {
2210 case sig::boolean_P:
2211 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
2214 #define CYFromFFI_(primitive, native) \
2215 case sig::primitive ## _P: \
2216 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
2219 CYFromFFI_(uchar, unsigned char)
2220 CYFromFFI_(char, char)
2221 CYFromFFI_(ushort, unsigned short)
2222 CYFromFFI_(short, short)
2223 CYFromFFI_(ulong, unsigned long)
2224 CYFromFFI_(long, long)
2225 CYFromFFI_(uint, unsigned int)
2226 CYFromFFI_(int, int)
2227 CYFromFFI_(ulonglong, unsigned long long)
2228 CYFromFFI_(longlong, long long)
2229 CYFromFFI_(float, float)
2230 CYFromFFI_(double, double)
2233 case sig::object_P: {
2234 if (id object = *reinterpret_cast<id *>(data)) {
2235 value = CYCastJSValue(context, object);
2241 case sig::typename_P:
2242 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
2245 case sig::selector_P:
2246 if (SEL sel = *reinterpret_cast<SEL *>(data))
2247 value = CYMakeSelector(context, sel);
2252 case sig::pointer_P:
2253 if (void *pointer = *reinterpret_cast<void **>(data))
2254 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
2259 if (char *utf8 = *reinterpret_cast<char **>(data))
2260 value = CYCastJSValue(context, utf8);
2265 value = CYMakeStruct(context, data, type, ffi, owner);
2269 value = CYJSUndefined(context);
2273 value = CYJSNull(context);
2277 fprintf(stderr, "CYFromFFI(%c)\n", type->primitive);
2284 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
2285 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
2289 method_getReturnType(method, type, sizeof(type));
2294 // XXX: possibly use a more "awesome" check?
2298 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, objc_method *method) {
2300 return method_getTypeEncoding(method);
2301 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel)])
2302 return CYPoolCString(pool, type);
2307 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2308 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2310 JSContextRef context(internal->context_);
2312 size_t count(internal->cif_.nargs);
2313 JSValueRef values[count];
2315 for (size_t index(0); index != count; ++index)
2316 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2318 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2319 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2322 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2323 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2325 JSContextRef context(internal->context_);
2327 size_t count(internal->cif_.nargs);
2328 JSValueRef values[count];
2330 for (size_t index(0); index != count; ++index)
2331 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2333 JSObjectRef _this(CYCastJSObject(context, values[0]));
2335 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2336 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2339 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2340 // XXX: in case of exceptions this will leak
2341 // XXX: in point of fact, this may /need/ to leak :(
2342 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2344 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2345 NULL, sizeof(ffi_closure),
2346 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2350 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2351 _assert(status == FFI_OK);
2353 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2355 internal->value_ = closure;
2360 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2361 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2362 return JSObjectMake(context, Functor_, internal);
2365 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2366 JSValueRef exception(NULL);
2367 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2368 CYThrow(context, exception);
2371 JSObjectRef function(CYCastJSObject(context, value));
2372 return CYMakeFunctor(context, function, type);
2374 void (*function)()(CYCastPointer<void (*)()>(context, value));
2375 return CYMakeFunctor(context, function, type);
2380 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2381 Message_privateData *internal(new Message_privateData(sel, type, imp));
2382 return JSObjectMake(context, Message_, internal);
2385 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2386 JSObjectRef function(CYCastJSObject(context, value));
2387 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2388 return reinterpret_cast<IMP>(internal->GetValue());
2391 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2392 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2393 Class _class(internal->GetValue());
2396 const char *name(CYPoolCString(pool, property));
2398 if (SEL sel = sel_getUid(name))
2399 if (class_getInstanceMethod(_class, sel) != NULL)
2405 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2406 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2407 Class _class(internal->GetValue());
2410 const char *name(CYPoolCString(pool, property));
2412 if (SEL sel = sel_getUid(name))
2413 if (objc_method *method = class_getInstanceMethod(_class, sel))
2414 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2419 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2420 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2421 Class _class(internal->GetValue());
2424 const char *name(CYPoolCString(pool, property));
2426 SEL sel(sel_registerName(name));
2428 objc_method *method(class_getInstanceMethod(_class, sel));
2433 if (JSValueIsObjectOfClass(context, value, Message_)) {
2434 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2435 type = sig::Unparse(pool, &message->signature_);
2436 imp = reinterpret_cast<IMP>(message->GetValue());
2438 type = CYPoolTypeEncoding(pool, _class, sel, method);
2439 imp = CYMakeMessage(context, value, type);
2443 method_setImplementation(method, imp);
2445 class_replaceMethod(_class, sel, imp, type);
2451 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2452 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2453 Class _class(internal->GetValue());
2456 const char *name(CYPoolCString(pool, property));
2458 if (SEL sel = sel_getUid(name))
2459 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
2460 objc_method_list list = {NULL, 1, {method}};
2461 class_removeMethods(_class, &list);
2469 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2470 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2471 Class _class(internal->GetValue());
2474 objc_method **data(class_copyMethodList(_class, &size));
2475 for (size_t i(0); i != size; ++i)
2476 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2480 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2481 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2482 id self(internal->GetValue());
2484 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2488 NSString *name(CYCastNSString(pool, property));
2490 if (CYInternal *internal = CYInternal::Get(self))
2491 if (internal->HasProperty(context, property))
2494 Class _class(object_getClass(self));
2497 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2498 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2499 if ([self cy$hasProperty:name])
2501 } CYPoolCatch(false)
2503 const char *string(CYPoolCString(pool, name));
2505 if (class_getProperty(_class, string) != NULL)
2508 if (SEL sel = sel_getUid(string))
2509 if (CYImplements(self, _class, sel, true))
2515 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2516 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2517 id self(internal->GetValue());
2519 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2520 return Internal::Make(context, self, object);
2524 NSString *name(CYCastNSString(pool, property));
2526 if (CYInternal *internal = CYInternal::Get(self))
2527 if (JSValueRef value = internal->GetProperty(context, property))
2531 if (NSObject *data = [self cy$getProperty:name])
2532 return CYCastJSValue(context, data);
2535 const char *string(CYPoolCString(pool, name));
2536 Class _class(object_getClass(self));
2539 if (objc_property_t property = class_getProperty(_class, string)) {
2540 PropertyAttributes attributes(property);
2541 SEL sel(sel_registerName(attributes.Getter()));
2542 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
2546 if (SEL sel = sel_getUid(string))
2547 if (CYImplements(self, _class, sel, true))
2548 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
2554 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2555 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2556 id self(internal->GetValue());
2561 NSString *name(CYCastNSString(pool, property));
2562 NSObject *data(CYCastNSObject(pool, context, value));
2565 if ([self cy$setProperty:name to:data])
2569 const char *string(CYPoolCString(pool, name));
2570 Class _class(object_getClass(self));
2573 if (objc_property_t property = class_getProperty(_class, string)) {
2574 PropertyAttributes attributes(property);
2575 if (const char *setter = attributes.Setter()) {
2576 SEL sel(sel_registerName(setter));
2577 JSValueRef arguments[1] = {value};
2578 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
2584 size_t length(strlen(string));
2586 char set[length + 5];
2592 if (string[0] != '\0') {
2593 set[3] = toupper(string[0]);
2594 memcpy(set + 4, string + 1, length - 1);
2597 set[length + 3] = ':';
2598 set[length + 4] = '\0';
2600 if (SEL sel = sel_getUid(set))
2601 if (CYImplements(self, _class, sel, false)) {
2602 JSValueRef arguments[1] = {value};
2603 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
2606 if (CYInternal *internal = CYInternal::Set(self)) {
2607 internal->SetProperty(context, property, value);
2615 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2616 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2617 id self(internal->GetValue());
2621 NSString *name(CYCastNSString(NULL, property));
2622 return [self cy$deleteProperty:name];
2627 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2628 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2629 id self(internal->GetValue());
2632 Class _class(object_getClass(self));
2636 objc_property_t *data(class_copyPropertyList(_class, &size));
2637 for (size_t i(0); i != size; ++i)
2638 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2643 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2645 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2646 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2651 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2652 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2653 Class _class(internal->GetValue());
2654 if (!CYIsClass(_class))
2657 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2658 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2659 // XXX: this isn't always safe
2661 return [linternal->GetValue() isKindOfClass:_class];
2668 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2669 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2672 id self(internal->GetValue());
2673 const char *name(CYPoolCString(pool, property));
2675 if (object_getInstanceVariable(self, name, NULL) != NULL)
2681 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2682 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2686 id self(internal->GetValue());
2687 const char *name(CYPoolCString(pool, property));
2689 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2690 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2691 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2698 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2699 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2703 id self(internal->GetValue());
2704 const char *name(CYPoolCString(pool, property));
2706 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2707 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2708 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2716 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2717 if (Class super = class_getSuperclass(_class))
2718 Internal_getPropertyNames_(super, names);
2721 Ivar *data(class_copyIvarList(_class, &size));
2722 for (size_t i(0); i != size; ++i)
2723 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2727 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2728 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2731 id self(internal->GetValue());
2732 Class _class(object_getClass(self));
2734 Internal_getPropertyNames_(_class, names);
2737 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2738 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2739 return internal->GetOwner();
2743 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2744 Type_privateData *typical(internal->type_);
2745 sig::Type *type(typical->type_);
2749 const char *name(CYPoolCString(pool, property));
2750 size_t length(strlen(name));
2751 double number(CYCastDouble(name, length));
2753 size_t count(type->data.signature.count);
2755 if (std::isnan(number)) {
2756 if (property == NULL)
2759 sig::Element *elements(type->data.signature.elements);
2761 for (size_t local(0); local != count; ++local) {
2762 sig::Element *element(&elements[local]);
2763 if (element->name != NULL && strcmp(name, element->name) == 0) {
2771 index = static_cast<ssize_t>(number);
2772 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2777 ffi_type **elements(typical->GetFFI()->elements);
2779 base = reinterpret_cast<uint8_t *>(internal->value_);
2780 for (ssize_t local(0); local != index; ++local)
2781 base += elements[local]->size;
2786 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2787 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2788 Type_privateData *typical(internal->type_);
2790 ffi_type *ffi(typical->GetFFI());
2792 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2793 base += ffi->size * index;
2795 JSObjectRef owner(internal->GetOwner() ?: object);
2798 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2802 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2804 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2805 Type_privateData *typical(internal->type_);
2807 if (typical->type_ == NULL)
2811 if (!CYGetOffset(pool, property, offset))
2814 return Pointer_getIndex(context, object, offset, exception);
2817 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2818 return Pointer_getIndex(context, object, 0, exception);
2821 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2822 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2823 Type_privateData *typical(internal->type_);
2825 ffi_type *ffi(typical->GetFFI());
2827 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2828 base += ffi->size * index;
2831 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2836 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2838 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2839 Type_privateData *typical(internal->type_);
2841 if (typical->type_ == NULL)
2845 if (!CYGetOffset(pool, property, offset))
2848 return Pointer_setIndex(context, object, offset, value, exception);
2851 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2852 return Pointer_setIndex(context, object, 0, value, exception);
2855 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2856 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2857 Type_privateData *typical(internal->type_);
2858 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2861 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2863 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2864 Type_privateData *typical(internal->type_);
2870 if (!Index_(pool, internal, property, index, base))
2873 JSObjectRef owner(internal->GetOwner() ?: object);
2875 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2879 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2881 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2882 Type_privateData *typical(internal->type_);
2888 if (!Index_(pool, internal, property, index, base))
2891 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2896 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2897 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2898 Type_privateData *typical(internal->type_);
2899 sig::Type *type(typical->type_);
2904 size_t count(type->data.signature.count);
2905 sig::Element *elements(type->data.signature.elements);
2909 for (size_t index(0); index != count; ++index) {
2911 name = elements[index].name;
2914 sprintf(number, "%lu", index);
2918 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2922 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)()) {
2924 if (setups + count != signature->count - 1)
2925 _throw(NSInvalidArgumentException, "incorrect number of arguments to ffi function");
2927 size_t size(setups + count);
2929 memcpy(values, setup, sizeof(void *) * setups);
2931 for (size_t index(setups); index != size; ++index) {
2932 sig::Element *element(&signature->elements[index + 1]);
2933 ffi_type *ffi(cif->arg_types[index]);
2935 values[index] = new(pool) uint8_t[ffi->size];
2936 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2939 uint8_t value[cif->rtype->size];
2940 ffi_call(cif, function, value, values);
2942 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2946 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2949 NSString *name(CYCastNSString(pool, property));
2950 if (Class _class = NSClassFromString(name))
2951 return CYMakeInstance(context, _class, true);
2956 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2957 size_t size(objc_getClassList(NULL, 0));
2958 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2961 size_t writ(objc_getClassList(data, size));
2964 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2970 for (size_t i(0); i != writ; ++i)
2971 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2977 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2978 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2982 const char *name(CYPoolCString(pool, property));
2984 const char **data(objc_copyClassNamesForImage(internal, &size));
2986 for (size_t i(0); i != size; ++i)
2987 if (strcmp(name, data[i]) == 0) {
2988 if (Class _class = objc_getClass(name)) {
2989 value = CYMakeInstance(context, _class, true);
3001 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3002 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
3004 const char **data(objc_copyClassNamesForImage(internal, &size));
3005 for (size_t i(0); i != size; ++i)
3006 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3010 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3013 const char *name(CYPoolCString(pool, property));
3015 const char **data(objc_copyImageNames(&size));
3016 for (size_t i(0); i != size; ++i)
3017 if (strcmp(name, data[i]) == 0) {
3026 JSObjectRef value(JSObjectMake(context, NULL, NULL));
3027 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
3032 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3034 const char **data(objc_copyImageNames(&size));
3035 for (size_t i(0); i != size; ++i)
3036 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3040 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3043 NSString *name(CYCastNSString(pool, property));
3044 if (Protocol *protocol = NSProtocolFromString(name))
3045 return CYMakeInstance(context, protocol, true);
3050 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3052 Protocol **data(objc_copyProtocolList(&size));
3053 for (size_t i(0); i != size; ++i)
3054 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
3058 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
3059 Type_privateData *internal(new Type_privateData(NULL, type));
3060 return JSObjectMake(context, Type_privateData::Class_, internal);
3063 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
3064 Type_privateData *internal(new Type_privateData(type));
3065 return JSObjectMake(context, Type_privateData::Class_, internal);
3068 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3069 if (JSStringIsEqualToUTF8CString(property, "nil"))
3070 return Instance::Make(context, nil);
3074 NSString *name(CYCastNSString(pool, property));
3075 if (Class _class = NSClassFromString(name))
3076 return CYMakeInstance(context, _class, true);
3077 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
3078 switch ([[entry objectAtIndex:0] intValue]) {
3080 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
3082 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
3084 // XXX: this is horrendously inefficient
3085 sig::Signature signature;
3086 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
3088 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3089 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
3091 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
3092 switch ([[entry objectAtIndex:0] intValue]) {
3093 // XXX: implement case 0
3095 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
3102 static bool stret(ffi_type *ffi_type) {
3103 return ffi_type->type == FFI_TYPE_STRUCT && (
3104 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
3105 struct_forward_array[ffi_type->size] != 0
3111 int *_NSGetArgc(void);
3112 char ***_NSGetArgv(void);
3115 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3120 printf("%s\n", CYCastCString(context, arguments[0]));
3121 return CYJSUndefined(context);
3125 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
3129 _class = object_getClass(self);
3131 if (objc_method *method = class_getInstanceMethod(_class, _cmd))
3132 type = method_getTypeEncoding(method);
3136 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
3138 _throw(NSInvalidArgumentException, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3139 type = CYPoolCString(pool, [method _typeString]);
3144 objc_super super = {self, _class};
3145 void *arg0 = &super;
3151 sig::Signature signature;
3152 sig::Parse(pool, &signature, type, &Structor_);
3155 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3157 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSendSuper_stret) : reinterpret_cast<void (*)()>(&objc_msgSendSuper);
3158 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3161 static size_t Nonce_(0);
3163 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3165 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
3166 return CYCastJSValue(context, name);
3169 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3180 _throw(NSInvalidArgumentException, "too few arguments to objc_msgSend");
3182 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
3183 Super *internal(reinterpret_cast<Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3184 self = internal->GetValue();
3185 _class = internal->class_;;
3186 uninitialized = false;
3187 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
3188 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3189 self = internal->GetValue();
3191 uninitialized = internal->IsUninitialized();
3193 internal->value_ = nil;
3195 self = CYCastNSObject(pool, context, arguments[0]);
3197 uninitialized = false;
3201 return CYJSNull(context);
3203 _cmd = CYCastSEL(context, arguments[1]);
3206 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
3210 /* Hook: objc_registerClassPair {{{ */
3211 // XXX: replace this with associated objects
3213 MSHook(void, CYDealloc, id self, SEL sel) {
3214 CYInternal *internal;
3215 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
3216 if (internal != NULL)
3218 _CYDealloc(self, sel);
3221 MSHook(void, objc_registerClassPair, Class _class) {
3222 Class super(class_getSuperclass(_class));
3223 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
3224 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
3225 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
3228 _objc_registerClassPair(_class);
3231 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3234 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3236 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3237 if (value == NULL || !CYIsClass(value))
3238 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3239 Class _class((Class) value);
3240 $objc_registerClassPair(_class);
3241 return CYJSUndefined(context);
3247 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3248 JSGarbageCollect(context);
3249 return CYJSUndefined(context);
3253 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3254 JSValueRef setup[count + 2];
3257 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
3258 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
3261 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3263 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
3265 // XXX: handle Instance::Uninitialized?
3266 id self(CYCastNSObject(pool, context, _this));
3270 setup[1] = &internal->sel_;
3272 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3276 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3278 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
3279 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3282 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3285 _throw(NSInvalidArgumentException, "incorrect number of arguments to Super constructor");
3287 NSObject *self(CYCastNSObject(pool, context, arguments[0]));
3288 Class _class(CYCastClass(pool, context, arguments[1]));
3289 return Super::Make(context, self, _class);
3293 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3296 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector constructor");
3297 const char *name(CYCastCString(context, arguments[0]));
3298 return CYMakeSelector(context, sel_registerName(name));
3302 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3305 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3307 void *value(CYCastPointer<void *>(context, arguments[0]));
3308 const char *type(CYCastCString(context, arguments[1]));
3312 sig::Signature signature;
3313 sig::Parse(pool, &signature, type, &Structor_);
3315 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
3319 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3322 _throw(NSInvalidArgumentException, "incorrect number of arguments to Type constructor");
3323 const char *type(CYCastCString(context, arguments[0]));
3324 return CYMakeType(context, type);
3328 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3329 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3334 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3335 type.primitive = sig::pointer_P;
3336 type.data.data.size = 0;
3338 size_t index(CYGetIndex(NULL, property));
3339 if (index == _not(size_t))
3341 type.primitive = sig::array_P;
3342 type.data.data.size = index;
3348 type.data.data.type = internal->type_;
3350 return CYMakeType(context, &type);
3354 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3355 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3359 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3360 sig::Type *type(internal->type_);
3361 ffi_type *ffi(internal->GetFFI());
3363 uint8_t value[ffi->size];
3365 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3366 return CYFromFFI(context, type, ffi, value);
3370 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3373 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3374 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3376 sig::Type *type(internal->type_);
3379 if (type->primitive != sig::array_P)
3382 size = type->data.data.size;
3383 type = type->data.data.type;
3386 void *value(malloc(internal->GetFFI()->size));
3387 return CYMakePointer(context, value, type, NULL, NULL);
3392 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3395 _throw(NSInvalidArgumentException, "incorrect number of arguments to Instance constructor");
3396 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3397 return Instance::Make(context, self);
3402 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3405 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3406 const char *type(CYCastCString(context, arguments[1]));
3407 return CYMakeFunctor(context, arguments[0], type);
3411 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3412 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3413 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3416 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3417 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3418 Type_privateData *typical(internal->GetType());
3423 if (typical == NULL) {
3427 type = typical->type_;
3428 ffi = typical->ffi_;
3431 return CYMakePointer(context, &internal->value_, type, ffi, object);
3434 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3435 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3438 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3442 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3443 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3446 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3447 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3449 sprintf(string, "%p", internal->value_);
3452 return CYCastJSValue(context, string);
3457 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3458 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3459 return Instance::Make(context, object_getClass(internal->GetValue()));
3462 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3463 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3464 id self(internal->GetValue());
3465 if (!CYIsClass(self))
3466 return CYJSUndefined(context);
3468 return CYGetClassPrototype(context, self);
3472 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3473 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3474 id self(internal->GetValue());
3475 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3476 return CYJSUndefined(context);
3477 return Messages::Make(context, self);
3480 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3481 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3484 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3488 return CYCastJSValue(context, CYJSString(CYCastNSCYON(internal->GetValue())));
3493 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3494 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3497 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3501 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3502 // XXX: check for support of cy$toJSON?
3503 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3508 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3509 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3512 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3516 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3521 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3522 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3525 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3529 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3530 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3533 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3534 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3535 const char *name(sel_getName(internal->GetValue()));
3539 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3544 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3547 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector.type");
3549 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3550 if (Class _class = CYCastClass(pool, context, arguments[0])) {
3551 SEL sel(internal->GetValue());
3552 if (objc_method *method = class_getInstanceMethod(_class, sel))
3553 if (const char *type = CYPoolTypeEncoding(pool, _class, sel, method))
3554 return CYCastJSValue(context, CYJSString(type));
3557 // XXX: do a lookup of some kind
3558 return CYJSNull(context);
3563 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3565 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3567 const char *type(sig::Unparse(pool, internal->type_));
3568 return CYCastJSValue(context, CYJSString(type));
3572 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3574 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3576 const char *type(sig::Unparse(pool, internal->type_));
3577 size_t size(strlen(type));
3578 char *cyon(new(pool) char[12 + size + 1]);
3579 memcpy(cyon, "new Type(\"", 10);
3580 cyon[12 + size] = '\0';
3581 cyon[12 + size - 2] = '"';
3582 cyon[12 + size - 1] = ')';
3583 memcpy(cyon + 10, type, size);
3584 return CYCastJSValue(context, CYJSString(cyon));
3588 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3589 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3592 static JSStaticValue CYValue_staticValues[2] = {
3593 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3594 {NULL, NULL, NULL, 0}
3597 static JSStaticValue Pointer_staticValues[2] = {
3598 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3599 {NULL, NULL, NULL, 0}
3602 static JSStaticFunction Pointer_staticFunctions[4] = {
3603 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3604 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3605 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3609 static JSStaticFunction Struct_staticFunctions[2] = {
3610 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3614 static JSStaticFunction Functor_staticFunctions[4] = {
3615 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3616 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3617 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3622 static JSStaticValue Instance_staticValues[5] = {
3623 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3624 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3625 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3626 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3627 {NULL, NULL, NULL, 0}
3630 static JSStaticFunction Instance_staticFunctions[5] = {
3631 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3632 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3633 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3634 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3638 static JSStaticFunction Internal_staticFunctions[2] = {
3639 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3643 static JSStaticFunction Selector_staticFunctions[5] = {
3644 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3645 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3646 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3647 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3652 static JSStaticFunction Type_staticFunctions[4] = {
3653 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3654 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3655 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3659 void CYSetArgs(int argc, const char *argv[]) {
3660 JSContextRef context(CYGetJSContext());
3661 JSValueRef args[argc];
3662 for (int i(0); i != argc; ++i)
3663 args[i] = CYCastJSValue(context, argv[i]);
3664 JSValueRef exception(NULL);
3665 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3666 CYThrow(context, exception);
3667 CYSetProperty(context, System_, CYJSString("args"), array);
3670 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3671 return JSContextGetGlobalObject(context);
3674 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3675 JSContextRef context(CYGetJSContext());
3676 JSValueRef exception(NULL), result;
3679 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3680 } catch (const char *error) {
3684 if (exception != NULL) { error:
3689 if (JSValueIsUndefined(context, result))
3695 json = CYPoolCCYON(pool, context, result, &exception);
3696 } catch (const char *error) {
3700 if (exception != NULL)
3703 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3707 static apr_pool_t *Pool_;
3709 apr_pool_t *CYGetGlobalPool() {
3713 MSInitialize { _pooled
3714 _aprcall(apr_initialize());
3715 _aprcall(apr_pool_create(&Pool_, NULL));
3717 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3720 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3721 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3724 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3725 NSCFType_ = objc_getClass("NSCFType");
3728 NSArray_ = objc_getClass("NSArray");
3729 NSDictionary_ = objc_getClass("NSDictonary");
3730 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3731 NSZombie_ = objc_getClass("_NSZombie_");
3732 Object_ = objc_getClass("Object");
3736 JSGlobalContextRef CYGetJSContext() {
3737 if (Context_ == NULL) {
3738 JSClassDefinition definition;
3740 definition = kJSClassDefinitionEmpty;
3741 definition.className = "Functor";
3742 definition.staticFunctions = Functor_staticFunctions;
3743 definition.callAsFunction = &Functor_callAsFunction;
3744 definition.finalize = &Finalize;
3745 Functor_ = JSClassCreate(&definition);
3747 definition = kJSClassDefinitionEmpty;
3748 definition.className = "Pointer";
3749 definition.staticValues = Pointer_staticValues;
3750 definition.staticFunctions = Pointer_staticFunctions;
3751 definition.getProperty = &Pointer_getProperty;
3752 definition.setProperty = &Pointer_setProperty;
3753 definition.finalize = &Finalize;
3754 Pointer_ = JSClassCreate(&definition);
3756 definition = kJSClassDefinitionEmpty;
3757 definition.className = "Selector";
3758 definition.staticValues = CYValue_staticValues;
3759 definition.staticFunctions = Selector_staticFunctions;
3760 definition.callAsFunction = &Selector_callAsFunction;
3761 definition.finalize = &Finalize;
3762 Selector_ = JSClassCreate(&definition);
3764 definition = kJSClassDefinitionEmpty;
3765 definition.className = "Struct";
3766 definition.staticFunctions = Struct_staticFunctions;
3767 definition.getProperty = &Struct_getProperty;
3768 definition.setProperty = &Struct_setProperty;
3769 definition.getPropertyNames = &Struct_getPropertyNames;
3770 definition.finalize = &Finalize;
3771 Struct_ = JSClassCreate(&definition);
3773 definition = kJSClassDefinitionEmpty;
3774 definition.className = "Type";
3775 definition.staticFunctions = Type_staticFunctions;
3776 definition.getProperty = &Type_getProperty;
3777 definition.callAsFunction = &Type_callAsFunction;
3778 definition.callAsConstructor = &Type_callAsConstructor;
3779 definition.finalize = &Finalize;
3780 Type_privateData::Class_ = JSClassCreate(&definition);
3782 definition = kJSClassDefinitionEmpty;
3783 definition.className = "Runtime";
3784 definition.getProperty = &Runtime_getProperty;
3785 Runtime_ = JSClassCreate(&definition);
3787 definition = kJSClassDefinitionEmpty;
3788 //definition.getProperty = &Global_getProperty;
3789 JSClassRef Global(JSClassCreate(&definition));
3791 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3793 JSObjectRef global(CYGetGlobalObject(context));
3795 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3797 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3798 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3799 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3801 length_ = JSStringCreateWithUTF8CString("length");
3802 message_ = JSStringCreateWithUTF8CString("message");
3803 name_ = JSStringCreateWithUTF8CString("name");
3804 prototype_ = JSStringCreateWithUTF8CString("prototype");
3805 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3806 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3808 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3809 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3811 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3812 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3813 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3814 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3816 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3818 /* Objective-C Classes {{{ */
3820 definition = kJSClassDefinitionEmpty;
3821 definition.className = "Instance";
3822 definition.staticValues = Instance_staticValues;
3823 definition.staticFunctions = Instance_staticFunctions;
3824 definition.hasProperty = &Instance_hasProperty;
3825 definition.getProperty = &Instance_getProperty;
3826 definition.setProperty = &Instance_setProperty;
3827 definition.deleteProperty = &Instance_deleteProperty;
3828 definition.getPropertyNames = &Instance_getPropertyNames;
3829 definition.callAsConstructor = &Instance_callAsConstructor;
3830 definition.hasInstance = &Instance_hasInstance;
3831 definition.finalize = &Finalize;
3832 Instance_ = JSClassCreate(&definition);
3834 definition = kJSClassDefinitionEmpty;
3835 definition.className = "Internal";
3836 definition.staticFunctions = Internal_staticFunctions;
3837 definition.hasProperty = &Internal_hasProperty;
3838 definition.getProperty = &Internal_getProperty;
3839 definition.setProperty = &Internal_setProperty;
3840 definition.getPropertyNames = &Internal_getPropertyNames;
3841 definition.finalize = &Finalize;
3842 Internal_ = JSClassCreate(&definition);
3844 definition = kJSClassDefinitionEmpty;
3845 definition.className = "Message";
3846 definition.staticFunctions = Functor_staticFunctions;
3847 definition.callAsFunction = &Message_callAsFunction;
3848 definition.finalize = &Finalize;
3849 Message_ = JSClassCreate(&definition);
3851 definition = kJSClassDefinitionEmpty;
3852 definition.className = "Messages";
3853 definition.hasProperty = &Messages_hasProperty;
3854 definition.getProperty = &Messages_getProperty;
3855 definition.setProperty = &Messages_setProperty;
3857 definition.deleteProperty = &Messages_deleteProperty;
3859 definition.getPropertyNames = &Messages_getPropertyNames;
3860 definition.finalize = &Finalize;
3861 Messages_ = JSClassCreate(&definition);
3862 definition = kJSClassDefinitionEmpty;
3864 definition.className = "Super";
3865 Super_ = JSClassCreate(&definition);
3867 definition.className = "ObjectiveC::Classes";
3868 definition.getProperty = &ObjectiveC_Classes_getProperty;
3869 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3870 ObjectiveC_Classes_ = JSClassCreate(&definition);
3872 definition = kJSClassDefinitionEmpty;
3873 definition.className = "ObjectiveC::Images";
3874 definition.getProperty = &ObjectiveC_Images_getProperty;
3875 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3876 ObjectiveC_Images_ = JSClassCreate(&definition);
3878 definition = kJSClassDefinitionEmpty;
3879 definition.className = "ObjectiveC::Image::Classes";
3880 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3881 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3882 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3884 definition = kJSClassDefinitionEmpty;
3885 definition.className = "ObjectiveC::Protocols";
3886 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3887 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3888 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3890 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3891 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3893 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3894 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3895 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3897 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3898 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3899 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3900 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
3902 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3903 JSValueProtect(context, Instance_prototype_);
3905 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3906 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3907 CYSetProperty(context, global, CYJSString("Super"), Super);
3909 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3910 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3914 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3915 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3916 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3917 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3919 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3920 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3921 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
3923 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3927 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3931 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
3932 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
3933 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
3935 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3937 System_ = JSObjectMake(context, NULL, NULL);
3938 CYSetProperty(context, global, CYJSString("system"), System_);
3939 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3940 //CYSetProperty(context, System_, CYJSString("global"), global);
3942 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3944 Result_ = JSStringCreateWithUTF8CString("_");
3946 JSValueProtect(context, Array_);
3947 JSValueProtect(context, Function_);
3948 JSValueProtect(context, String_);
3950 JSValueProtect(context, Object_prototype_);
3952 JSValueProtect(context, Array_prototype_);
3953 JSValueProtect(context, Array_pop_);
3954 JSValueProtect(context, Array_push_);
3955 JSValueProtect(context, Array_splice_);