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"
54 #include <CoreFoundation/CoreFoundation.h>
55 #include <CoreFoundation/CFLogUtilities.h>
56 #include <JavaScriptCore/JSStringRefCF.h>
61 #include <WebKit/WebScriptObject.h>
63 #include <Foundation/Foundation.h>
69 #include <ext/stdio_filebuf.h>
77 #include "Cycript.tab.hh"
83 #define _throw(name, args...) \
84 @throw [NSException exceptionWithName:name reason:[NSString stringWithFormat:@args] userInfo:nil]
86 #define _throw(name, args...) \
90 #define _assert(test) do { \
92 _throw(NSInternalInconsistencyException, "*** _assert(%s):%s(%u):%s [errno=%d]", #test, __FILE__, __LINE__, __FUNCTION__, errno); \
95 #define _trace() do { \
96 fprintf(stderr, "_trace():%u\n", __LINE__); \
102 @catch (NSException *error) { \
103 CYThrow(context, error, exception); \
111 catch (NSException *error) { \
112 CYThrow(context, error, exception); \
115 *exception = CYCastJSValue(context, "catch(...)"); \
121 #define CYPoolTry { \
123 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
125 #define CYPoolCatch(value) \
126 @catch (NSException *error) { \
127 _saved = [error retain]; \
133 [_saved autorelease]; \
138 #define CYPoolCatch }
142 #define class_getSuperclass GSObjCSuper
143 #define object_getClass GSObjCClass
146 void CYThrow(JSContextRef context, JSValueRef value);
148 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception);
149 JSStringRef CYCopyJSString(const char *value);
151 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value);
153 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)());
154 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
156 struct CYUTF8String {
160 CYUTF8String(const char *data, size_t size) :
167 struct CYUTF16String {
168 const uint16_t *data;
171 CYUTF16String(const uint16_t *data, size_t size) :
178 /* JavaScript Properties {{{ */
179 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
180 JSValueRef exception(NULL);
181 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
182 CYThrow(context, exception);
186 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
187 JSValueRef exception(NULL);
188 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
189 CYThrow(context, exception);
193 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
194 JSValueRef exception(NULL);
195 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
196 CYThrow(context, exception);
199 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
200 JSValueRef exception(NULL);
201 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
202 CYThrow(context, exception);
205 /* JavaScript Strings {{{ */
206 JSStringRef CYCopyJSString(const char *value) {
207 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
210 JSStringRef CYCopyJSString(JSStringRef value) {
211 return value == NULL ? NULL : JSStringRetain(value);
214 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
215 if (JSValueIsNull(context, value))
217 JSValueRef exception(NULL);
218 JSStringRef string(JSValueToStringCopy(context, value, &exception));
219 CYThrow(context, exception);
229 JSStringRelease(string_);
233 CYJSString(const CYJSString &rhs) :
234 string_(CYCopyJSString(rhs.string_))
238 template <typename Arg0_>
239 CYJSString(Arg0_ arg0) :
240 string_(CYCopyJSString(arg0))
244 template <typename Arg0_, typename Arg1_>
245 CYJSString(Arg0_ arg0, Arg1_ arg1) :
246 string_(CYCopyJSString(arg0, arg1))
250 CYJSString &operator =(const CYJSString &rhs) {
252 string_ = CYCopyJSString(rhs.string_);
265 operator JSStringRef() const {
271 // XXX: this macro is unhygenic
272 #define CYCastCString_(string) ({ \
274 if (string == NULL) \
277 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
278 utf8 = reinterpret_cast<char *>(alloca(size)); \
279 JSStringGetUTF8CString(string, utf8, size); \
284 // XXX: this macro is unhygenic
285 #define CYCastCString(context, value) ({ \
289 else if (JSStringRef string = CYCopyJSString(context, value)) { \
290 utf8 = CYCastCString_(string); \
291 JSStringRelease(string); \
300 /* Objective-C Pool Release {{{ */
301 apr_status_t CYPoolRelease_(void *data) {
302 id object(reinterpret_cast<id>(data));
307 id CYPoolRelease_(apr_pool_t *pool, id object) {
310 else if (pool == NULL)
311 return [object autorelease];
313 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
318 template <typename Type_>
319 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
320 return (Type_) CYPoolRelease_(pool, (id) object);
323 /* Objective-C Strings {{{ */
324 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
326 return [value UTF8String];
328 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
329 char *string(new(pool) char[size]);
330 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
331 _throw(NSInternalInconsistencyException, "[NSString getCString:maxLength:encoding:] == NO");
336 JSStringRef CYCopyJSString_(NSString *value) {
338 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
341 return CYCopyJSString(CYPoolCString(pool, value));
345 JSStringRef CYCopyJSString(id value) {
348 // XXX: this definition scares me; is anyone using this?!
349 NSString *string([value description]);
350 return CYCopyJSString_(string);
353 NSString *CYCopyNSString(const CYUTF8String &value) {
355 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
357 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
361 NSString *CYCopyNSString(JSStringRef value) {
363 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
365 return CYCopyNSString(CYCastCString_(value));
369 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
370 return CYCopyNSString(CYJSString(context, value));
373 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
374 return CYPoolRelease(pool, CYCopyNSString(value));
377 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
378 const char *name(sel_getName(sel));
379 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
382 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
383 return CYPoolRelease(pool, CYCopyNSString(value));
388 CYUTF8String CYCastUTF8String(NSString *value) {
389 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
390 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
393 /* JavaScript Stringify {{{ */
394 void CYStringify(std::ostringstream &str, const char *data, size_t size) {
395 unsigned quot(0), apos(0);
396 for (const char *value(data), *end(data + size); value != end; ++value)
399 else if (*value == '\'')
402 bool single(quot > apos);
404 str << (single ? '\'' : '"');
406 for (const char *value(data), *end(data + size); value != end; ++value)
408 case '\\': str << "\\\\"; break;
409 case '\b': str << "\\b"; break;
410 case '\f': str << "\\f"; break;
411 case '\n': str << "\\n"; break;
412 case '\r': str << "\\r"; break;
413 case '\t': str << "\\t"; break;
414 case '\v': str << "\\v"; break;
429 if (*value < 0x20 || *value >= 0x7f)
430 str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(*value);
435 str << (single ? '\'' : '"');
439 static JSGlobalContextRef Context_;
440 static JSObjectRef System_;
441 static JSObjectRef ObjectiveC_;
443 static JSClassRef Functor_;
444 static JSClassRef Instance_;
445 static JSClassRef Internal_;
446 static JSClassRef Message_;
447 static JSClassRef Messages_;
448 static JSClassRef Pointer_;
449 static JSClassRef Runtime_;
450 static JSClassRef Selector_;
451 static JSClassRef Struct_;
453 static JSClassRef ObjectiveC_Classes_;
454 static JSClassRef ObjectiveC_Image_Classes_;
455 static JSClassRef ObjectiveC_Images_;
456 static JSClassRef ObjectiveC_Protocols_;
458 static JSObjectRef Array_;
459 static JSObjectRef Function_;
460 static JSObjectRef String_;
462 static JSStringRef Result_;
464 static JSStringRef length_;
465 static JSStringRef message_;
466 static JSStringRef name_;
467 static JSStringRef prototype_;
468 static JSStringRef toCYON_;
469 static JSStringRef toJSON_;
471 static JSObjectRef Instance_prototype_;
472 static JSObjectRef Object_prototype_;
474 static JSObjectRef Array_prototype_;
475 static JSObjectRef Array_pop_;
476 static JSObjectRef Array_push_;
477 static JSObjectRef Array_splice_;
481 static Class NSCFBoolean_;
482 static Class NSCFType_;
485 static Class NSArray_;
486 static Class NSDictionary_;
487 static Class NSMessageBuilder_;
488 static Class NSZombie_;
489 static Class Object_;
492 static NSArray *Bridge_;
494 static void Finalize(JSObjectRef object) {
495 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
498 class Type_privateData;
508 CYValue(const void *value) :
509 value_(const_cast<void *>(value))
513 CYValue(const CYValue &rhs) :
518 virtual Type_privateData *GetType() const {
527 JSContextRef context_;
531 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
537 JSValueProtect(context_, owner_);
542 JSValueUnprotect(context_, owner_);
545 JSObjectRef GetOwner() const {
551 struct Selector_privateData :
554 Selector_privateData(SEL value) :
559 SEL GetValue() const {
560 return reinterpret_cast<SEL>(value_);
563 virtual Type_privateData *GetType() const;
566 // XXX: trick this out with associated objects!
567 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
569 return Instance_prototype_;
571 // XXX: I need to think through multi-context
572 typedef std::map<id, JSValueRef> CacheMap;
573 static CacheMap cache_;
575 JSValueRef &value(cache_[self]);
579 JSClassRef _class(NULL);
580 JSValueRef prototype;
582 if (self == NSArray_)
583 prototype = Array_prototype_;
584 else if (self == NSDictionary_)
585 prototype = Object_prototype_;
587 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
589 JSObjectRef object(JSObjectMake(context, _class, NULL));
590 JSObjectSetPrototype(context, object, prototype);
592 JSValueProtect(context, object);
602 Transient = (1 << 0),
603 Uninitialized = (1 << 1),
608 Instance(id value, Flags flags) :
614 virtual ~Instance() {
615 if ((flags_ & Transient) == 0)
616 // XXX: does this handle background threads correctly?
617 // XXX: this simply does not work on the console because I'm stupid
618 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
621 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
622 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
623 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
627 id GetValue() const {
628 return reinterpret_cast<id>(value_);
631 bool IsUninitialized() const {
632 return (flags_ & Uninitialized) != 0;
635 virtual Type_privateData *GetType() const;
641 Messages(Class value) :
646 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
647 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
648 if (_class == NSArray_)
650 if (Class super = class_getSuperclass(_class))
651 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
653 JSObjectSetPrototype(context, value, Array_prototype_);*/
657 Class GetValue() const {
658 return reinterpret_cast<Class>(value_);
665 Internal(id value, JSContextRef context, JSObjectRef owner) :
666 CYOwned(value, context, owner)
670 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
671 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
674 id GetValue() const {
675 return reinterpret_cast<id>(value_);
682 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
684 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
685 lhs.name = apr_pstrdup(pool, rhs.name);
686 if (rhs.type == NULL)
689 lhs.type = new(pool) Type;
690 Copy(pool, *lhs.type, *rhs.type);
692 lhs.offset = rhs.offset;
695 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
696 size_t count(rhs.count);
698 lhs.elements = new(pool) Element[count];
699 for (size_t index(0); index != count; ++index)
700 Copy(pool, lhs.elements[index], rhs.elements[index]);
703 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
704 lhs.primitive = rhs.primitive;
705 lhs.name = apr_pstrdup(pool, rhs.name);
706 lhs.flags = rhs.flags;
708 if (sig::IsAggregate(rhs.primitive))
709 Copy(pool, lhs.data.signature, rhs.data.signature);
711 sig::Type *&lht(lhs.data.data.type);
712 sig::Type *&rht(rhs.data.data.type);
717 lht = new(pool) Type;
718 Copy(pool, *lht, *rht);
721 lhs.data.data.size = rhs.data.data.size;
725 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
727 lhs.alignment = rhs.alignment;
729 if (rhs.elements == NULL)
733 while (rhs.elements[count] != NULL)
736 lhs.elements = new(pool) ffi_type *[count + 1];
737 lhs.elements[count] = NULL;
739 for (size_t index(0); index != count; ++index) {
740 // XXX: if these are libffi native then you can just take them
741 ffi_type *ffi(new(pool) ffi_type);
742 lhs.elements[index] = ffi;
743 sig::Copy(pool, *ffi, *rhs.elements[index]);
750 struct CStringMapLess :
751 std::binary_function<const char *, const char *, bool>
753 _finline bool operator ()(const char *lhs, const char *rhs) const {
754 return strcmp(lhs, rhs) < 0;
758 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
763 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
764 switch ([[entry objectAtIndex:0] intValue]) {
766 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
770 sig::Signature signature;
771 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
772 type = signature.elements[0].type;
778 struct Type_privateData :
782 static Type_privateData *Object;
783 static Type_privateData *Selector;
786 static JSClassRef Class_;
791 void Set(sig::Type *type) {
792 type_ = new(pool_) sig::Type;
793 sig::Copy(pool_, *type_, *type);
796 Type_privateData(apr_pool_t *pool, const char *type) :
802 sig::Signature signature;
803 sig::Parse(pool_, &signature, type, &Structor_);
804 type_ = signature.elements[0].type;
807 Type_privateData(sig::Type *type) :
814 Type_privateData(sig::Type *type, ffi_type *ffi) {
815 ffi_ = new(pool_) ffi_type;
816 sig::Copy(pool_, *ffi_, *ffi);
822 ffi_ = new(pool_) ffi_type;
824 sig::Element element;
826 element.type = type_;
829 sig::Signature signature;
830 signature.elements = &element;
834 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
842 JSClassRef Type_privateData::Class_;
845 Type_privateData *Type_privateData::Object;
846 Type_privateData *Type_privateData::Selector;
848 Type_privateData *Instance::GetType() const {
849 return Type_privateData::Object;
852 Type_privateData *Selector_privateData::GetType() const {
853 return Type_privateData::Selector;
860 Type_privateData *type_;
862 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
863 CYOwned(value, context, owner),
864 type_(new(pool_) Type_privateData(type))
869 struct Struct_privateData :
872 Type_privateData *type_;
874 Struct_privateData(JSContextRef context, JSObjectRef owner) :
875 CYOwned(NULL, context, owner)
880 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
881 static TypeMap Types_;
883 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
884 Struct_privateData *internal(new Struct_privateData(context, owner));
885 apr_pool_t *pool(internal->pool_);
886 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
887 internal->type_ = typical;
890 internal->value_ = data;
892 size_t size(typical->GetFFI()->size);
893 void *copy(apr_palloc(internal->pool_, size));
894 memcpy(copy, data, size);
895 internal->value_ = copy;
898 return JSObjectMake(context, Struct_, internal);
901 struct Functor_privateData :
904 sig::Signature signature_;
908 Functor_privateData(const char *type, void (*value)()) :
909 CYValue(reinterpret_cast<void *>(value))
911 sig::Parse(pool_, &signature_, type, &Structor_);
912 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
915 void (*GetValue())() const {
916 return reinterpret_cast<void (*)()>(value_);
920 struct Closure_privateData :
923 JSContextRef context_;
924 JSObjectRef function_;
926 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
927 Functor_privateData(type, NULL),
931 JSValueProtect(context_, function_);
934 virtual ~Closure_privateData() {
935 JSValueUnprotect(context_, function_);
940 struct Message_privateData :
945 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
946 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
952 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
953 Instance::Flags flags;
956 flags = Instance::Transient;
958 flags = Instance::None;
959 object = [object retain];
962 return Instance::Make(context, object, flags);
966 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
967 return JSValueMakeBoolean(context, value);
970 JSValueRef CYCastJSValue(JSContextRef context, double value) {
971 return JSValueMakeNumber(context, value);
974 #define CYCastJSValue_(Type_) \
975 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
976 return JSValueMakeNumber(context, static_cast<double>(value)); \
980 CYCastJSValue_(unsigned int)
981 CYCastJSValue_(long int)
982 CYCastJSValue_(long unsigned int)
983 CYCastJSValue_(long long int)
984 CYCastJSValue_(long long unsigned int)
986 JSValueRef CYJSUndefined(JSContextRef context) {
987 return JSValueMakeUndefined(context);
990 size_t CYGetIndex(const CYUTF8String &value) {
991 if (value.data[0] != '0') {
993 size_t index(strtoul(value.data, &end, 10));
994 if (value.data + value.size == end)
996 } else if (value.data[1] == '\0')
1002 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value);
1004 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
1005 return CYGetIndex(CYPoolUTF8String(pool, value));
1008 bool CYGetOffset(const char *value, ssize_t &index) {
1009 if (value[0] != '0') {
1011 index = strtol(value, &end, 10);
1012 if (value + strlen(value) == end)
1014 } else if (value[1] == '\0') {
1023 size_t CYGetIndex(NSString *value) {
1024 return CYGetIndex(CYCastUTF8String(value));
1027 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
1028 return CYGetOffset(CYPoolCString(pool, value), index);
1033 @interface NSMethodSignature (Cycript)
1034 - (NSString *) _typeString;
1037 @interface NSObject (Cycript)
1039 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1040 - (JSType) cy$JSType;
1042 - (NSObject *) cy$toJSON:(NSString *)key;
1043 - (NSString *) cy$toCYON;
1044 - (NSString *) cy$toKey;
1046 - (bool) cy$hasProperty:(NSString *)name;
1047 - (NSObject *) cy$getProperty:(NSString *)name;
1048 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
1049 - (bool) cy$deleteProperty:(NSString *)name;
1054 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1057 @interface NSString (Cycript)
1058 - (void *) cy$symbol;
1063 NSString *CYCastNSCYON(id value) {
1069 Class _class(object_getClass(value));
1070 SEL sel(@selector(cy$toCYON));
1072 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
1073 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1074 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1075 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1076 string = [value cy$toCYON];
1079 if (value == NSZombie_)
1080 string = @"_NSZombie_";
1081 else if (_class == NSZombie_)
1082 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1083 // XXX: frowny /in/ the pants
1084 else if (value == NSMessageBuilder_ || value == Object_)
1087 string = [NSString stringWithFormat:@"%@", value];
1090 // XXX: frowny pants
1092 string = @"undefined";
1101 struct PropertyAttributes {
1106 const char *variable;
1108 const char *getter_;
1109 const char *setter_;
1119 PropertyAttributes(objc_property_t property) :
1131 name = property_getName(property);
1132 const char *attributes(property_getAttributes(property));
1134 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
1136 case 'R': readonly = true; break;
1137 case 'C': copy = true; break;
1138 case '&': retain = true; break;
1139 case 'N': nonatomic = true; break;
1140 case 'G': getter_ = token + 1; break;
1141 case 'S': setter_ = token + 1; break;
1142 case 'V': variable = token + 1; break;
1146 /*if (variable == NULL) {
1147 variable = property_getName(property);
1148 size_t size(strlen(variable));
1149 char *name(new(pool_) char[size + 2]);
1151 memcpy(name + 1, variable, size);
1152 name[size + 1] = '\0';
1157 const char *Getter() {
1158 if (getter_ == NULL)
1159 getter_ = apr_pstrdup(pool_, name);
1163 const char *Setter() {
1164 if (setter_ == NULL && !readonly) {
1165 size_t length(strlen(name));
1167 char *temp(new(pool_) char[length + 5]);
1173 temp[3] = toupper(name[0]);
1174 memcpy(temp + 4, name + 1, length - 1);
1177 temp[length + 3] = ':';
1178 temp[length + 4] = '\0';
1191 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
1192 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
1199 @interface CYWebUndefined : NSObject {
1202 + (CYWebUndefined *) undefined;
1206 @implementation CYWebUndefined
1208 + (CYWebUndefined *) undefined {
1209 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
1215 #define WebUndefined CYWebUndefined
1220 /* Bridge: NSArray {{{ */
1221 @implementation NSArray (Cycript)
1223 - (NSString *) cy$toCYON {
1224 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1225 [json appendString:@"["];
1229 for (id object in self) {
1232 for (size_t index(0), count([self count]); index != count; ++index) {
1233 object = [self objectAtIndex:index];
1236 [json appendString:@","];
1239 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
1240 [json appendString:CYCastNSCYON(object)];
1242 [json appendString:@","];
1247 [json appendString:@"]"];
1251 - (bool) cy$hasProperty:(NSString *)name {
1252 if ([name isEqualToString:@"length"])
1255 size_t index(CYGetIndex(name));
1256 if (index == _not(size_t) || index >= [self count])
1257 return [super cy$hasProperty:name];
1262 - (NSObject *) cy$getProperty:(NSString *)name {
1263 if ([name isEqualToString:@"length"]) {
1264 NSUInteger count([self count]);
1266 return [NSNumber numberWithUnsignedInteger:count];
1268 return [NSNumber numberWithUnsignedInt:count];
1272 size_t index(CYGetIndex(name));
1273 if (index == _not(size_t) || index >= [self count])
1274 return [super cy$getProperty:name];
1276 return [self objectAtIndex:index];
1281 /* Bridge: NSDictionary {{{ */
1282 @implementation NSDictionary (Cycript)
1284 - (NSString *) cy$toCYON {
1285 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1286 [json appendString:@"{"];
1290 for (id key in self) {
1292 NSEnumerator *keys([self keyEnumerator]);
1293 while (id key = [keys nextObject]) {
1296 [json appendString:@","];
1299 [json appendString:[key cy$toKey]];
1300 [json appendString:@":"];
1301 NSObject *object([self objectForKey:key]);
1302 [json appendString:CYCastNSCYON(object)];
1305 [json appendString:@"}"];
1309 - (bool) cy$hasProperty:(NSString *)name {
1310 return [self objectForKey:name] != nil;
1313 - (NSObject *) cy$getProperty:(NSString *)name {
1314 return [self objectForKey:name];
1319 /* Bridge: NSMutableArray {{{ */
1320 @implementation NSMutableArray (Cycript)
1322 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1323 if ([name isEqualToString:@"length"]) {
1324 // XXX: is this not intelligent?
1325 NSNumber *number(reinterpret_cast<NSNumber *>(value));
1327 NSUInteger size([number unsignedIntegerValue]);
1329 NSUInteger size([number unsignedIntValue]);
1331 NSUInteger count([self count]);
1333 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1334 else if (size != count) {
1335 WebUndefined *undefined([WebUndefined undefined]);
1336 for (size_t i(count); i != size; ++i)
1337 [self addObject:undefined];
1342 size_t index(CYGetIndex(name));
1343 if (index == _not(size_t))
1344 return [super cy$setProperty:name to:value];
1346 id object(value ?: [NSNull null]);
1348 size_t count([self count]);
1350 [self replaceObjectAtIndex:index withObject:object];
1352 if (index != count) {
1353 WebUndefined *undefined([WebUndefined undefined]);
1354 for (size_t i(count); i != index; ++i)
1355 [self addObject:undefined];
1358 [self addObject:object];
1364 - (bool) cy$deleteProperty:(NSString *)name {
1365 size_t index(CYGetIndex(name));
1366 if (index == _not(size_t) || index >= [self count])
1367 return [super cy$deleteProperty:name];
1368 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1374 /* Bridge: NSMutableDictionary {{{ */
1375 @implementation NSMutableDictionary (Cycript)
1377 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1378 [self setObject:(value ?: [NSNull null]) forKey:name];
1382 - (bool) cy$deleteProperty:(NSString *)name {
1383 if ([self objectForKey:name] == nil)
1386 [self removeObjectForKey:name];
1393 /* Bridge: NSNumber {{{ */
1394 @implementation NSNumber (Cycript)
1396 - (JSType) cy$JSType {
1398 // XXX: this just seems stupid
1399 if ([self class] == NSCFBoolean_)
1400 return kJSTypeBoolean;
1402 return kJSTypeNumber;
1405 - (NSObject *) cy$toJSON:(NSString *)key {
1409 - (NSString *) cy$toCYON {
1410 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1413 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1414 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1419 /* Bridge: NSNull {{{ */
1420 @implementation NSNull (Cycript)
1422 - (JSType) cy$JSType {
1426 - (NSObject *) cy$toJSON:(NSString *)key {
1430 - (NSString *) cy$toCYON {
1436 /* Bridge: NSObject {{{ */
1437 @implementation NSObject (Cycript)
1439 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1440 return CYMakeInstance(context, self, false);
1443 - (JSType) cy$JSType {
1444 return kJSTypeObject;
1447 - (NSObject *) cy$toJSON:(NSString *)key {
1448 return [self description];
1451 - (NSString *) cy$toCYON {
1452 return [[self cy$toJSON:@""] cy$toCYON];
1455 - (NSString *) cy$toKey {
1456 return [self cy$toCYON];
1459 - (bool) cy$hasProperty:(NSString *)name {
1463 - (NSObject *) cy$getProperty:(NSString *)name {
1467 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1471 - (bool) cy$deleteProperty:(NSString *)name {
1477 /* Bridge: NSProxy {{{ */
1478 @implementation NSProxy (Cycript)
1480 - (NSObject *) cy$toJSON:(NSString *)key {
1481 return [self description];
1484 - (NSString *) cy$toCYON {
1485 return [[self cy$toJSON:@""] cy$toCYON];
1490 /* Bridge: NSString {{{ */
1491 @implementation NSString (Cycript)
1493 - (JSType) cy$JSType {
1494 return kJSTypeString;
1497 - (NSObject *) cy$toJSON:(NSString *)key {
1501 - (NSString *) cy$toCYON {
1502 std::ostringstream str;
1503 CYUTF8String string(CYCastUTF8String(self));
1504 CYStringify(str, string.data, string.size);
1505 std::string value(str.str());
1506 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1509 - (NSString *) cy$toKey {
1510 const char *value([self UTF8String]);
1511 size_t size(strlen(value));
1516 if (DigitRange_[value[0]]) {
1517 size_t index(CYGetIndex(self));
1518 if (index == _not(size_t))
1521 if (!WordStartRange_[value[0]])
1523 for (size_t i(1); i != size; ++i)
1524 if (!WordEndRange_[value[i]])
1531 return [self cy$toCYON];
1534 - (void *) cy$symbol {
1536 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1541 /* Bridge: WebUndefined {{{ */
1542 @implementation WebUndefined (Cycript)
1544 - (JSType) cy$JSType {
1545 return kJSTypeUndefined;
1548 - (NSObject *) cy$toJSON:(NSString *)key {
1552 - (NSString *) cy$toCYON {
1553 return @"undefined";
1556 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1557 return CYJSUndefined(context);
1563 /* Bridge: CYJSObject {{{ */
1564 @interface CYJSObject : NSMutableDictionary {
1565 JSObjectRef object_;
1566 JSContextRef context_;
1569 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1571 - (NSObject *) cy$toJSON:(NSString *)key;
1573 - (NSUInteger) count;
1574 - (id) objectForKey:(id)key;
1575 - (NSEnumerator *) keyEnumerator;
1576 - (void) setObject:(id)object forKey:(id)key;
1577 - (void) removeObjectForKey:(id)key;
1581 /* Bridge: CYJSArray {{{ */
1582 @interface CYJSArray : NSMutableArray {
1583 JSObjectRef object_;
1584 JSContextRef context_;
1587 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1589 - (NSUInteger) count;
1590 - (id) objectAtIndex:(NSUInteger)index;
1592 - (void) addObject:(id)anObject;
1593 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1594 - (void) removeLastObject;
1595 - (void) removeObjectAtIndex:(NSUInteger)index;
1596 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1603 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1604 JSValueRef exception(NULL);
1605 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1606 CYThrow(context, exception);
1607 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1608 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1611 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1612 if (!JSValueIsObjectOfClass(context, object, Instance_))
1613 return CYCastNSObject_(pool, context, object);
1615 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1616 return internal->GetValue();
1621 double CYCastDouble(const char *value, size_t size) {
1623 double number(strtod(value, &end));
1624 if (end != value + size)
1629 double CYCastDouble(const char *value) {
1630 return CYCastDouble(value, strlen(value));
1633 double CYCastDouble(JSContextRef context, JSValueRef value) {
1634 JSValueRef exception(NULL);
1635 double number(JSValueToNumber(context, value, &exception));
1636 CYThrow(context, exception);
1641 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
1642 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
1646 bool CYCastBool(JSContextRef context, JSValueRef value) {
1647 return JSValueToBoolean(context, value);
1651 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1655 switch (JSType type = JSValueGetType(context, value)) {
1656 case kJSTypeUndefined:
1657 object = [WebUndefined undefined];
1665 case kJSTypeBoolean:
1667 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
1670 object = [[NSNumber alloc] initWithBool:CYCastBool(context, value)];
1676 object = CYCopyNSNumber(context, value);
1681 object = CYCopyNSString(context, value);
1686 // XXX: this might could be more efficient
1687 object = CYCastNSObject(pool, context, (JSObjectRef) value);
1692 _throw(NSInternalInconsistencyException, "JSValueGetType() == 0x%x", type);
1699 return CYPoolRelease(pool, object);
1701 return [object retain];
1704 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1705 return CYNSObject(pool, context, value, true);
1708 id CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1709 return CYNSObject(pool, context, value, false);
1712 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1714 size_t size(JSPropertyNameArrayGetCount(names));
1715 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1716 for (size_t index(0); index != size; ++index)
1717 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1722 void CYThrow(JSContextRef context, JSValueRef value) {
1726 @throw CYCastNSObject(NULL, context, value);
1733 JSValueRef CYJSNull(JSContextRef context) {
1734 return JSValueMakeNull(context);
1737 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1738 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1741 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1742 return CYCastJSValue(context, CYJSString(value));
1746 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1748 return CYJSNull(context);
1749 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1750 return [value cy$JSValueInContext:context];
1752 return CYMakeInstance(context, value, false);
1756 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1757 JSValueRef exception(NULL);
1758 JSObjectRef object(JSValueToObject(context, value, &exception));
1759 CYThrow(context, exception);
1763 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1764 if (exception == NULL)
1766 *exception = CYCastJSValue(context, error);
1769 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1770 JSValueRef exception(NULL);
1771 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1772 CYThrow(context, exception);
1776 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1777 // XXX: this isn't actually correct
1778 return value != NULL && JSValueIsObject(context, value);
1782 @implementation CYJSObject
1784 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1785 if ((self = [super init]) != nil) {
1788 JSValueProtect(context_, object_);
1793 JSValueUnprotect(context_, object_);
1797 - (NSObject *) cy$toJSON:(NSString *)key {
1798 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1799 if (!CYIsCallable(context_, toJSON))
1800 return [super cy$toJSON:key];
1802 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1803 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1804 // XXX: do I really want an NSNull here?!
1805 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1809 - (NSString *) cy$toCYON {
1810 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1811 if (!CYIsCallable(context_, toCYON)) super:
1812 return [super cy$toCYON];
1813 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1814 return CYCastNSString(NULL, CYJSString(context_, value));
1818 - (NSUInteger) count {
1819 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1820 size_t size(JSPropertyNameArrayGetCount(names));
1821 JSPropertyNameArrayRelease(names);
1825 - (id) objectForKey:(id)key {
1826 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1827 if (JSValueIsUndefined(context_, value))
1829 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1832 - (NSEnumerator *) keyEnumerator {
1833 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1834 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1835 JSPropertyNameArrayRelease(names);
1839 - (void) setObject:(id)object forKey:(id)key {
1840 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1843 - (void) removeObjectForKey:(id)key {
1844 JSValueRef exception(NULL);
1845 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1846 CYThrow(context_, exception);
1851 @implementation CYJSArray
1853 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1854 if ((self = [super init]) != nil) {
1857 JSValueProtect(context_, object_);
1862 JSValueUnprotect(context_, object_);
1866 - (NSUInteger) count {
1867 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1870 - (id) objectAtIndex:(NSUInteger)index {
1871 size_t bounds([self count]);
1872 if (index >= bounds)
1873 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1874 JSValueRef exception(NULL);
1875 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1876 CYThrow(context_, exception);
1877 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1880 - (void) addObject:(id)object {
1881 JSValueRef exception(NULL);
1882 JSValueRef arguments[1];
1883 arguments[0] = CYCastJSValue(context_, object);
1884 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1885 CYThrow(context_, exception);
1888 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1889 size_t bounds([self count] + 1);
1890 if (index >= bounds)
1891 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1892 JSValueRef exception(NULL);
1893 JSValueRef arguments[3];
1894 arguments[0] = CYCastJSValue(context_, index);
1895 arguments[1] = CYCastJSValue(context_, 0);
1896 arguments[2] = CYCastJSValue(context_, object);
1897 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1898 CYThrow(context_, exception);
1901 - (void) removeLastObject {
1902 JSValueRef exception(NULL);
1903 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1904 CYThrow(context_, exception);
1907 - (void) removeObjectAtIndex:(NSUInteger)index {
1908 size_t bounds([self count]);
1909 if (index >= bounds)
1910 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1911 JSValueRef exception(NULL);
1912 JSValueRef arguments[2];
1913 arguments[0] = CYCastJSValue(context_, index);
1914 arguments[1] = CYCastJSValue(context_, 1);
1915 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1916 CYThrow(context_, exception);
1919 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1920 size_t bounds([self count]);
1921 if (index >= bounds)
1922 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1923 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1929 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1930 if (JSValueIsNull(context, value))
1931 return [@"null" retain];
1935 return [CYCastNSCYON(CYCastNSObject(NULL, context, value)) retain];
1940 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1941 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1942 const char *string(CYPoolCString(pool, json));
1949 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1953 JSObjectRef object_;
1961 // XXX: delete object_? ;(
1964 static CYInternal *Get(id self) {
1965 CYInternal *internal(NULL);
1966 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1967 // XXX: do something epic? ;P
1973 static CYInternal *Set(id self) {
1974 CYInternal *internal(NULL);
1975 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1976 if (internal == NULL) {
1977 internal = new CYInternal();
1978 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1981 // XXX: do something epic? ;P
1987 bool HasProperty(JSContextRef context, JSStringRef name) {
1988 if (object_ == NULL)
1990 return JSObjectHasProperty(context, object_, name);
1993 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1994 if (object_ == NULL)
1996 return CYGetProperty(context, object_, name);
1999 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
2000 if (object_ == NULL)
2001 object_ = JSObjectMake(context, NULL, NULL);
2002 CYSetProperty(context, object_, name, value);
2008 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
2009 Selector_privateData *internal(new Selector_privateData(sel));
2010 return JSObjectMake(context, Selector_, internal);
2014 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
2015 Pointer *internal(new Pointer(pointer, context, owner, type));
2016 return JSObjectMake(context, Pointer_, internal);
2019 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
2020 Functor_privateData *internal(new Functor_privateData(type, function));
2021 return JSObjectMake(context, Functor_, internal);
2024 static CYUTF16String CYCastUTF16String(JSStringRef value) {
2025 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
2028 // XXX: sometimes pool is null
2029 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value) {
2030 CYUTF16String utf16(CYCastUTF16String(value));
2031 const char *in(reinterpret_cast<const char *>(utf16.data));
2033 iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL")));
2035 size_t size(JSStringGetMaximumUTF8CStringSize(value));
2036 char *out(new(pool) char[size]);
2037 CYUTF8String utf8(out, size);
2039 size = utf16.size * 2;
2040 _syscall(iconv(conversion, const_cast<char **>(&in), &size, &out, &utf8.size));
2043 utf8.size = out - utf8.data;
2045 _syscall(iconv_close(conversion));
2050 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
2051 CYUTF8String utf8(CYPoolUTF8String(pool, value));
2052 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
2056 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
2057 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
2060 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
2061 return CYGetOffset(CYPoolCString(pool, value), index);
2064 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
2065 switch (JSValueGetType(context, value)) {
2068 /*case kJSTypeString:
2069 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
2071 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
2072 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
2073 return internal->value_;
2076 double number(CYCastDouble(context, value));
2077 if (std::isnan(number))
2078 _throw(NSInvalidArgumentException, "cannot convert value to pointer");
2079 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
2083 template <typename Type_>
2084 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
2085 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
2089 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
2090 if (JSValueIsObjectOfClass(context, value, Selector_)) {
2091 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2092 return reinterpret_cast<SEL>(internal->value_);
2094 return CYCastPointer<SEL>(context, value);
2098 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
2099 switch (type->primitive) {
2100 case sig::boolean_P:
2101 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
2104 #define CYPoolFFI_(primitive, native) \
2105 case sig::primitive ## _P: \
2106 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
2109 CYPoolFFI_(uchar, unsigned char)
2110 CYPoolFFI_(char, char)
2111 CYPoolFFI_(ushort, unsigned short)
2112 CYPoolFFI_(short, short)
2113 CYPoolFFI_(ulong, unsigned long)
2114 CYPoolFFI_(long, long)
2115 CYPoolFFI_(uint, unsigned int)
2116 CYPoolFFI_(int, int)
2117 CYPoolFFI_(ulonglong, unsigned long long)
2118 CYPoolFFI_(longlong, long long)
2119 CYPoolFFI_(float, float)
2120 CYPoolFFI_(double, double)
2124 case sig::typename_P:
2125 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
2128 case sig::selector_P:
2129 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
2133 case sig::pointer_P:
2134 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
2138 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
2141 case sig::struct_P: {
2142 uint8_t *base(reinterpret_cast<uint8_t *>(data));
2143 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
2144 for (size_t index(0); index != type->data.signature.count; ++index) {
2145 sig::Element *element(&type->data.signature.elements[index]);
2146 ffi_type *field(ffi->elements[index]);
2149 if (aggregate == NULL)
2152 rhs = CYGetProperty(context, aggregate, index);
2153 if (JSValueIsUndefined(context, rhs)) {
2154 if (element->name != NULL)
2155 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
2158 if (JSValueIsUndefined(context, rhs)) undefined:
2159 _throw(NSInvalidArgumentException, "unable to extract structure value");
2163 CYPoolFFI(pool, context, element->type, field, base, rhs);
2165 base += field->size;
2173 fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
2178 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
2181 switch (type->primitive) {
2182 case sig::boolean_P:
2183 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
2186 #define CYFromFFI_(primitive, native) \
2187 case sig::primitive ## _P: \
2188 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
2191 CYFromFFI_(uchar, unsigned char)
2192 CYFromFFI_(char, char)
2193 CYFromFFI_(ushort, unsigned short)
2194 CYFromFFI_(short, short)
2195 CYFromFFI_(ulong, unsigned long)
2196 CYFromFFI_(long, long)
2197 CYFromFFI_(uint, unsigned int)
2198 CYFromFFI_(int, int)
2199 CYFromFFI_(ulonglong, unsigned long long)
2200 CYFromFFI_(longlong, long long)
2201 CYFromFFI_(float, float)
2202 CYFromFFI_(double, double)
2205 case sig::object_P: {
2206 if (id object = *reinterpret_cast<id *>(data)) {
2207 value = CYCastJSValue(context, object);
2213 case sig::typename_P:
2214 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
2217 case sig::selector_P:
2218 if (SEL sel = *reinterpret_cast<SEL *>(data))
2219 value = CYMakeSelector(context, sel);
2224 case sig::pointer_P:
2225 if (void *pointer = *reinterpret_cast<void **>(data))
2226 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
2231 if (char *utf8 = *reinterpret_cast<char **>(data))
2232 value = CYCastJSValue(context, utf8);
2237 value = CYMakeStruct(context, data, type, ffi, owner);
2241 value = CYJSUndefined(context);
2245 value = CYJSNull(context);
2249 fprintf(stderr, "CYFromFFI(%c)\n", type->primitive);
2256 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
2257 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
2261 method_getReturnType(method, type, sizeof(type));
2266 // XXX: possibly use a more "awesome" check?
2270 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, objc_method *method) {
2272 return method_getTypeEncoding(method);
2273 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel)])
2274 return CYPoolCString(pool, type);
2279 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2280 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2282 JSContextRef context(internal->context_);
2284 size_t count(internal->cif_.nargs);
2285 JSValueRef values[count];
2287 for (size_t index(0); index != count; ++index)
2288 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2290 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2291 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2294 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2295 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2297 JSContextRef context(internal->context_);
2299 size_t count(internal->cif_.nargs);
2300 JSValueRef values[count];
2302 for (size_t index(0); index != count; ++index)
2303 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2305 JSObjectRef _this(CYCastJSObject(context, values[0]));
2307 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2308 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2311 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2312 // XXX: in case of exceptions this will leak
2313 // XXX: in point of fact, this may /need/ to leak :(
2314 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2316 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2317 NULL, sizeof(ffi_closure),
2318 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2322 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2323 _assert(status == FFI_OK);
2325 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2327 internal->value_ = closure;
2332 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2333 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2334 return JSObjectMake(context, Functor_, internal);
2337 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2338 JSValueRef exception(NULL);
2339 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2340 CYThrow(context, exception);
2343 JSObjectRef function(CYCastJSObject(context, value));
2344 return CYMakeFunctor(context, function, type);
2346 void (*function)()(CYCastPointer<void (*)()>(context, value));
2347 return CYMakeFunctor(context, function, type);
2352 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2353 Message_privateData *internal(new Message_privateData(sel, type, imp));
2354 return JSObjectMake(context, Message_, internal);
2357 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2358 JSObjectRef function(CYCastJSObject(context, value));
2359 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2360 return reinterpret_cast<IMP>(internal->GetValue());
2363 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2364 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2365 Class _class(internal->GetValue());
2368 const char *name(CYPoolCString(pool, property));
2370 if (SEL sel = sel_getUid(name))
2371 if (class_getInstanceMethod(_class, sel) != NULL)
2377 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2378 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2379 Class _class(internal->GetValue());
2382 const char *name(CYPoolCString(pool, property));
2384 if (SEL sel = sel_getUid(name))
2385 if (objc_method *method = class_getInstanceMethod(_class, sel))
2386 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2391 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2392 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2393 Class _class(internal->GetValue());
2396 const char *name(CYPoolCString(pool, property));
2398 SEL sel(sel_registerName(name));
2400 objc_method *method(class_getInstanceMethod(_class, sel));
2405 if (JSValueIsObjectOfClass(context, value, Message_)) {
2406 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2407 type = sig::Unparse(pool, &message->signature_);
2408 imp = reinterpret_cast<IMP>(message->GetValue());
2410 type = CYPoolTypeEncoding(pool, _class, sel, method);
2411 imp = CYMakeMessage(context, value, type);
2415 method_setImplementation(method, imp);
2417 class_replaceMethod(_class, sel, imp, type);
2423 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2424 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2425 Class _class(internal->GetValue());
2428 const char *name(CYPoolCString(pool, property));
2430 if (SEL sel = sel_getUid(name))
2431 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
2432 objc_method_list list = {NULL, 1, {method}};
2433 class_removeMethods(_class, &list);
2441 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2442 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2443 Class _class(internal->GetValue());
2446 objc_method **data(class_copyMethodList(_class, &size));
2447 for (size_t i(0); i != size; ++i)
2448 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2452 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2453 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2454 id self(internal->GetValue());
2456 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2460 NSString *name(CYCastNSString(pool, property));
2462 if (CYInternal *internal = CYInternal::Get(self))
2463 if (internal->HasProperty(context, property))
2466 Class _class(object_getClass(self));
2469 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2470 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2471 if ([self cy$hasProperty:name])
2473 } CYPoolCatch(false)
2475 const char *string(CYPoolCString(pool, name));
2477 if (class_getProperty(_class, string) != NULL)
2480 if (SEL sel = sel_getUid(string))
2481 if (CYImplements(self, _class, sel, true))
2487 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2488 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2489 id self(internal->GetValue());
2491 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2492 return Internal::Make(context, self, object);
2496 NSString *name(CYCastNSString(pool, property));
2498 if (CYInternal *internal = CYInternal::Get(self))
2499 if (JSValueRef value = internal->GetProperty(context, property))
2503 if (NSObject *data = [self cy$getProperty:name])
2504 return CYCastJSValue(context, data);
2507 const char *string(CYPoolCString(pool, name));
2508 Class _class(object_getClass(self));
2511 if (objc_property_t property = class_getProperty(_class, string)) {
2512 PropertyAttributes attributes(property);
2513 SEL sel(sel_registerName(attributes.Getter()));
2514 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2518 if (SEL sel = sel_getUid(string))
2519 if (CYImplements(self, _class, sel, true))
2520 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2526 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2527 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2528 id self(internal->GetValue());
2533 NSString *name(CYCastNSString(pool, property));
2534 NSObject *data(CYCastNSObject(pool, context, value));
2537 if ([self cy$setProperty:name to:data])
2541 const char *string(CYPoolCString(pool, name));
2542 Class _class(object_getClass(self));
2545 if (objc_property_t property = class_getProperty(_class, string)) {
2546 PropertyAttributes attributes(property);
2547 if (const char *setter = attributes.Setter()) {
2548 SEL sel(sel_registerName(setter));
2549 JSValueRef arguments[1] = {value};
2550 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2556 size_t length(strlen(string));
2558 char set[length + 5];
2564 if (string[0] != '\0') {
2565 set[3] = toupper(string[0]);
2566 memcpy(set + 4, string + 1, length - 1);
2569 set[length + 3] = ':';
2570 set[length + 4] = '\0';
2572 if (SEL sel = sel_getUid(set))
2573 if (CYImplements(self, _class, sel, false)) {
2574 JSValueRef arguments[1] = {value};
2575 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2578 if (CYInternal *internal = CYInternal::Set(self)) {
2579 internal->SetProperty(context, property, value);
2587 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2588 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2589 id self(internal->GetValue());
2593 NSString *name(CYCastNSString(NULL, property));
2594 return [self cy$deleteProperty:name];
2599 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2600 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2601 id self(internal->GetValue());
2604 Class _class(object_getClass(self));
2608 objc_property_t *data(class_copyPropertyList(_class, &size));
2609 for (size_t i(0); i != size; ++i)
2610 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2615 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2617 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2618 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2623 static bool CYIsClass(id self) {
2624 // XXX: this is a lame object_isClass
2625 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2628 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2629 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2630 Class _class(internal->GetValue());
2631 if (!CYIsClass(_class))
2634 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2635 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2636 // XXX: this isn't always safe
2638 return [linternal->GetValue() isKindOfClass:_class];
2645 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2646 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2649 id self(internal->GetValue());
2650 const char *name(CYPoolCString(pool, property));
2652 if (object_getInstanceVariable(self, name, NULL) != NULL)
2658 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2659 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2663 id self(internal->GetValue());
2664 const char *name(CYPoolCString(pool, property));
2666 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2667 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2668 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2675 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2676 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2680 id self(internal->GetValue());
2681 const char *name(CYPoolCString(pool, property));
2683 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2684 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2685 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2693 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2694 if (Class super = class_getSuperclass(_class))
2695 Internal_getPropertyNames_(super, names);
2698 Ivar *data(class_copyIvarList(_class, &size));
2699 for (size_t i(0); i != size; ++i)
2700 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2704 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2705 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2708 id self(internal->GetValue());
2709 Class _class(object_getClass(self));
2711 Internal_getPropertyNames_(_class, names);
2714 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2715 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2716 return internal->GetOwner();
2720 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2721 Type_privateData *typical(internal->type_);
2722 sig::Type *type(typical->type_);
2726 const char *name(CYPoolCString(pool, property));
2727 size_t length(strlen(name));
2728 double number(CYCastDouble(name, length));
2730 size_t count(type->data.signature.count);
2732 if (std::isnan(number)) {
2733 if (property == NULL)
2736 sig::Element *elements(type->data.signature.elements);
2738 for (size_t local(0); local != count; ++local) {
2739 sig::Element *element(&elements[local]);
2740 if (element->name != NULL && strcmp(name, element->name) == 0) {
2748 index = static_cast<ssize_t>(number);
2749 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2754 ffi_type **elements(typical->GetFFI()->elements);
2756 base = reinterpret_cast<uint8_t *>(internal->value_);
2757 for (ssize_t local(0); local != index; ++local)
2758 base += elements[local]->size;
2763 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2764 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2765 Type_privateData *typical(internal->type_);
2767 ffi_type *ffi(typical->GetFFI());
2769 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2770 base += ffi->size * index;
2772 JSObjectRef owner(internal->GetOwner() ?: object);
2775 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2779 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2781 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2782 Type_privateData *typical(internal->type_);
2784 if (typical->type_ == NULL)
2788 if (!CYGetOffset(pool, property, offset))
2791 return Pointer_getIndex(context, object, offset, exception);
2794 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2795 return Pointer_getIndex(context, object, 0, exception);
2798 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2799 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2800 Type_privateData *typical(internal->type_);
2802 ffi_type *ffi(typical->GetFFI());
2804 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2805 base += ffi->size * index;
2808 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2813 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2815 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2816 Type_privateData *typical(internal->type_);
2818 if (typical->type_ == NULL)
2822 if (!CYGetOffset(pool, property, offset))
2825 return Pointer_setIndex(context, object, offset, value, exception);
2828 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2829 return Pointer_setIndex(context, object, 0, value, exception);
2832 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2833 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2834 Type_privateData *typical(internal->type_);
2835 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2838 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2840 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2841 Type_privateData *typical(internal->type_);
2847 if (!Index_(pool, internal, property, index, base))
2850 JSObjectRef owner(internal->GetOwner() ?: object);
2852 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2856 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2858 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2859 Type_privateData *typical(internal->type_);
2865 if (!Index_(pool, internal, property, index, base))
2868 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2873 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2874 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2875 Type_privateData *typical(internal->type_);
2876 sig::Type *type(typical->type_);
2881 size_t count(type->data.signature.count);
2882 sig::Element *elements(type->data.signature.elements);
2886 for (size_t index(0); index != count; ++index) {
2888 name = elements[index].name;
2891 sprintf(number, "%lu", index);
2895 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2899 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)()) {
2901 if (setups + count != signature->count - 1)
2902 _throw(NSInvalidArgumentException, "incorrect number of arguments to ffi function");
2904 size_t size(setups + count);
2906 memcpy(values, setup, sizeof(void *) * setups);
2908 for (size_t index(setups); index != size; ++index) {
2909 sig::Element *element(&signature->elements[index + 1]);
2910 ffi_type *ffi(cif->arg_types[index]);
2912 values[index] = new(pool) uint8_t[ffi->size];
2913 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2916 uint8_t value[cif->rtype->size];
2917 ffi_call(cif, function, value, values);
2919 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2923 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2926 NSString *name(CYCastNSString(pool, property));
2927 if (Class _class = NSClassFromString(name))
2928 return CYMakeInstance(context, _class, true);
2933 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2934 size_t size(objc_getClassList(NULL, 0));
2935 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2938 size_t writ(objc_getClassList(data, size));
2941 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2947 for (size_t i(0); i != writ; ++i)
2948 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2954 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2955 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2959 const char *name(CYPoolCString(pool, property));
2961 const char **data(objc_copyClassNamesForImage(internal, &size));
2963 for (size_t i(0); i != size; ++i)
2964 if (strcmp(name, data[i]) == 0) {
2965 if (Class _class = objc_getClass(name)) {
2966 value = CYMakeInstance(context, _class, true);
2978 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2979 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2981 const char **data(objc_copyClassNamesForImage(internal, &size));
2982 for (size_t i(0); i != size; ++i)
2983 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2987 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2990 const char *name(CYPoolCString(pool, property));
2992 const char **data(objc_copyImageNames(&size));
2993 for (size_t i(0); i != size; ++i)
2994 if (strcmp(name, data[i]) == 0) {
3003 JSObjectRef value(JSObjectMake(context, NULL, NULL));
3004 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
3009 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3011 const char **data(objc_copyImageNames(&size));
3012 for (size_t i(0); i != size; ++i)
3013 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3017 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3020 NSString *name(CYCastNSString(pool, property));
3021 if (Protocol *protocol = NSProtocolFromString(name))
3022 return CYMakeInstance(context, protocol, true);
3027 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3029 Protocol **data(objc_copyProtocolList(&size));
3030 for (size_t i(0); i != size; ++i)
3031 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
3035 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
3036 Type_privateData *internal(new Type_privateData(NULL, type));
3037 return JSObjectMake(context, Type_privateData::Class_, internal);
3040 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
3041 Type_privateData *internal(new Type_privateData(type));
3042 return JSObjectMake(context, Type_privateData::Class_, internal);
3045 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3046 if (JSStringIsEqualToUTF8CString(property, "nil"))
3047 return Instance::Make(context, nil);
3051 NSString *name(CYCastNSString(pool, property));
3052 if (Class _class = NSClassFromString(name))
3053 return CYMakeInstance(context, _class, true);
3054 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
3055 switch ([[entry objectAtIndex:0] intValue]) {
3057 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
3059 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
3061 // XXX: this is horrendously inefficient
3062 sig::Signature signature;
3063 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
3065 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3066 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
3068 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
3069 switch ([[entry objectAtIndex:0] intValue]) {
3070 // XXX: implement case 0
3072 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
3078 static bool stret(ffi_type *ffi_type) {
3079 return ffi_type->type == FFI_TYPE_STRUCT && (
3080 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
3081 struct_forward_array[ffi_type->size] != 0
3086 int *_NSGetArgc(void);
3087 char ***_NSGetArgv(void);
3090 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3095 printf("%s\n", CYCastCString(context, arguments[0]));
3096 return CYJSUndefined(context);
3100 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
3103 Class _class(object_getClass(self));
3104 if (objc_method *method = class_getInstanceMethod(_class, _cmd))
3105 type = method_getTypeEncoding(method);
3109 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
3111 _throw(NSInvalidArgumentException, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3112 type = CYPoolCString(pool, [method _typeString]);
3121 sig::Signature signature;
3122 sig::Parse(pool, &signature, type, &Structor_);
3125 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3127 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
3128 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3131 static size_t Nonce_(0);
3133 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3135 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
3136 return CYCastJSValue(context, name);
3139 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3149 _throw(NSInvalidArgumentException, "too few arguments to objc_msgSend");
3151 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
3152 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3153 self = internal->GetValue();
3154 uninitialized = internal->IsUninitialized();
3156 internal->value_ = nil;
3158 self = CYCastNSObject(pool, context, arguments[0]);
3159 uninitialized = false;
3163 return CYJSNull(context);
3165 _cmd = CYCastSEL(context, arguments[1]);
3168 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
3172 /* Hook: objc_registerClassPair {{{ */
3173 // XXX: replace this with associated objects
3175 MSHook(void, CYDealloc, id self, SEL sel) {
3176 CYInternal *internal;
3177 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
3178 if (internal != NULL)
3180 _CYDealloc(self, sel);
3183 MSHook(void, objc_registerClassPair, Class _class) {
3184 Class super(class_getSuperclass(_class));
3185 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
3186 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
3187 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
3190 _objc_registerClassPair(_class);
3193 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3196 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3198 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3199 if (value == NULL || !CYIsClass(value))
3200 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3201 Class _class((Class) value);
3202 $objc_registerClassPair(_class);
3203 return CYJSUndefined(context);
3209 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3210 JSGarbageCollect(context);
3211 return CYJSUndefined(context);
3215 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3216 JSValueRef setup[count + 2];
3219 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
3220 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
3223 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3225 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
3227 // XXX: handle Instance::Uninitialized?
3228 id self(CYCastNSObject(pool, context, _this));
3232 setup[1] = &internal->sel_;
3234 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3238 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3240 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
3241 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3244 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3247 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector constructor");
3248 const char *name(CYCastCString(context, arguments[0]));
3249 return CYMakeSelector(context, sel_registerName(name));
3253 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3256 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3258 void *value(CYCastPointer<void *>(context, arguments[0]));
3259 const char *type(CYCastCString(context, arguments[1]));
3263 sig::Signature signature;
3264 sig::Parse(pool, &signature, type, &Structor_);
3266 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
3270 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3273 _throw(NSInvalidArgumentException, "incorrect number of arguments to Type constructor");
3274 const char *type(CYCastCString(context, arguments[0]));
3275 return CYMakeType(context, type);
3279 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3280 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3285 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3286 type.primitive = sig::pointer_P;
3287 type.data.data.size = 0;
3289 size_t index(CYGetIndex(NULL, property));
3290 if (index == _not(size_t))
3292 type.primitive = sig::array_P;
3293 type.data.data.size = index;
3299 type.data.data.type = internal->type_;
3301 return CYMakeType(context, &type);
3305 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3306 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3310 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3311 sig::Type *type(internal->type_);
3312 ffi_type *ffi(internal->GetFFI());
3314 uint8_t value[ffi->size];
3316 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3317 return CYFromFFI(context, type, ffi, value);
3321 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3324 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3325 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3327 sig::Type *type(internal->type_);
3330 if (type->primitive != sig::array_P)
3333 size = type->data.data.size;
3334 type = type->data.data.type;
3337 void *value(malloc(internal->GetFFI()->size));
3338 return CYMakePointer(context, value, type, NULL, NULL);
3343 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3346 _throw(NSInvalidArgumentException, "incorrect number of arguments to Instance constructor");
3347 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3348 return Instance::Make(context, self);
3353 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3356 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3357 const char *type(CYCastCString(context, arguments[1]));
3358 return CYMakeFunctor(context, arguments[0], type);
3362 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3363 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3364 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3367 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3368 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3369 Type_privateData *typical(internal->GetType());
3374 if (typical == NULL) {
3378 type = typical->type_;
3379 ffi = typical->ffi_;
3382 return CYMakePointer(context, &internal->value_, type, ffi, object);
3385 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3386 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3389 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3393 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3394 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3397 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3398 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3400 sprintf(string, "%p", internal->value_);
3403 return CYCastJSValue(context, string);
3408 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3409 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3410 return Instance::Make(context, object_getClass(internal->GetValue()));
3413 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3414 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3415 id self(internal->GetValue());
3416 if (!CYIsClass(self))
3417 return CYJSUndefined(context);
3419 return CYGetClassPrototype(context, self);
3423 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3424 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3425 id self(internal->GetValue());
3426 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3427 return CYJSUndefined(context);
3428 return Messages::Make(context, self);
3431 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3432 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3435 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3439 return CYCastJSValue(context, CYJSString(CYCastNSCYON(internal->GetValue())));
3444 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3445 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3448 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3452 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3453 // XXX: check for support of cy$toJSON?
3454 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3459 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3460 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3463 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3467 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3472 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3473 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3476 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3480 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3481 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3484 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3485 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3486 const char *name(sel_getName(internal->GetValue()));
3490 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3495 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3498 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector.type");
3500 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3501 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3502 if (value == NULL) lookup:
3503 // XXX: do a lookup of some kind
3504 return CYJSNull(context);
3505 else if (!CYIsClass(value))
3506 _throw(NSInvalidArgumentException, "Selector.type takes a Class");
3508 Class _class((Class) value);
3509 SEL sel(internal->GetValue());
3510 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
3511 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3512 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3519 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3521 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3523 const char *type(sig::Unparse(pool, internal->type_));
3524 return CYCastJSValue(context, CYJSString(type));
3528 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3530 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3532 const char *type(sig::Unparse(pool, internal->type_));
3533 size_t size(strlen(type));
3534 char *cyon(new(pool) char[12 + size + 1]);
3535 memcpy(cyon, "new Type(\"", 10);
3536 cyon[12 + size] = '\0';
3537 cyon[12 + size - 2] = '"';
3538 cyon[12 + size - 1] = ')';
3539 memcpy(cyon + 10, type, size);
3540 return CYCastJSValue(context, CYJSString(cyon));
3544 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3545 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3548 static JSStaticValue CYValue_staticValues[2] = {
3549 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3550 {NULL, NULL, NULL, 0}
3553 static JSStaticValue Pointer_staticValues[2] = {
3554 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3555 {NULL, NULL, NULL, 0}
3558 static JSStaticFunction Pointer_staticFunctions[4] = {
3559 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3560 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3561 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3565 static JSStaticFunction Struct_staticFunctions[2] = {
3566 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3570 static JSStaticFunction Functor_staticFunctions[4] = {
3571 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3572 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3573 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3578 static JSStaticValue Instance_staticValues[5] = {
3579 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3580 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3581 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3582 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3583 {NULL, NULL, NULL, 0}
3586 static JSStaticFunction Instance_staticFunctions[5] = {
3587 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3588 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3589 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3590 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3594 static JSStaticFunction Internal_staticFunctions[2] = {
3595 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3599 static JSStaticFunction Selector_staticFunctions[5] = {
3600 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3601 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3602 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3603 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3608 static JSStaticFunction Type_staticFunctions[4] = {
3609 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3610 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3611 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3615 void CYSetArgs(int argc, const char *argv[]) {
3616 JSContextRef context(CYGetJSContext());
3617 JSValueRef args[argc];
3618 for (int i(0); i != argc; ++i)
3619 args[i] = CYCastJSValue(context, argv[i]);
3620 JSValueRef exception(NULL);
3621 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3622 CYThrow(context, exception);
3623 CYSetProperty(context, System_, CYJSString("args"), array);
3626 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3627 return JSContextGetGlobalObject(context);
3630 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3631 JSContextRef context(CYGetJSContext());
3632 JSValueRef exception(NULL), result;
3635 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3636 } catch (const char *error) {
3640 if (exception != NULL) { error:
3645 if (JSValueIsUndefined(context, result))
3651 json = CYPoolCCYON(pool, context, result, &exception);
3652 } catch (const char *error) {
3656 if (exception != NULL)
3659 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3663 static apr_pool_t *Pool_;
3665 apr_pool_t *CYGetGlobalPool() {
3669 MSInitialize { _pooled
3670 _aprcall(apr_initialize());
3671 _aprcall(apr_pool_create(&Pool_, NULL));
3673 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3676 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3677 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3680 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3681 NSCFType_ = objc_getClass("NSCFType");
3684 NSArray_ = objc_getClass("NSArray");
3685 NSDictionary_ = objc_getClass("NSDictonary");
3686 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3687 NSZombie_ = objc_getClass("_NSZombie_");
3688 Object_ = objc_getClass("Object");
3692 JSGlobalContextRef CYGetJSContext() {
3693 if (Context_ == NULL) {
3694 JSClassDefinition definition;
3696 definition = kJSClassDefinitionEmpty;
3697 definition.className = "Functor";
3698 definition.staticFunctions = Functor_staticFunctions;
3699 definition.callAsFunction = &Functor_callAsFunction;
3700 definition.finalize = &Finalize;
3701 Functor_ = JSClassCreate(&definition);
3703 definition = kJSClassDefinitionEmpty;
3704 definition.className = "Pointer";
3705 definition.staticValues = Pointer_staticValues;
3706 definition.staticFunctions = Pointer_staticFunctions;
3707 definition.getProperty = &Pointer_getProperty;
3708 definition.setProperty = &Pointer_setProperty;
3709 definition.finalize = &Finalize;
3710 Pointer_ = JSClassCreate(&definition);
3712 definition = kJSClassDefinitionEmpty;
3713 definition.className = "Selector";
3714 definition.staticValues = CYValue_staticValues;
3715 definition.staticFunctions = Selector_staticFunctions;
3716 definition.callAsFunction = &Selector_callAsFunction;
3717 definition.finalize = &Finalize;
3718 Selector_ = JSClassCreate(&definition);
3720 definition = kJSClassDefinitionEmpty;
3721 definition.className = "Struct";
3722 definition.staticFunctions = Struct_staticFunctions;
3723 definition.getProperty = &Struct_getProperty;
3724 definition.setProperty = &Struct_setProperty;
3725 definition.getPropertyNames = &Struct_getPropertyNames;
3726 definition.finalize = &Finalize;
3727 Struct_ = JSClassCreate(&definition);
3729 definition = kJSClassDefinitionEmpty;
3730 definition.className = "Type";
3731 definition.staticFunctions = Type_staticFunctions;
3732 definition.getProperty = &Type_getProperty;
3733 definition.callAsFunction = &Type_callAsFunction;
3734 definition.callAsConstructor = &Type_callAsConstructor;
3735 definition.finalize = &Finalize;
3736 Type_privateData::Class_ = JSClassCreate(&definition);
3738 definition = kJSClassDefinitionEmpty;
3739 definition.className = "Runtime";
3740 definition.getProperty = &Runtime_getProperty;
3741 Runtime_ = JSClassCreate(&definition);
3743 definition = kJSClassDefinitionEmpty;
3744 //definition.getProperty = &Global_getProperty;
3745 JSClassRef Global(JSClassCreate(&definition));
3747 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3749 JSObjectRef global(CYGetGlobalObject(context));
3751 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3753 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3754 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3755 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3757 length_ = JSStringCreateWithUTF8CString("length");
3758 message_ = JSStringCreateWithUTF8CString("message");
3759 name_ = JSStringCreateWithUTF8CString("name");
3760 prototype_ = JSStringCreateWithUTF8CString("prototype");
3761 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3762 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3764 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3765 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3767 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3768 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3769 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3770 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3772 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3774 /* Objective-C Classes {{{ */
3776 definition = kJSClassDefinitionEmpty;
3777 definition.className = "Instance";
3778 definition.staticValues = Instance_staticValues;
3779 definition.staticFunctions = Instance_staticFunctions;
3780 definition.hasProperty = &Instance_hasProperty;
3781 definition.getProperty = &Instance_getProperty;
3782 definition.setProperty = &Instance_setProperty;
3783 definition.deleteProperty = &Instance_deleteProperty;
3784 definition.getPropertyNames = &Instance_getPropertyNames;
3785 definition.callAsConstructor = &Instance_callAsConstructor;
3786 definition.hasInstance = &Instance_hasInstance;
3787 definition.finalize = &Finalize;
3788 Instance_ = JSClassCreate(&definition);
3790 definition = kJSClassDefinitionEmpty;
3791 definition.className = "Internal";
3792 definition.staticFunctions = Internal_staticFunctions;
3793 definition.hasProperty = &Internal_hasProperty;
3794 definition.getProperty = &Internal_getProperty;
3795 definition.setProperty = &Internal_setProperty;
3796 definition.getPropertyNames = &Internal_getPropertyNames;
3797 definition.finalize = &Finalize;
3798 Internal_ = JSClassCreate(&definition);
3800 definition = kJSClassDefinitionEmpty;
3801 definition.className = "Message";
3802 definition.staticFunctions = Functor_staticFunctions;
3803 definition.callAsFunction = &Message_callAsFunction;
3804 definition.finalize = &Finalize;
3805 Message_ = JSClassCreate(&definition);
3807 definition = kJSClassDefinitionEmpty;
3808 definition.className = "Messages";
3809 definition.hasProperty = &Messages_hasProperty;
3810 definition.getProperty = &Messages_getProperty;
3811 definition.setProperty = &Messages_setProperty;
3813 definition.deleteProperty = &Messages_deleteProperty;
3815 definition.getPropertyNames = &Messages_getPropertyNames;
3816 definition.finalize = &Finalize;
3817 Messages_ = JSClassCreate(&definition);
3818 definition = kJSClassDefinitionEmpty;
3820 definition.className = "ObjectiveC::Classes";
3821 definition.getProperty = &ObjectiveC_Classes_getProperty;
3822 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3823 ObjectiveC_Classes_ = JSClassCreate(&definition);
3825 definition = kJSClassDefinitionEmpty;
3826 definition.className = "ObjectiveC::Images";
3827 definition.getProperty = &ObjectiveC_Images_getProperty;
3828 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3829 ObjectiveC_Images_ = JSClassCreate(&definition);
3831 definition = kJSClassDefinitionEmpty;
3832 definition.className = "ObjectiveC::Image::Classes";
3833 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3834 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3835 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3837 definition = kJSClassDefinitionEmpty;
3838 definition.className = "ObjectiveC::Protocols";
3839 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3840 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3841 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3843 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3844 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3846 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3847 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3848 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3850 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3851 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3852 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3854 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3855 JSValueProtect(context, Instance_prototype_);
3857 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3858 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3860 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3861 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3865 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3866 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3867 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3868 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3870 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3871 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3872 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
3874 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3878 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3882 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
3883 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
3884 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
3886 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3888 System_ = JSObjectMake(context, NULL, NULL);
3889 CYSetProperty(context, global, CYJSString("system"), System_);
3890 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3891 //CYSetProperty(context, System_, CYJSString("global"), global);
3893 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3895 Result_ = JSStringCreateWithUTF8CString("_");
3897 JSValueProtect(context, Array_);
3898 JSValueProtect(context, Function_);
3899 JSValueProtect(context, String_);
3901 JSValueProtect(context, Object_prototype_);
3903 JSValueProtect(context, Array_prototype_);
3904 JSValueProtect(context, Array_pop_);
3905 JSValueProtect(context, Array_push_);
3906 JSValueProtect(context, Array_splice_);