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 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
143 struct CYUTF8String {
147 CYUTF8String(const char *data, size_t size) :
154 struct CYUTF16String {
155 const uint16_t *data;
158 CYUTF16String(const uint16_t *data, size_t size) :
165 /* JavaScript Properties {{{ */
166 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
167 JSValueRef exception(NULL);
168 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
169 CYThrow(context, exception);
173 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
174 JSValueRef exception(NULL);
175 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
176 CYThrow(context, exception);
180 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
181 JSValueRef exception(NULL);
182 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
183 CYThrow(context, exception);
186 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
187 JSValueRef exception(NULL);
188 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
189 CYThrow(context, exception);
192 /* JavaScript Strings {{{ */
193 JSStringRef CYCopyJSString(const char *value) {
194 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
197 JSStringRef CYCopyJSString(JSStringRef value) {
198 return value == NULL ? NULL : JSStringRetain(value);
201 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
202 if (JSValueIsNull(context, value))
204 JSValueRef exception(NULL);
205 JSStringRef string(JSValueToStringCopy(context, value, &exception));
206 CYThrow(context, exception);
216 JSStringRelease(string_);
220 CYJSString(const CYJSString &rhs) :
221 string_(CYCopyJSString(rhs.string_))
225 template <typename Arg0_>
226 CYJSString(Arg0_ arg0) :
227 string_(CYCopyJSString(arg0))
231 template <typename Arg0_, typename Arg1_>
232 CYJSString(Arg0_ arg0, Arg1_ arg1) :
233 string_(CYCopyJSString(arg0, arg1))
237 CYJSString &operator =(const CYJSString &rhs) {
239 string_ = CYCopyJSString(rhs.string_);
252 operator JSStringRef() const {
258 // XXX: this macro is unhygenic
259 #define CYCastCString_(string) ({ \
261 if (string == NULL) \
264 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
265 utf8 = reinterpret_cast<char *>(alloca(size)); \
266 JSStringGetUTF8CString(string, utf8, size); \
271 // XXX: this macro is unhygenic
272 #define CYCastCString(context, value) ({ \
276 else if (JSStringRef string = CYCopyJSString(context, value)) { \
277 utf8 = CYCastCString_(string); \
278 JSStringRelease(string); \
287 /* Objective-C Pool Release {{{ */
288 apr_status_t CYPoolRelease_(void *data) {
289 id object(reinterpret_cast<id>(data));
294 id CYPoolRelease_(apr_pool_t *pool, id object) {
297 else if (pool == NULL)
298 return [object autorelease];
300 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
305 template <typename Type_>
306 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
307 return (Type_) CYPoolRelease_(pool, (id) object);
310 /* Objective-C Strings {{{ */
311 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
313 return [value UTF8String];
315 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
316 char *string(new(pool) char[size]);
317 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
318 _throw(NSInternalInconsistencyException, "[NSString getCString:maxLength:encoding:] == NO");
323 JSStringRef CYCopyJSString_(NSString *value) {
325 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
328 return CYCopyJSString(CYPoolCString(pool, value));
332 JSStringRef CYCopyJSString(id value) {
335 // XXX: this definition scares me; is anyone using this?!
336 NSString *string([value description]);
337 return CYCopyJSString_(string);
340 NSString *CYCopyNSString(const CYUTF8String &value) {
342 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
344 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
348 NSString *CYCopyNSString(JSStringRef value) {
350 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
352 return CYCopyNSString(CYCastCString_(value));
356 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
357 return CYCopyNSString(CYJSString(context, value));
360 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
361 return CYPoolRelease(pool, CYCopyNSString(value));
364 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
365 const char *name(sel_getName(sel));
366 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
369 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
370 return CYPoolRelease(pool, CYCopyNSString(value));
373 CYUTF8String CYCastUTF8String(NSString *value) {
374 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
375 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
380 /* JavaScript Stringify {{{ */
381 void CYStringify(std::ostringstream &str, const char *data, size_t size) {
382 unsigned quot(0), apos(0);
383 for (const char *value(data), *end(data + size); value != end; ++value)
386 else if (*value == '\'')
389 bool single(quot > apos);
391 str << (single ? '\'' : '"');
393 for (const char *value(data), *end(data + size); value != end; ++value)
395 case '\\': str << "\\\\"; break;
396 case '\b': str << "\\b"; break;
397 case '\f': str << "\\f"; break;
398 case '\n': str << "\\n"; break;
399 case '\r': str << "\\r"; break;
400 case '\t': str << "\\t"; break;
401 case '\v': str << "\\v"; break;
416 if (*value < 0x20 || *value >= 0x7f)
417 str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(*value);
422 str << (single ? '\'' : '"');
426 static JSGlobalContextRef Context_;
427 static JSObjectRef System_;
429 static JSClassRef Functor_;
430 static JSClassRef Pointer_;
431 static JSClassRef Runtime_;
432 static JSClassRef Struct_;
435 static JSClassRef Instance_;
436 static JSClassRef Internal_;
437 static JSClassRef Message_;
438 static JSClassRef Messages_;
439 static JSClassRef Selector_;
440 static JSClassRef Super_;
442 static JSClassRef ObjectiveC_Classes_;
443 static JSClassRef ObjectiveC_Image_Classes_;
444 static JSClassRef ObjectiveC_Images_;
445 static JSClassRef ObjectiveC_Protocols_;
447 static JSObjectRef Instance_prototype_;
450 static JSObjectRef Array_;
451 static JSObjectRef Function_;
452 static JSObjectRef String_;
454 static JSStringRef Result_;
456 static JSStringRef length_;
457 static JSStringRef message_;
458 static JSStringRef name_;
459 static JSStringRef prototype_;
460 static JSStringRef toCYON_;
461 static JSStringRef toJSON_;
463 static JSObjectRef Object_prototype_;
465 static JSObjectRef Array_prototype_;
466 static JSObjectRef Array_pop_;
467 static JSObjectRef Array_push_;
468 static JSObjectRef Array_splice_;
472 static Class NSCFBoolean_;
473 static Class NSCFType_;
476 static Class NSArray_;
477 static Class NSDictionary_;
478 static Class NSMessageBuilder_;
479 static Class NSZombie_;
480 static Class Object_;
483 static NSArray *Bridge_;
485 static void Finalize(JSObjectRef object) {
486 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
489 class Type_privateData;
499 CYValue(const void *value) :
500 value_(const_cast<void *>(value))
504 CYValue(const CYValue &rhs) :
509 virtual Type_privateData *GetType() const {
518 JSContextRef context_;
522 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
528 JSValueProtect(context_, owner_);
533 JSValueUnprotect(context_, owner_);
536 JSObjectRef GetOwner() const {
542 struct Selector_privateData :
545 Selector_privateData(SEL value) :
550 SEL GetValue() const {
551 return reinterpret_cast<SEL>(value_);
554 virtual Type_privateData *GetType() const;
557 // XXX: trick this out with associated objects!
558 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
560 return Instance_prototype_;
562 // XXX: I need to think through multi-context
563 typedef std::map<id, JSValueRef> CacheMap;
564 static CacheMap cache_;
566 JSValueRef &value(cache_[self]);
570 JSClassRef _class(NULL);
571 JSValueRef prototype;
573 if (self == NSArray_)
574 prototype = Array_prototype_;
575 else if (self == NSDictionary_)
576 prototype = Object_prototype_;
578 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
580 JSObjectRef object(JSObjectMake(context, _class, NULL));
581 JSObjectSetPrototype(context, object, prototype);
583 JSValueProtect(context, object);
593 Transient = (1 << 0),
594 Uninitialized = (1 << 1),
599 Instance(id value, Flags flags) :
605 virtual ~Instance() {
606 if ((flags_ & Transient) == 0)
607 // XXX: does this handle background threads correctly?
608 // XXX: this simply does not work on the console because I'm stupid
609 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
612 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
613 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
614 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
618 id GetValue() const {
619 return reinterpret_cast<id>(value_);
622 bool IsUninitialized() const {
623 return (flags_ & Uninitialized) != 0;
626 virtual Type_privateData *GetType() const;
634 Super(id value, Class _class) :
635 Instance(value, Instance::Transient),
640 static JSObjectRef Make(JSContextRef context, id object, Class _class) {
641 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
649 Messages(Class value) :
654 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
655 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
656 if (_class == NSArray_)
658 if (Class super = class_getSuperclass(_class))
659 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
661 JSObjectSetPrototype(context, value, Array_prototype_);*/
665 Class GetValue() const {
666 return reinterpret_cast<Class>(value_);
673 Internal(id value, JSContextRef context, JSObjectRef owner) :
674 CYOwned(value, context, owner)
678 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
679 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
682 id GetValue() const {
683 return reinterpret_cast<id>(value_);
690 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
692 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
693 lhs.name = apr_pstrdup(pool, rhs.name);
694 if (rhs.type == NULL)
697 lhs.type = new(pool) Type;
698 Copy(pool, *lhs.type, *rhs.type);
700 lhs.offset = rhs.offset;
703 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
704 size_t count(rhs.count);
706 lhs.elements = new(pool) Element[count];
707 for (size_t index(0); index != count; ++index)
708 Copy(pool, lhs.elements[index], rhs.elements[index]);
711 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
712 lhs.primitive = rhs.primitive;
713 lhs.name = apr_pstrdup(pool, rhs.name);
714 lhs.flags = rhs.flags;
716 if (sig::IsAggregate(rhs.primitive))
717 Copy(pool, lhs.data.signature, rhs.data.signature);
719 sig::Type *&lht(lhs.data.data.type);
720 sig::Type *&rht(rhs.data.data.type);
725 lht = new(pool) Type;
726 Copy(pool, *lht, *rht);
729 lhs.data.data.size = rhs.data.data.size;
733 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
735 lhs.alignment = rhs.alignment;
737 if (rhs.elements == NULL)
741 while (rhs.elements[count] != NULL)
744 lhs.elements = new(pool) ffi_type *[count + 1];
745 lhs.elements[count] = NULL;
747 for (size_t index(0); index != count; ++index) {
748 // XXX: if these are libffi native then you can just take them
749 ffi_type *ffi(new(pool) ffi_type);
750 lhs.elements[index] = ffi;
751 sig::Copy(pool, *ffi, *rhs.elements[index]);
758 struct CStringMapLess :
759 std::binary_function<const char *, const char *, bool>
761 _finline bool operator ()(const char *lhs, const char *rhs) const {
762 return strcmp(lhs, rhs) < 0;
766 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
771 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
772 switch ([[entry objectAtIndex:0] intValue]) {
774 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
778 sig::Signature signature;
779 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
780 type = signature.elements[0].type;
786 struct Type_privateData :
790 static Type_privateData *Object;
791 static Type_privateData *Selector;
794 static JSClassRef Class_;
799 void Set(sig::Type *type) {
800 type_ = new(pool_) sig::Type;
801 sig::Copy(pool_, *type_, *type);
804 Type_privateData(apr_pool_t *pool, const char *type) :
810 sig::Signature signature;
811 sig::Parse(pool_, &signature, type, &Structor_);
812 type_ = signature.elements[0].type;
815 Type_privateData(sig::Type *type) :
822 Type_privateData(sig::Type *type, ffi_type *ffi) {
823 ffi_ = new(pool_) ffi_type;
824 sig::Copy(pool_, *ffi_, *ffi);
830 ffi_ = new(pool_) ffi_type;
832 sig::Element element;
834 element.type = type_;
837 sig::Signature signature;
838 signature.elements = &element;
842 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
850 JSClassRef Type_privateData::Class_;
853 Type_privateData *Type_privateData::Object;
854 Type_privateData *Type_privateData::Selector;
856 Type_privateData *Instance::GetType() const {
857 return Type_privateData::Object;
860 Type_privateData *Selector_privateData::GetType() const {
861 return Type_privateData::Selector;
868 Type_privateData *type_;
870 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
871 CYOwned(value, context, owner),
872 type_(new(pool_) Type_privateData(type))
877 struct Struct_privateData :
880 Type_privateData *type_;
882 Struct_privateData(JSContextRef context, JSObjectRef owner) :
883 CYOwned(NULL, context, owner)
888 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
889 static TypeMap Types_;
891 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
892 Struct_privateData *internal(new Struct_privateData(context, owner));
893 apr_pool_t *pool(internal->pool_);
894 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
895 internal->type_ = typical;
898 internal->value_ = data;
900 size_t size(typical->GetFFI()->size);
901 void *copy(apr_palloc(internal->pool_, size));
902 memcpy(copy, data, size);
903 internal->value_ = copy;
906 return JSObjectMake(context, Struct_, internal);
909 struct Functor_privateData :
912 sig::Signature signature_;
915 Functor_privateData(const char *type, void (*value)()) :
916 CYValue(reinterpret_cast<void *>(value))
918 sig::Parse(pool_, &signature_, type, &Structor_);
919 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
922 void (*GetValue())() const {
923 return reinterpret_cast<void (*)()>(value_);
927 struct Closure_privateData :
930 JSContextRef context_;
931 JSObjectRef function_;
933 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
934 Functor_privateData(type, NULL),
938 JSValueProtect(context_, function_);
941 virtual ~Closure_privateData() {
942 JSValueUnprotect(context_, function_);
947 struct Message_privateData :
952 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
953 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
959 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
960 Instance::Flags flags;
963 flags = Instance::Transient;
965 flags = Instance::None;
966 object = [object retain];
969 return Instance::Make(context, object, flags);
973 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
974 return JSValueMakeBoolean(context, value);
977 JSValueRef CYCastJSValue(JSContextRef context, double value) {
978 return JSValueMakeNumber(context, value);
981 #define CYCastJSValue_(Type_) \
982 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
983 return JSValueMakeNumber(context, static_cast<double>(value)); \
987 CYCastJSValue_(unsigned int)
988 CYCastJSValue_(long int)
989 CYCastJSValue_(long unsigned int)
990 CYCastJSValue_(long long int)
991 CYCastJSValue_(long long unsigned int)
993 JSValueRef CYJSUndefined(JSContextRef context) {
994 return JSValueMakeUndefined(context);
997 size_t CYGetIndex(const CYUTF8String &value) {
998 if (value.data[0] != '0') {
1000 size_t index(strtoul(value.data, &end, 10));
1001 if (value.data + value.size == end)
1003 } else if (value.data[1] == '\0')
1005 return _not(size_t);
1009 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value);
1011 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
1012 return CYGetIndex(CYPoolUTF8String(pool, value));
1015 bool CYGetOffset(const char *value, ssize_t &index) {
1016 if (value[0] != '0') {
1018 index = strtol(value, &end, 10);
1019 if (value + strlen(value) == end)
1021 } else if (value[1] == '\0') {
1030 size_t CYGetIndex(NSString *value) {
1031 return CYGetIndex(CYCastUTF8String(value));
1034 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
1035 return CYGetOffset(CYPoolCString(pool, value), index);
1040 @interface NSMethodSignature (Cycript)
1041 - (NSString *) _typeString;
1044 @interface NSObject (Cycript)
1046 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1047 - (JSType) cy$JSType;
1049 - (NSObject *) cy$toJSON:(NSString *)key;
1050 - (NSString *) cy$toCYON;
1051 - (NSString *) cy$toKey;
1053 - (bool) cy$hasProperty:(NSString *)name;
1054 - (NSObject *) cy$getProperty:(NSString *)name;
1055 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
1056 - (bool) cy$deleteProperty:(NSString *)name;
1061 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1064 @interface NSString (Cycript)
1065 - (void *) cy$symbol;
1070 NSString *CYCastNSCYON(id value) {
1076 Class _class(object_getClass(value));
1077 SEL sel(@selector(cy$toCYON));
1079 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
1080 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1081 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1082 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1083 string = [value cy$toCYON];
1086 if (value == NSZombie_)
1087 string = @"_NSZombie_";
1088 else if (_class == NSZombie_)
1089 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1090 // XXX: frowny /in/ the pants
1091 else if (value == NSMessageBuilder_ || value == Object_)
1094 string = [NSString stringWithFormat:@"%@", value];
1097 // XXX: frowny pants
1099 string = @"undefined";
1108 struct PropertyAttributes {
1113 const char *variable;
1115 const char *getter_;
1116 const char *setter_;
1126 PropertyAttributes(objc_property_t property) :
1138 name = property_getName(property);
1139 const char *attributes(property_getAttributes(property));
1141 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
1143 case 'R': readonly = true; break;
1144 case 'C': copy = true; break;
1145 case '&': retain = true; break;
1146 case 'N': nonatomic = true; break;
1147 case 'G': getter_ = token + 1; break;
1148 case 'S': setter_ = token + 1; break;
1149 case 'V': variable = token + 1; break;
1153 /*if (variable == NULL) {
1154 variable = property_getName(property);
1155 size_t size(strlen(variable));
1156 char *name(new(pool_) char[size + 2]);
1158 memcpy(name + 1, variable, size);
1159 name[size + 1] = '\0';
1164 const char *Getter() {
1165 if (getter_ == NULL)
1166 getter_ = apr_pstrdup(pool_, name);
1170 const char *Setter() {
1171 if (setter_ == NULL && !readonly) {
1172 size_t length(strlen(name));
1174 char *temp(new(pool_) char[length + 5]);
1180 temp[3] = toupper(name[0]);
1181 memcpy(temp + 4, name + 1, length - 1);
1184 temp[length + 3] = ':';
1185 temp[length + 4] = '\0';
1198 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
1199 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
1206 @interface CYWebUndefined : NSObject {
1209 + (CYWebUndefined *) undefined;
1213 @implementation CYWebUndefined
1215 + (CYWebUndefined *) undefined {
1216 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
1222 #define WebUndefined CYWebUndefined
1227 /* Bridge: NSArray {{{ */
1228 @implementation NSArray (Cycript)
1230 - (NSString *) cy$toCYON {
1231 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1232 [json appendString:@"["];
1236 for (id object in self) {
1239 for (size_t index(0), count([self count]); index != count; ++index) {
1240 object = [self objectAtIndex:index];
1243 [json appendString:@","];
1246 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
1247 [json appendString:CYCastNSCYON(object)];
1249 [json appendString:@","];
1254 [json appendString:@"]"];
1258 - (bool) cy$hasProperty:(NSString *)name {
1259 if ([name isEqualToString:@"length"])
1262 size_t index(CYGetIndex(name));
1263 if (index == _not(size_t) || index >= [self count])
1264 return [super cy$hasProperty:name];
1269 - (NSObject *) cy$getProperty:(NSString *)name {
1270 if ([name isEqualToString:@"length"]) {
1271 NSUInteger count([self count]);
1273 return [NSNumber numberWithUnsignedInteger:count];
1275 return [NSNumber numberWithUnsignedInt:count];
1279 size_t index(CYGetIndex(name));
1280 if (index == _not(size_t) || index >= [self count])
1281 return [super cy$getProperty:name];
1283 return [self objectAtIndex:index];
1288 /* Bridge: NSDictionary {{{ */
1289 @implementation NSDictionary (Cycript)
1291 - (NSString *) cy$toCYON {
1292 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1293 [json appendString:@"{"];
1297 for (id key in self) {
1299 NSEnumerator *keys([self keyEnumerator]);
1300 while (id key = [keys nextObject]) {
1303 [json appendString:@","];
1306 [json appendString:[key cy$toKey]];
1307 [json appendString:@":"];
1308 NSObject *object([self objectForKey:key]);
1309 [json appendString:CYCastNSCYON(object)];
1312 [json appendString:@"}"];
1316 - (bool) cy$hasProperty:(NSString *)name {
1317 return [self objectForKey:name] != nil;
1320 - (NSObject *) cy$getProperty:(NSString *)name {
1321 return [self objectForKey:name];
1326 /* Bridge: NSMutableArray {{{ */
1327 @implementation NSMutableArray (Cycript)
1329 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1330 if ([name isEqualToString:@"length"]) {
1331 // XXX: is this not intelligent?
1332 NSNumber *number(reinterpret_cast<NSNumber *>(value));
1334 NSUInteger size([number unsignedIntegerValue]);
1336 NSUInteger size([number unsignedIntValue]);
1338 NSUInteger count([self count]);
1340 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1341 else if (size != count) {
1342 WebUndefined *undefined([WebUndefined undefined]);
1343 for (size_t i(count); i != size; ++i)
1344 [self addObject:undefined];
1349 size_t index(CYGetIndex(name));
1350 if (index == _not(size_t))
1351 return [super cy$setProperty:name to:value];
1353 id object(value ?: [NSNull null]);
1355 size_t count([self count]);
1357 [self replaceObjectAtIndex:index withObject:object];
1359 if (index != count) {
1360 WebUndefined *undefined([WebUndefined undefined]);
1361 for (size_t i(count); i != index; ++i)
1362 [self addObject:undefined];
1365 [self addObject:object];
1371 - (bool) cy$deleteProperty:(NSString *)name {
1372 size_t index(CYGetIndex(name));
1373 if (index == _not(size_t) || index >= [self count])
1374 return [super cy$deleteProperty:name];
1375 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1381 /* Bridge: NSMutableDictionary {{{ */
1382 @implementation NSMutableDictionary (Cycript)
1384 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1385 [self setObject:(value ?: [NSNull null]) forKey:name];
1389 - (bool) cy$deleteProperty:(NSString *)name {
1390 if ([self objectForKey:name] == nil)
1393 [self removeObjectForKey:name];
1400 /* Bridge: NSNumber {{{ */
1401 @implementation NSNumber (Cycript)
1403 - (JSType) cy$JSType {
1405 // XXX: this just seems stupid
1406 if ([self class] == NSCFBoolean_)
1407 return kJSTypeBoolean;
1409 return kJSTypeNumber;
1412 - (NSObject *) cy$toJSON:(NSString *)key {
1416 - (NSString *) cy$toCYON {
1417 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1420 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1421 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1426 /* Bridge: NSNull {{{ */
1427 @implementation NSNull (Cycript)
1429 - (JSType) cy$JSType {
1433 - (NSObject *) cy$toJSON:(NSString *)key {
1437 - (NSString *) cy$toCYON {
1443 /* Bridge: NSObject {{{ */
1444 @implementation NSObject (Cycript)
1446 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1447 return CYMakeInstance(context, self, false);
1450 - (JSType) cy$JSType {
1451 return kJSTypeObject;
1454 - (NSObject *) cy$toJSON:(NSString *)key {
1455 return [self description];
1458 - (NSString *) cy$toCYON {
1459 return [[self cy$toJSON:@""] cy$toCYON];
1462 - (NSString *) cy$toKey {
1463 return [self cy$toCYON];
1466 - (bool) cy$hasProperty:(NSString *)name {
1470 - (NSObject *) cy$getProperty:(NSString *)name {
1474 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1478 - (bool) cy$deleteProperty:(NSString *)name {
1484 /* Bridge: NSProxy {{{ */
1485 @implementation NSProxy (Cycript)
1487 - (NSObject *) cy$toJSON:(NSString *)key {
1488 return [self description];
1491 - (NSString *) cy$toCYON {
1492 return [[self cy$toJSON:@""] cy$toCYON];
1497 /* Bridge: NSString {{{ */
1498 @implementation NSString (Cycript)
1500 - (JSType) cy$JSType {
1501 return kJSTypeString;
1504 - (NSObject *) cy$toJSON:(NSString *)key {
1508 - (NSString *) cy$toCYON {
1509 std::ostringstream str;
1510 CYUTF8String string(CYCastUTF8String(self));
1511 CYStringify(str, string.data, string.size);
1512 std::string value(str.str());
1513 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1516 - (NSString *) cy$toKey {
1517 const char *value([self UTF8String]);
1518 size_t size(strlen(value));
1523 if (DigitRange_[value[0]]) {
1524 size_t index(CYGetIndex(self));
1525 if (index == _not(size_t))
1528 if (!WordStartRange_[value[0]])
1530 for (size_t i(1); i != size; ++i)
1531 if (!WordEndRange_[value[i]])
1538 return [self cy$toCYON];
1541 - (void *) cy$symbol {
1543 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1548 /* Bridge: WebUndefined {{{ */
1549 @implementation WebUndefined (Cycript)
1551 - (JSType) cy$JSType {
1552 return kJSTypeUndefined;
1555 - (NSObject *) cy$toJSON:(NSString *)key {
1559 - (NSString *) cy$toCYON {
1560 return @"undefined";
1563 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1564 return CYJSUndefined(context);
1570 /* Bridge: CYJSObject {{{ */
1571 @interface CYJSObject : NSMutableDictionary {
1572 JSObjectRef object_;
1573 JSContextRef context_;
1576 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1578 - (NSObject *) cy$toJSON:(NSString *)key;
1580 - (NSUInteger) count;
1581 - (id) objectForKey:(id)key;
1582 - (NSEnumerator *) keyEnumerator;
1583 - (void) setObject:(id)object forKey:(id)key;
1584 - (void) removeObjectForKey:(id)key;
1588 /* Bridge: CYJSArray {{{ */
1589 @interface CYJSArray : NSMutableArray {
1590 JSObjectRef object_;
1591 JSContextRef context_;
1594 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1596 - (NSUInteger) count;
1597 - (id) objectAtIndex:(NSUInteger)index;
1599 - (void) addObject:(id)anObject;
1600 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1601 - (void) removeLastObject;
1602 - (void) removeObjectAtIndex:(NSUInteger)index;
1603 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1610 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1611 JSValueRef exception(NULL);
1612 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1613 CYThrow(context, exception);
1614 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1615 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1618 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1619 if (!JSValueIsObjectOfClass(context, object, Instance_))
1620 return CYCastNSObject_(pool, context, object);
1622 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1623 return internal->GetValue();
1628 double CYCastDouble(const char *value, size_t size) {
1630 double number(strtod(value, &end));
1631 if (end != value + size)
1636 double CYCastDouble(const char *value) {
1637 return CYCastDouble(value, strlen(value));
1640 double CYCastDouble(JSContextRef context, JSValueRef value) {
1641 JSValueRef exception(NULL);
1642 double number(JSValueToNumber(context, value, &exception));
1643 CYThrow(context, exception);
1648 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
1649 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
1653 bool CYCastBool(JSContextRef context, JSValueRef value) {
1654 return JSValueToBoolean(context, value);
1658 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1662 switch (JSType type = JSValueGetType(context, value)) {
1663 case kJSTypeUndefined:
1664 object = [WebUndefined undefined];
1672 case kJSTypeBoolean:
1674 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
1677 object = [[NSNumber alloc] initWithBool:CYCastBool(context, value)];
1683 object = CYCopyNSNumber(context, value);
1688 object = CYCopyNSString(context, value);
1693 // XXX: this might could be more efficient
1694 object = CYCastNSObject(pool, context, (JSObjectRef) value);
1699 _throw(NSInternalInconsistencyException, "JSValueGetType() == 0x%x", type);
1706 return CYPoolRelease(pool, object);
1708 return [object retain];
1711 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1712 return CYNSObject(pool, context, value, true);
1714 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1715 return CYNSObject(pool, context, value, false);
1718 static bool CYIsClass(id self) {
1719 // XXX: this is a lame object_isClass
1720 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1723 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1724 id self(CYCastNSObject(pool, context, value));
1725 if (CYIsClass(self))
1726 return (Class) self;
1727 _throw(NSInvalidArgumentException, "got something that is not a Class");
1731 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1733 size_t size(JSPropertyNameArrayGetCount(names));
1734 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1735 for (size_t index(0); index != size; ++index)
1736 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1741 void CYThrow(JSContextRef context, JSValueRef value) {
1745 @throw CYCastNSObject(NULL, context, value);
1752 JSValueRef CYJSNull(JSContextRef context) {
1753 return JSValueMakeNull(context);
1756 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1757 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1760 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1761 return CYCastJSValue(context, CYJSString(value));
1765 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1767 return CYJSNull(context);
1768 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1769 return [value cy$JSValueInContext:context];
1771 return CYMakeInstance(context, value, false);
1775 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1776 JSValueRef exception(NULL);
1777 JSObjectRef object(JSValueToObject(context, value, &exception));
1778 CYThrow(context, exception);
1782 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1783 if (exception == NULL)
1785 *exception = CYCastJSValue(context, error);
1788 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1789 JSValueRef exception(NULL);
1790 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1791 CYThrow(context, exception);
1795 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1796 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
1800 @implementation CYJSObject
1802 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1803 if ((self = [super init]) != nil) {
1806 JSValueProtect(context_, object_);
1811 JSValueUnprotect(context_, object_);
1815 - (NSObject *) cy$toJSON:(NSString *)key {
1816 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1817 if (!CYIsCallable(context_, toJSON))
1818 return [super cy$toJSON:key];
1820 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1821 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1822 // XXX: do I really want an NSNull here?!
1823 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1827 - (NSString *) cy$toCYON {
1828 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1829 if (!CYIsCallable(context_, toCYON)) super:
1830 return [super cy$toCYON];
1831 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1832 return CYCastNSString(NULL, CYJSString(context_, value));
1836 - (NSUInteger) count {
1837 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1838 size_t size(JSPropertyNameArrayGetCount(names));
1839 JSPropertyNameArrayRelease(names);
1843 - (id) objectForKey:(id)key {
1844 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1845 if (JSValueIsUndefined(context_, value))
1847 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1850 - (NSEnumerator *) keyEnumerator {
1851 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1852 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1853 JSPropertyNameArrayRelease(names);
1857 - (void) setObject:(id)object forKey:(id)key {
1858 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1861 - (void) removeObjectForKey:(id)key {
1862 JSValueRef exception(NULL);
1863 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1864 CYThrow(context_, exception);
1869 @implementation CYJSArray
1871 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1872 if ((self = [super init]) != nil) {
1875 JSValueProtect(context_, object_);
1880 JSValueUnprotect(context_, object_);
1884 - (NSUInteger) count {
1885 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1888 - (id) objectAtIndex:(NSUInteger)index {
1889 size_t bounds([self count]);
1890 if (index >= bounds)
1891 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1892 JSValueRef exception(NULL);
1893 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1894 CYThrow(context_, exception);
1895 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1898 - (void) addObject:(id)object {
1899 JSValueRef exception(NULL);
1900 JSValueRef arguments[1];
1901 arguments[0] = CYCastJSValue(context_, object);
1902 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1903 CYThrow(context_, exception);
1906 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1907 size_t bounds([self count] + 1);
1908 if (index >= bounds)
1909 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1910 JSValueRef exception(NULL);
1911 JSValueRef arguments[3];
1912 arguments[0] = CYCastJSValue(context_, index);
1913 arguments[1] = CYCastJSValue(context_, 0);
1914 arguments[2] = CYCastJSValue(context_, object);
1915 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1916 CYThrow(context_, exception);
1919 - (void) removeLastObject {
1920 JSValueRef exception(NULL);
1921 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1922 CYThrow(context_, exception);
1925 - (void) removeObjectAtIndex:(NSUInteger)index {
1926 size_t bounds([self count]);
1927 if (index >= bounds)
1928 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1929 JSValueRef exception(NULL);
1930 JSValueRef arguments[2];
1931 arguments[0] = CYCastJSValue(context_, index);
1932 arguments[1] = CYCastJSValue(context_, 1);
1933 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1934 CYThrow(context_, exception);
1937 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1938 size_t bounds([self count]);
1939 if (index >= bounds)
1940 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1941 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1947 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1948 if (JSValueIsNull(context, value))
1949 return [@"null" retain];
1953 return [CYCastNSCYON(CYCastNSObject(NULL, context, value)) retain];
1958 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1959 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1960 const char *string(CYPoolCString(pool, json));
1967 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1971 JSObjectRef object_;
1979 // XXX: delete object_? ;(
1982 static CYInternal *Get(id self) {
1983 CYInternal *internal(NULL);
1984 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1985 // XXX: do something epic? ;P
1991 static CYInternal *Set(id self) {
1992 CYInternal *internal(NULL);
1993 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1994 if (internal == NULL) {
1995 internal = new CYInternal();
1996 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1999 // XXX: do something epic? ;P
2005 bool HasProperty(JSContextRef context, JSStringRef name) {
2006 if (object_ == NULL)
2008 return JSObjectHasProperty(context, object_, name);
2011 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
2012 if (object_ == NULL)
2014 return CYGetProperty(context, object_, name);
2017 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
2018 if (object_ == NULL)
2019 object_ = JSObjectMake(context, NULL, NULL);
2020 CYSetProperty(context, object_, name, value);
2026 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
2027 Selector_privateData *internal(new Selector_privateData(sel));
2028 return JSObjectMake(context, Selector_, internal);
2032 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
2033 Pointer *internal(new Pointer(pointer, context, owner, type));
2034 return JSObjectMake(context, Pointer_, internal);
2037 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
2038 Functor_privateData *internal(new Functor_privateData(type, function));
2039 return JSObjectMake(context, Functor_, internal);
2042 static CYUTF16String CYCastUTF16String(JSStringRef value) {
2043 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
2046 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value) {
2048 return CYCastUTF8String(CYCastNSString(NULL, value));
2050 CYUTF16String utf16(CYCastUTF16String(value));
2051 const char *in(reinterpret_cast<const char *>(utf16.data));
2053 iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL")));
2055 size_t size(JSStringGetMaximumUTF8CStringSize(value));
2056 char *out(new(pool) char[size]);
2057 CYUTF8String utf8(out, size);
2059 size = utf16.size * 2;
2060 _syscall(iconv(conversion, const_cast<char **>(&in), &size, &out, &utf8.size));
2063 utf8.size = out - utf8.data;
2065 _syscall(iconv_close(conversion));
2070 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
2071 CYUTF8String utf8(CYPoolUTF8String(pool, value));
2072 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
2076 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
2077 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
2080 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
2081 return CYGetOffset(CYPoolCString(pool, value), index);
2084 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
2085 switch (JSValueGetType(context, value)) {
2088 /*case kJSTypeString:
2089 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
2091 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
2092 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
2093 return internal->value_;
2096 double number(CYCastDouble(context, value));
2097 if (std::isnan(number))
2098 _throw(NSInvalidArgumentException, "cannot convert value to pointer");
2099 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
2103 template <typename Type_>
2104 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
2105 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
2109 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
2110 if (JSValueIsObjectOfClass(context, value, Selector_)) {
2111 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2112 return reinterpret_cast<SEL>(internal->value_);
2114 return CYCastPointer<SEL>(context, value);
2118 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
2119 switch (type->primitive) {
2120 case sig::boolean_P:
2121 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
2124 #define CYPoolFFI_(primitive, native) \
2125 case sig::primitive ## _P: \
2126 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
2129 CYPoolFFI_(uchar, unsigned char)
2130 CYPoolFFI_(char, char)
2131 CYPoolFFI_(ushort, unsigned short)
2132 CYPoolFFI_(short, short)
2133 CYPoolFFI_(ulong, unsigned long)
2134 CYPoolFFI_(long, long)
2135 CYPoolFFI_(uint, unsigned int)
2136 CYPoolFFI_(int, int)
2137 CYPoolFFI_(ulonglong, unsigned long long)
2138 CYPoolFFI_(longlong, long long)
2139 CYPoolFFI_(float, float)
2140 CYPoolFFI_(double, double)
2144 case sig::typename_P:
2145 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
2148 case sig::selector_P:
2149 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
2153 case sig::pointer_P:
2154 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
2158 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
2161 case sig::struct_P: {
2162 uint8_t *base(reinterpret_cast<uint8_t *>(data));
2163 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
2164 for (size_t index(0); index != type->data.signature.count; ++index) {
2165 sig::Element *element(&type->data.signature.elements[index]);
2166 ffi_type *field(ffi->elements[index]);
2169 if (aggregate == NULL)
2172 rhs = CYGetProperty(context, aggregate, index);
2173 if (JSValueIsUndefined(context, rhs)) {
2174 if (element->name != NULL)
2175 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
2178 if (JSValueIsUndefined(context, rhs)) undefined:
2179 _throw(NSInvalidArgumentException, "unable to extract structure value");
2183 CYPoolFFI(pool, context, element->type, field, base, rhs);
2185 base += field->size;
2193 fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
2198 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
2201 switch (type->primitive) {
2202 case sig::boolean_P:
2203 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
2206 #define CYFromFFI_(primitive, native) \
2207 case sig::primitive ## _P: \
2208 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
2211 CYFromFFI_(uchar, unsigned char)
2212 CYFromFFI_(char, char)
2213 CYFromFFI_(ushort, unsigned short)
2214 CYFromFFI_(short, short)
2215 CYFromFFI_(ulong, unsigned long)
2216 CYFromFFI_(long, long)
2217 CYFromFFI_(uint, unsigned int)
2218 CYFromFFI_(int, int)
2219 CYFromFFI_(ulonglong, unsigned long long)
2220 CYFromFFI_(longlong, long long)
2221 CYFromFFI_(float, float)
2222 CYFromFFI_(double, double)
2225 case sig::object_P: {
2226 if (id object = *reinterpret_cast<id *>(data)) {
2227 value = CYCastJSValue(context, object);
2233 case sig::typename_P:
2234 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
2237 case sig::selector_P:
2238 if (SEL sel = *reinterpret_cast<SEL *>(data))
2239 value = CYMakeSelector(context, sel);
2244 case sig::pointer_P:
2245 if (void *pointer = *reinterpret_cast<void **>(data))
2246 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
2251 if (char *utf8 = *reinterpret_cast<char **>(data))
2252 value = CYCastJSValue(context, utf8);
2257 value = CYMakeStruct(context, data, type, ffi, owner);
2261 value = CYJSUndefined(context);
2265 value = CYJSNull(context);
2269 fprintf(stderr, "CYFromFFI(%c)\n", type->primitive);
2276 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
2277 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
2281 method_getReturnType(method, type, sizeof(type));
2286 // XXX: possibly use a more "awesome" check?
2290 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, objc_method *method) {
2292 return method_getTypeEncoding(method);
2293 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel)])
2294 return CYPoolCString(pool, type);
2299 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2300 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2302 JSContextRef context(internal->context_);
2304 size_t count(internal->cif_.nargs);
2305 JSValueRef values[count];
2307 for (size_t index(0); index != count; ++index)
2308 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2310 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2311 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2314 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2315 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2317 JSContextRef context(internal->context_);
2319 size_t count(internal->cif_.nargs);
2320 JSValueRef values[count];
2322 for (size_t index(0); index != count; ++index)
2323 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2325 JSObjectRef _this(CYCastJSObject(context, values[0]));
2327 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2328 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2331 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2332 // XXX: in case of exceptions this will leak
2333 // XXX: in point of fact, this may /need/ to leak :(
2334 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2336 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2337 NULL, sizeof(ffi_closure),
2338 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2342 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2343 _assert(status == FFI_OK);
2345 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2347 internal->value_ = closure;
2352 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2353 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2354 return JSObjectMake(context, Functor_, internal);
2357 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2358 JSValueRef exception(NULL);
2359 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2360 CYThrow(context, exception);
2363 JSObjectRef function(CYCastJSObject(context, value));
2364 return CYMakeFunctor(context, function, type);
2366 void (*function)()(CYCastPointer<void (*)()>(context, value));
2367 return CYMakeFunctor(context, function, type);
2372 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2373 Message_privateData *internal(new Message_privateData(sel, type, imp));
2374 return JSObjectMake(context, Message_, internal);
2377 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2378 JSObjectRef function(CYCastJSObject(context, value));
2379 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2380 return reinterpret_cast<IMP>(internal->GetValue());
2383 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2384 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2385 Class _class(internal->GetValue());
2388 const char *name(CYPoolCString(pool, property));
2390 if (SEL sel = sel_getUid(name))
2391 if (class_getInstanceMethod(_class, sel) != NULL)
2397 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2398 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2399 Class _class(internal->GetValue());
2402 const char *name(CYPoolCString(pool, property));
2404 if (SEL sel = sel_getUid(name))
2405 if (objc_method *method = class_getInstanceMethod(_class, sel))
2406 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2411 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2412 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2413 Class _class(internal->GetValue());
2416 const char *name(CYPoolCString(pool, property));
2418 SEL sel(sel_registerName(name));
2420 objc_method *method(class_getInstanceMethod(_class, sel));
2425 if (JSValueIsObjectOfClass(context, value, Message_)) {
2426 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2427 type = sig::Unparse(pool, &message->signature_);
2428 imp = reinterpret_cast<IMP>(message->GetValue());
2430 type = CYPoolTypeEncoding(pool, _class, sel, method);
2431 imp = CYMakeMessage(context, value, type);
2435 method_setImplementation(method, imp);
2437 class_replaceMethod(_class, sel, imp, type);
2443 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2444 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2445 Class _class(internal->GetValue());
2448 const char *name(CYPoolCString(pool, property));
2450 if (SEL sel = sel_getUid(name))
2451 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
2452 objc_method_list list = {NULL, 1, {method}};
2453 class_removeMethods(_class, &list);
2461 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2462 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2463 Class _class(internal->GetValue());
2466 objc_method **data(class_copyMethodList(_class, &size));
2467 for (size_t i(0); i != size; ++i)
2468 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2472 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2473 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2474 id self(internal->GetValue());
2476 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2480 NSString *name(CYCastNSString(pool, property));
2482 if (CYInternal *internal = CYInternal::Get(self))
2483 if (internal->HasProperty(context, property))
2486 Class _class(object_getClass(self));
2489 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2490 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2491 if ([self cy$hasProperty:name])
2493 } CYPoolCatch(false)
2495 const char *string(CYPoolCString(pool, name));
2497 if (class_getProperty(_class, string) != NULL)
2500 if (SEL sel = sel_getUid(string))
2501 if (CYImplements(self, _class, sel, true))
2507 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2508 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2509 id self(internal->GetValue());
2511 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2512 return Internal::Make(context, self, object);
2516 NSString *name(CYCastNSString(pool, property));
2518 if (CYInternal *internal = CYInternal::Get(self))
2519 if (JSValueRef value = internal->GetProperty(context, property))
2523 if (NSObject *data = [self cy$getProperty:name])
2524 return CYCastJSValue(context, data);
2527 const char *string(CYPoolCString(pool, name));
2528 Class _class(object_getClass(self));
2531 if (objc_property_t property = class_getProperty(_class, string)) {
2532 PropertyAttributes attributes(property);
2533 SEL sel(sel_registerName(attributes.Getter()));
2534 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
2538 if (SEL sel = sel_getUid(string))
2539 if (CYImplements(self, _class, sel, true))
2540 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
2546 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2547 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2548 id self(internal->GetValue());
2553 NSString *name(CYCastNSString(pool, property));
2554 NSObject *data(CYCastNSObject(pool, context, value));
2557 if ([self cy$setProperty:name to:data])
2561 const char *string(CYPoolCString(pool, name));
2562 Class _class(object_getClass(self));
2565 if (objc_property_t property = class_getProperty(_class, string)) {
2566 PropertyAttributes attributes(property);
2567 if (const char *setter = attributes.Setter()) {
2568 SEL sel(sel_registerName(setter));
2569 JSValueRef arguments[1] = {value};
2570 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
2576 size_t length(strlen(string));
2578 char set[length + 5];
2584 if (string[0] != '\0') {
2585 set[3] = toupper(string[0]);
2586 memcpy(set + 4, string + 1, length - 1);
2589 set[length + 3] = ':';
2590 set[length + 4] = '\0';
2592 if (SEL sel = sel_getUid(set))
2593 if (CYImplements(self, _class, sel, false)) {
2594 JSValueRef arguments[1] = {value};
2595 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
2598 if (CYInternal *internal = CYInternal::Set(self)) {
2599 internal->SetProperty(context, property, value);
2607 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2608 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2609 id self(internal->GetValue());
2613 NSString *name(CYCastNSString(NULL, property));
2614 return [self cy$deleteProperty:name];
2619 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2620 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2621 id self(internal->GetValue());
2624 Class _class(object_getClass(self));
2628 objc_property_t *data(class_copyPropertyList(_class, &size));
2629 for (size_t i(0); i != size; ++i)
2630 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2635 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2637 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2638 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2643 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2644 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2645 Class _class(internal->GetValue());
2646 if (!CYIsClass(_class))
2649 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2650 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2651 // XXX: this isn't always safe
2653 return [linternal->GetValue() isKindOfClass:_class];
2660 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2661 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2664 id self(internal->GetValue());
2665 const char *name(CYPoolCString(pool, property));
2667 if (object_getInstanceVariable(self, name, NULL) != NULL)
2673 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2674 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2678 id self(internal->GetValue());
2679 const char *name(CYPoolCString(pool, property));
2681 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2682 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2683 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2690 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2691 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2695 id self(internal->GetValue());
2696 const char *name(CYPoolCString(pool, property));
2698 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2699 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2700 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2708 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2709 if (Class super = class_getSuperclass(_class))
2710 Internal_getPropertyNames_(super, names);
2713 Ivar *data(class_copyIvarList(_class, &size));
2714 for (size_t i(0); i != size; ++i)
2715 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2719 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2720 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2723 id self(internal->GetValue());
2724 Class _class(object_getClass(self));
2726 Internal_getPropertyNames_(_class, names);
2729 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2730 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2731 return internal->GetOwner();
2735 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2736 Type_privateData *typical(internal->type_);
2737 sig::Type *type(typical->type_);
2741 const char *name(CYPoolCString(pool, property));
2742 size_t length(strlen(name));
2743 double number(CYCastDouble(name, length));
2745 size_t count(type->data.signature.count);
2747 if (std::isnan(number)) {
2748 if (property == NULL)
2751 sig::Element *elements(type->data.signature.elements);
2753 for (size_t local(0); local != count; ++local) {
2754 sig::Element *element(&elements[local]);
2755 if (element->name != NULL && strcmp(name, element->name) == 0) {
2763 index = static_cast<ssize_t>(number);
2764 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2769 ffi_type **elements(typical->GetFFI()->elements);
2771 base = reinterpret_cast<uint8_t *>(internal->value_);
2772 for (ssize_t local(0); local != index; ++local)
2773 base += elements[local]->size;
2778 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2779 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2780 Type_privateData *typical(internal->type_);
2782 ffi_type *ffi(typical->GetFFI());
2784 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2785 base += ffi->size * index;
2787 JSObjectRef owner(internal->GetOwner() ?: object);
2790 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2794 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2796 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2797 Type_privateData *typical(internal->type_);
2799 if (typical->type_ == NULL)
2803 if (!CYGetOffset(pool, property, offset))
2806 return Pointer_getIndex(context, object, offset, exception);
2809 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2810 return Pointer_getIndex(context, object, 0, exception);
2813 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2814 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2815 Type_privateData *typical(internal->type_);
2817 ffi_type *ffi(typical->GetFFI());
2819 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2820 base += ffi->size * index;
2823 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2828 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2830 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2831 Type_privateData *typical(internal->type_);
2833 if (typical->type_ == NULL)
2837 if (!CYGetOffset(pool, property, offset))
2840 return Pointer_setIndex(context, object, offset, value, exception);
2843 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2844 return Pointer_setIndex(context, object, 0, value, exception);
2847 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2848 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2849 Type_privateData *typical(internal->type_);
2850 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2853 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2855 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2856 Type_privateData *typical(internal->type_);
2862 if (!Index_(pool, internal, property, index, base))
2865 JSObjectRef owner(internal->GetOwner() ?: object);
2867 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2871 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2873 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2874 Type_privateData *typical(internal->type_);
2880 if (!Index_(pool, internal, property, index, base))
2883 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2888 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2889 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2890 Type_privateData *typical(internal->type_);
2891 sig::Type *type(typical->type_);
2896 size_t count(type->data.signature.count);
2897 sig::Element *elements(type->data.signature.elements);
2901 for (size_t index(0); index != count; ++index) {
2903 name = elements[index].name;
2906 sprintf(number, "%lu", index);
2910 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2914 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)()) {
2916 if (setups + count != signature->count - 1)
2917 _throw(NSInvalidArgumentException, "incorrect number of arguments to ffi function");
2919 size_t size(setups + count);
2921 memcpy(values, setup, sizeof(void *) * setups);
2923 for (size_t index(setups); index != size; ++index) {
2924 sig::Element *element(&signature->elements[index + 1]);
2925 ffi_type *ffi(cif->arg_types[index]);
2927 values[index] = new(pool) uint8_t[ffi->size];
2928 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2931 uint8_t value[cif->rtype->size];
2932 ffi_call(cif, function, value, values);
2934 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2938 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2941 NSString *name(CYCastNSString(pool, property));
2942 if (Class _class = NSClassFromString(name))
2943 return CYMakeInstance(context, _class, true);
2948 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2949 size_t size(objc_getClassList(NULL, 0));
2950 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2953 size_t writ(objc_getClassList(data, size));
2956 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2962 for (size_t i(0); i != writ; ++i)
2963 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2969 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2970 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2974 const char *name(CYPoolCString(pool, property));
2976 const char **data(objc_copyClassNamesForImage(internal, &size));
2978 for (size_t i(0); i != size; ++i)
2979 if (strcmp(name, data[i]) == 0) {
2980 if (Class _class = objc_getClass(name)) {
2981 value = CYMakeInstance(context, _class, true);
2993 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2994 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2996 const char **data(objc_copyClassNamesForImage(internal, &size));
2997 for (size_t i(0); i != size; ++i)
2998 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3002 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3005 const char *name(CYPoolCString(pool, property));
3007 const char **data(objc_copyImageNames(&size));
3008 for (size_t i(0); i != size; ++i)
3009 if (strcmp(name, data[i]) == 0) {
3018 JSObjectRef value(JSObjectMake(context, NULL, NULL));
3019 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
3024 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3026 const char **data(objc_copyImageNames(&size));
3027 for (size_t i(0); i != size; ++i)
3028 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3032 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3035 NSString *name(CYCastNSString(pool, property));
3036 if (Protocol *protocol = NSProtocolFromString(name))
3037 return CYMakeInstance(context, protocol, true);
3042 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3044 Protocol **data(objc_copyProtocolList(&size));
3045 for (size_t i(0); i != size; ++i)
3046 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
3050 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
3051 Type_privateData *internal(new Type_privateData(NULL, type));
3052 return JSObjectMake(context, Type_privateData::Class_, internal);
3055 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
3056 Type_privateData *internal(new Type_privateData(type));
3057 return JSObjectMake(context, Type_privateData::Class_, internal);
3060 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3061 if (JSStringIsEqualToUTF8CString(property, "nil"))
3062 return Instance::Make(context, nil);
3066 NSString *name(CYCastNSString(pool, property));
3067 if (Class _class = NSClassFromString(name))
3068 return CYMakeInstance(context, _class, true);
3069 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
3070 switch ([[entry objectAtIndex:0] intValue]) {
3072 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
3074 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
3076 // XXX: this is horrendously inefficient
3077 sig::Signature signature;
3078 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
3080 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3081 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
3083 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
3084 switch ([[entry objectAtIndex:0] intValue]) {
3085 // XXX: implement case 0
3087 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
3094 static bool stret(ffi_type *ffi_type) {
3095 return ffi_type->type == FFI_TYPE_STRUCT && (
3096 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
3097 struct_forward_array[ffi_type->size] != 0
3103 int *_NSGetArgc(void);
3104 char ***_NSGetArgv(void);
3107 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3112 printf("%s\n", CYCastCString(context, arguments[0]));
3113 return CYJSUndefined(context);
3117 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
3121 _class = object_getClass(self);
3123 if (objc_method *method = class_getInstanceMethod(_class, _cmd))
3124 type = method_getTypeEncoding(method);
3128 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
3130 _throw(NSInvalidArgumentException, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3131 type = CYPoolCString(pool, [method _typeString]);
3136 objc_super super = {self, _class};
3137 void *arg0 = &super;
3143 sig::Signature signature;
3144 sig::Parse(pool, &signature, type, &Structor_);
3147 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3149 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSendSuper_stret) : reinterpret_cast<void (*)()>(&objc_msgSendSuper);
3150 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3153 static size_t Nonce_(0);
3155 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3157 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
3158 return CYCastJSValue(context, name);
3161 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3172 _throw(NSInvalidArgumentException, "too few arguments to objc_msgSend");
3174 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
3175 Super *internal(reinterpret_cast<Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3176 self = internal->GetValue();
3177 _class = internal->class_;;
3178 uninitialized = false;
3179 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
3180 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3181 self = internal->GetValue();
3183 uninitialized = internal->IsUninitialized();
3185 internal->value_ = nil;
3187 self = CYCastNSObject(pool, context, arguments[0]);
3189 uninitialized = false;
3193 return CYJSNull(context);
3195 _cmd = CYCastSEL(context, arguments[1]);
3198 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
3202 /* Hook: objc_registerClassPair {{{ */
3203 // XXX: replace this with associated objects
3205 MSHook(void, CYDealloc, id self, SEL sel) {
3206 CYInternal *internal;
3207 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
3208 if (internal != NULL)
3210 _CYDealloc(self, sel);
3213 MSHook(void, objc_registerClassPair, Class _class) {
3214 Class super(class_getSuperclass(_class));
3215 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
3216 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
3217 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
3220 _objc_registerClassPair(_class);
3223 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3226 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3228 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3229 if (value == NULL || !CYIsClass(value))
3230 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3231 Class _class((Class) value);
3232 $objc_registerClassPair(_class);
3233 return CYJSUndefined(context);
3239 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3240 JSGarbageCollect(context);
3241 return CYJSUndefined(context);
3245 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3246 JSValueRef setup[count + 2];
3249 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
3250 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
3253 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3255 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
3257 // XXX: handle Instance::Uninitialized?
3258 id self(CYCastNSObject(pool, context, _this));
3262 setup[1] = &internal->sel_;
3264 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3268 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3270 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
3271 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3274 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3277 _throw(NSInvalidArgumentException, "incorrect number of arguments to Super constructor");
3279 NSObject *self(CYCastNSObject(pool, context, arguments[0]));
3280 Class _class(CYCastClass(pool, context, arguments[1]));
3281 return Super::Make(context, self, _class);
3285 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3288 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector constructor");
3289 const char *name(CYCastCString(context, arguments[0]));
3290 return CYMakeSelector(context, sel_registerName(name));
3294 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3297 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3299 void *value(CYCastPointer<void *>(context, arguments[0]));
3300 const char *type(CYCastCString(context, arguments[1]));
3304 sig::Signature signature;
3305 sig::Parse(pool, &signature, type, &Structor_);
3307 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
3311 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3314 _throw(NSInvalidArgumentException, "incorrect number of arguments to Type constructor");
3315 const char *type(CYCastCString(context, arguments[0]));
3316 return CYMakeType(context, type);
3320 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3321 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3326 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3327 type.primitive = sig::pointer_P;
3328 type.data.data.size = 0;
3331 size_t index(CYGetIndex(pool, property));
3332 if (index == _not(size_t))
3334 type.primitive = sig::array_P;
3335 type.data.data.size = index;
3341 type.data.data.type = internal->type_;
3343 return CYMakeType(context, &type);
3347 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3348 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3352 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3353 sig::Type *type(internal->type_);
3354 ffi_type *ffi(internal->GetFFI());
3356 uint8_t value[ffi->size];
3358 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3359 return CYFromFFI(context, type, ffi, value);
3363 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3366 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3367 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3369 sig::Type *type(internal->type_);
3372 if (type->primitive != sig::array_P)
3375 size = type->data.data.size;
3376 type = type->data.data.type;
3379 void *value(malloc(internal->GetFFI()->size));
3380 return CYMakePointer(context, value, type, NULL, NULL);
3385 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3388 _throw(NSInvalidArgumentException, "incorrect number of arguments to Instance constructor");
3389 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3390 return Instance::Make(context, self);
3395 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3398 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3399 const char *type(CYCastCString(context, arguments[1]));
3400 return CYMakeFunctor(context, arguments[0], type);
3404 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3405 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3406 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3409 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3410 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3411 Type_privateData *typical(internal->GetType());
3416 if (typical == NULL) {
3420 type = typical->type_;
3421 ffi = typical->ffi_;
3424 return CYMakePointer(context, &internal->value_, type, ffi, object);
3427 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3428 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3431 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3435 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3436 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3439 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3440 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3442 sprintf(string, "%p", internal->value_);
3445 return CYCastJSValue(context, string);
3450 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3451 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3452 return Instance::Make(context, object_getClass(internal->GetValue()));
3455 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3456 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3457 id self(internal->GetValue());
3458 if (!CYIsClass(self))
3459 return CYJSUndefined(context);
3461 return CYGetClassPrototype(context, self);
3465 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3466 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3467 id self(internal->GetValue());
3468 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3469 return CYJSUndefined(context);
3470 return Messages::Make(context, self);
3473 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3474 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3477 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3481 return CYCastJSValue(context, CYJSString(CYCastNSCYON(internal->GetValue())));
3486 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3487 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3490 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3494 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3495 // XXX: check for support of cy$toJSON?
3496 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3501 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3502 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3505 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3509 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3514 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3515 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3518 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3522 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3523 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3526 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3527 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3528 const char *name(sel_getName(internal->GetValue()));
3532 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3537 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3540 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector.type");
3542 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3543 if (Class _class = CYCastClass(pool, context, arguments[0])) {
3544 SEL sel(internal->GetValue());
3545 if (objc_method *method = class_getInstanceMethod(_class, sel))
3546 if (const char *type = CYPoolTypeEncoding(pool, _class, sel, method))
3547 return CYCastJSValue(context, CYJSString(type));
3550 // XXX: do a lookup of some kind
3551 return CYJSNull(context);
3556 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3558 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3560 const char *type(sig::Unparse(pool, internal->type_));
3561 return CYCastJSValue(context, CYJSString(type));
3565 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3567 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3569 const char *type(sig::Unparse(pool, internal->type_));
3570 size_t size(strlen(type));
3571 char *cyon(new(pool) char[12 + size + 1]);
3572 memcpy(cyon, "new Type(\"", 10);
3573 cyon[12 + size] = '\0';
3574 cyon[12 + size - 2] = '"';
3575 cyon[12 + size - 1] = ')';
3576 memcpy(cyon + 10, type, size);
3577 return CYCastJSValue(context, CYJSString(cyon));
3581 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3582 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3585 static JSStaticValue CYValue_staticValues[2] = {
3586 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3587 {NULL, NULL, NULL, 0}
3590 static JSStaticValue Pointer_staticValues[2] = {
3591 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3592 {NULL, NULL, NULL, 0}
3595 static JSStaticFunction Pointer_staticFunctions[4] = {
3596 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3597 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3598 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3602 static JSStaticFunction Struct_staticFunctions[2] = {
3603 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3607 static JSStaticFunction Functor_staticFunctions[4] = {
3608 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3609 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3610 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3615 static JSStaticValue Instance_staticValues[5] = {
3616 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3617 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3618 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3619 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3620 {NULL, NULL, NULL, 0}
3623 static JSStaticFunction Instance_staticFunctions[5] = {
3624 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3625 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3626 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3627 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3631 static JSStaticFunction Internal_staticFunctions[2] = {
3632 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3636 static JSStaticFunction Selector_staticFunctions[5] = {
3637 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3638 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3639 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3640 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3645 static JSStaticFunction Type_staticFunctions[4] = {
3646 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3647 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3648 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3652 void CYSetArgs(int argc, const char *argv[]) {
3653 JSContextRef context(CYGetJSContext());
3654 JSValueRef args[argc];
3655 for (int i(0); i != argc; ++i)
3656 args[i] = CYCastJSValue(context, argv[i]);
3657 JSValueRef exception(NULL);
3658 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3659 CYThrow(context, exception);
3660 CYSetProperty(context, System_, CYJSString("args"), array);
3663 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3664 return JSContextGetGlobalObject(context);
3667 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3668 JSContextRef context(CYGetJSContext());
3669 JSValueRef exception(NULL), result;
3672 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3673 } catch (const char *error) {
3677 if (exception != NULL) { error:
3682 if (JSValueIsUndefined(context, result))
3688 json = CYPoolCCYON(pool, context, result, &exception);
3689 } catch (const char *error) {
3693 if (exception != NULL)
3696 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3700 static apr_pool_t *Pool_;
3702 apr_pool_t *CYGetGlobalPool() {
3706 MSInitialize { _pooled
3707 _aprcall(apr_initialize());
3708 _aprcall(apr_pool_create(&Pool_, NULL));
3710 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3713 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3714 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3717 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3718 NSCFType_ = objc_getClass("NSCFType");
3721 NSArray_ = objc_getClass("NSArray");
3722 NSDictionary_ = objc_getClass("NSDictonary");
3723 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3724 NSZombie_ = objc_getClass("_NSZombie_");
3725 Object_ = objc_getClass("Object");
3729 JSGlobalContextRef CYGetJSContext() {
3730 if (Context_ == NULL) {
3731 JSClassDefinition definition;
3733 definition = kJSClassDefinitionEmpty;
3734 definition.className = "Functor";
3735 definition.staticFunctions = Functor_staticFunctions;
3736 definition.callAsFunction = &Functor_callAsFunction;
3737 definition.finalize = &Finalize;
3738 Functor_ = JSClassCreate(&definition);
3740 definition = kJSClassDefinitionEmpty;
3741 definition.className = "Pointer";
3742 definition.staticValues = Pointer_staticValues;
3743 definition.staticFunctions = Pointer_staticFunctions;
3744 definition.getProperty = &Pointer_getProperty;
3745 definition.setProperty = &Pointer_setProperty;
3746 definition.finalize = &Finalize;
3747 Pointer_ = JSClassCreate(&definition);
3749 definition = kJSClassDefinitionEmpty;
3750 definition.className = "Selector";
3751 definition.staticValues = CYValue_staticValues;
3752 definition.staticFunctions = Selector_staticFunctions;
3753 definition.callAsFunction = &Selector_callAsFunction;
3754 definition.finalize = &Finalize;
3755 Selector_ = JSClassCreate(&definition);
3757 definition = kJSClassDefinitionEmpty;
3758 definition.className = "Struct";
3759 definition.staticFunctions = Struct_staticFunctions;
3760 definition.getProperty = &Struct_getProperty;
3761 definition.setProperty = &Struct_setProperty;
3762 definition.getPropertyNames = &Struct_getPropertyNames;
3763 definition.finalize = &Finalize;
3764 Struct_ = JSClassCreate(&definition);
3766 definition = kJSClassDefinitionEmpty;
3767 definition.className = "Type";
3768 definition.staticFunctions = Type_staticFunctions;
3769 definition.getProperty = &Type_getProperty;
3770 definition.callAsFunction = &Type_callAsFunction;
3771 definition.callAsConstructor = &Type_callAsConstructor;
3772 definition.finalize = &Finalize;
3773 Type_privateData::Class_ = JSClassCreate(&definition);
3775 definition = kJSClassDefinitionEmpty;
3776 definition.className = "Runtime";
3777 definition.getProperty = &Runtime_getProperty;
3778 Runtime_ = JSClassCreate(&definition);
3780 definition = kJSClassDefinitionEmpty;
3781 //definition.getProperty = &Global_getProperty;
3782 JSClassRef Global(JSClassCreate(&definition));
3784 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3786 JSObjectRef global(CYGetGlobalObject(context));
3788 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3790 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3791 JSValueProtect(context, Array_);
3793 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3794 JSValueProtect(context, Function_);
3796 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3797 JSValueProtect(context, String_);
3799 length_ = JSStringCreateWithUTF8CString("length");
3800 message_ = JSStringCreateWithUTF8CString("message");
3801 name_ = JSStringCreateWithUTF8CString("name");
3802 prototype_ = JSStringCreateWithUTF8CString("prototype");
3803 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3804 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3806 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3807 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3808 JSValueProtect(context, Object_prototype_);
3810 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3811 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3812 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3813 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3815 JSValueProtect(context, Array_prototype_);
3816 JSValueProtect(context, Array_pop_);
3817 JSValueProtect(context, Array_push_);
3818 JSValueProtect(context, Array_splice_);
3820 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3822 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3824 /* Objective-C Classes {{{ */
3826 definition = kJSClassDefinitionEmpty;
3827 definition.className = "Instance";
3828 definition.staticValues = Instance_staticValues;
3829 definition.staticFunctions = Instance_staticFunctions;
3830 definition.hasProperty = &Instance_hasProperty;
3831 definition.getProperty = &Instance_getProperty;
3832 definition.setProperty = &Instance_setProperty;
3833 definition.deleteProperty = &Instance_deleteProperty;
3834 definition.getPropertyNames = &Instance_getPropertyNames;
3835 definition.callAsConstructor = &Instance_callAsConstructor;
3836 definition.hasInstance = &Instance_hasInstance;
3837 definition.finalize = &Finalize;
3838 Instance_ = JSClassCreate(&definition);
3840 definition = kJSClassDefinitionEmpty;
3841 definition.className = "Internal";
3842 definition.staticFunctions = Internal_staticFunctions;
3843 definition.hasProperty = &Internal_hasProperty;
3844 definition.getProperty = &Internal_getProperty;
3845 definition.setProperty = &Internal_setProperty;
3846 definition.getPropertyNames = &Internal_getPropertyNames;
3847 definition.finalize = &Finalize;
3848 Internal_ = JSClassCreate(&definition);
3850 definition = kJSClassDefinitionEmpty;
3851 definition.className = "Message";
3852 definition.staticFunctions = Functor_staticFunctions;
3853 definition.callAsFunction = &Message_callAsFunction;
3854 definition.finalize = &Finalize;
3855 Message_ = JSClassCreate(&definition);
3857 definition = kJSClassDefinitionEmpty;
3858 definition.className = "Messages";
3859 definition.hasProperty = &Messages_hasProperty;
3860 definition.getProperty = &Messages_getProperty;
3861 definition.setProperty = &Messages_setProperty;
3863 definition.deleteProperty = &Messages_deleteProperty;
3865 definition.getPropertyNames = &Messages_getPropertyNames;
3866 definition.finalize = &Finalize;
3867 Messages_ = JSClassCreate(&definition);
3869 definition = kJSClassDefinitionEmpty;
3870 definition.className = "Super";
3871 definition.staticFunctions = Internal_staticFunctions;
3872 definition.finalize = &Finalize;
3873 Super_ = JSClassCreate(&definition);
3875 definition = kJSClassDefinitionEmpty;
3876 definition.className = "ObjectiveC::Classes";
3877 definition.getProperty = &ObjectiveC_Classes_getProperty;
3878 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3879 ObjectiveC_Classes_ = JSClassCreate(&definition);
3881 definition = kJSClassDefinitionEmpty;
3882 definition.className = "ObjectiveC::Images";
3883 definition.getProperty = &ObjectiveC_Images_getProperty;
3884 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3885 ObjectiveC_Images_ = JSClassCreate(&definition);
3887 definition = kJSClassDefinitionEmpty;
3888 definition.className = "ObjectiveC::Image::Classes";
3889 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3890 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3891 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3893 definition = kJSClassDefinitionEmpty;
3894 definition.className = "ObjectiveC::Protocols";
3895 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3896 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3897 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3899 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
3900 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC);
3902 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3903 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3904 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3906 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3907 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3908 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3909 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
3911 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3912 JSValueProtect(context, Instance_prototype_);
3914 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3915 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3916 CYSetProperty(context, global, CYJSString("Super"), Super);
3918 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3919 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3921 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3922 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3926 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3928 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3929 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3930 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
3932 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3936 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3940 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
3941 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
3942 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
3944 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3946 System_ = JSObjectMake(context, NULL, NULL);
3947 JSValueProtect(context, System_);
3949 CYSetProperty(context, global, CYJSString("system"), System_);
3950 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3951 //CYSetProperty(context, System_, CYJSString("global"), global);
3953 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3955 Result_ = JSStringCreateWithUTF8CString("_");