1 /* Cycript - Remove 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.
42 #include <substrate.h>
43 #include "cycript.hpp"
45 #include "sig/parse.hpp"
46 #include "sig/ffi_type.hpp"
48 #include "Pooling.hpp"
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <CoreFoundation/CFLogUtilities.h>
54 #include <WebKit/WebScriptObject.h>
59 #include <ext/stdio_filebuf.h>
67 #include "Cycript.tab.hh"
69 #include <apr-1/apr_thread_proc.h>
74 #define _assert(test) do { \
76 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
79 #define _trace() do { \
80 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
85 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
87 #define CYPoolCatch(value) \
88 @catch (NSException *error) { \
89 _saved = [error retain]; \
95 [_saved autorelease]; \
99 static JSGlobalContextRef Context_;
100 static JSObjectRef System_;
101 static JSObjectRef ObjectiveC_;
103 static JSClassRef Functor_;
104 static JSClassRef Instance_;
105 static JSClassRef Internal_;
106 static JSClassRef Message_;
107 static JSClassRef Pointer_;
108 static JSClassRef Prototype_;
109 static JSClassRef Runtime_;
110 static JSClassRef Selector_;
111 static JSClassRef Struct_;
112 static JSClassRef Type_;
114 static JSClassRef ObjectiveC_Classes_;
115 static JSClassRef ObjectiveC_Image_Classes_;
116 static JSClassRef ObjectiveC_Images_;
117 static JSClassRef ObjectiveC_Protocols_;
119 static JSObjectRef Array_;
120 static JSObjectRef Function_;
122 static JSStringRef Result_;
124 static JSStringRef length_;
125 static JSStringRef message_;
126 static JSStringRef name_;
127 static JSStringRef prototype_;
128 static JSStringRef toCYON_;
129 static JSStringRef toJSON_;
131 static JSObjectRef Array_prototype_;
132 static JSObjectRef Array_pop_;
133 static JSObjectRef Array_push_;
134 static JSObjectRef Array_splice_;
136 static Class NSArray_;
137 static Class NSCFBoolean_;
138 static Class NSCFType_;
139 static Class NSMessageBuilder_;
140 static Class NSZombie_;
141 static Class Object_;
143 static NSArray *Bridge_;
145 static void Finalize(JSObjectRef object) {
146 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
149 class Type_privateData;
159 CYValue(void *value) :
164 CYValue(const CYValue &rhs) :
169 virtual Type_privateData *GetType() const {
174 struct Selector_privateData :
177 Selector_privateData(SEL value) :
182 SEL GetValue() const {
183 return reinterpret_cast<SEL>(value_);
186 virtual Type_privateData *GetType() const;
194 Transient = (1 << 0),
195 Uninitialized = (1 << 1),
200 Instance(id value, Flags flags) :
206 virtual ~Instance() {
207 if ((flags_ & Transient) == 0)
208 // XXX: does this handle background threads correctly?
209 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
212 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
213 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
215 for (Class _class(object_getClass(object)); _class != nil; _class = class_getSuperclass(_class))
216 if (_class == NSArray_) {
217 JSObjectSetPrototype(context, value, Array_prototype_);
223 id GetValue() const {
224 return reinterpret_cast<id>(value_);
227 bool IsUninitialized() const {
228 return (flags_ & Uninitialized) != 0;
231 virtual Type_privateData *GetType() const;
237 Prototype(Class value) :
242 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
243 JSObjectRef value(JSObjectMake(context, Prototype_, new Prototype(_class)));
244 if (_class == NSArray_)
246 if (Class super = class_getSuperclass(_class))
247 JSObjectSetPrototype(context, value, Prototype::Make(context, super, array));
249 JSObjectSetPrototype(context, value, Array_prototype_);*/
253 Class GetValue() const {
254 return reinterpret_cast<Class>(value_);
263 Internal(id value, JSObjectRef owner) :
269 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
270 return JSObjectMake(context, Internal_, new Internal(object, owner));
273 id GetValue() const {
274 return reinterpret_cast<id>(value_);
280 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
282 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
283 lhs.name = apr_pstrdup(pool, rhs.name);
284 if (rhs.type == NULL)
287 lhs.type = new(pool) Type;
288 Copy(pool, *lhs.type, *rhs.type);
290 lhs.offset = rhs.offset;
293 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
294 size_t count(rhs.count);
296 lhs.elements = new(pool) Element[count];
297 for (size_t index(0); index != count; ++index)
298 Copy(pool, lhs.elements[index], rhs.elements[index]);
301 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
302 lhs.primitive = rhs.primitive;
303 lhs.name = apr_pstrdup(pool, rhs.name);
304 lhs.flags = rhs.flags;
306 if (sig::IsAggregate(rhs.primitive))
307 Copy(pool, lhs.data.signature, rhs.data.signature);
309 if (rhs.data.data.type != NULL) {
310 lhs.data.data.type = new(pool) Type;
311 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
314 lhs.data.data.size = rhs.data.data.size;
318 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
320 lhs.alignment = rhs.alignment;
322 if (rhs.elements == NULL)
326 while (rhs.elements[count] != NULL)
329 lhs.elements = new(pool) ffi_type *[count + 1];
330 lhs.elements[count] = NULL;
332 for (size_t index(0); index != count; ++index) {
333 // XXX: if these are libffi native then you can just take them
334 ffi_type *ffi(new(pool) ffi_type);
335 lhs.elements[index] = ffi;
336 sig::Copy(pool, *ffi, *rhs.elements[index]);
343 struct CStringMapLess :
344 std::binary_function<const char *, const char *, bool>
346 _finline bool operator ()(const char *lhs, const char *rhs) const {
347 return strcmp(lhs, rhs) < 0;
351 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
356 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
357 switch ([[entry objectAtIndex:0] intValue]) {
359 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
363 sig::Signature signature;
364 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
365 type = signature.elements[0].type;
371 struct Type_privateData :
374 static Type_privateData *Object;
375 static Type_privateData *Selector;
380 void Set(sig::Type *type) {
381 type_ = new(pool_) sig::Type;
382 sig::Copy(pool_, *type_, *type);
385 Type_privateData(apr_pool_t *pool, const char *type) :
391 sig::Signature signature;
392 sig::Parse(pool_, &signature, type, &Structor_);
393 type_ = signature.elements[0].type;
396 Type_privateData(sig::Type *type) :
403 Type_privateData(sig::Type *type, ffi_type *ffi) {
404 ffi_ = new(pool_) ffi_type;
405 sig::Copy(pool_, *ffi_, *ffi);
411 ffi_ = new(pool_) ffi_type;
413 sig::Element element;
415 element.type = type_;
418 sig::Signature signature;
419 signature.elements = &element;
423 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
431 Type_privateData *Type_privateData::Object;
432 Type_privateData *Type_privateData::Selector;
434 Type_privateData *Instance::GetType() const {
435 return Type_privateData::Object;
438 Type_privateData *Selector_privateData::GetType() const {
439 return Type_privateData::Selector;
446 Type_privateData *type_;
448 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
451 type_(new(pool_) Type_privateData(type))
456 struct Struct_privateData :
460 Type_privateData *type_;
462 Struct_privateData(JSObjectRef owner) :
468 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
469 static TypeMap Types_;
471 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
472 Struct_privateData *internal(new Struct_privateData(owner));
473 apr_pool_t *pool(internal->pool_);
474 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
475 internal->type_ = typical;
478 internal->value_ = data;
480 size_t size(typical->GetFFI()->size);
481 void *copy(apr_palloc(internal->pool_, size));
482 memcpy(copy, data, size);
483 internal->value_ = copy;
486 return JSObjectMake(context, Struct_, internal);
489 struct Functor_privateData :
492 sig::Signature signature_;
496 Functor_privateData(const char *type, void (*value)()) :
497 CYValue(reinterpret_cast<void *>(value))
499 sig::Parse(pool_, &signature_, type, &Structor_);
500 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
503 void (*GetValue())() const {
504 return reinterpret_cast<void (*)()>(value_);
508 struct Closure_privateData :
511 JSContextRef context_;
512 JSObjectRef function_;
514 Closure_privateData(const char *type) :
515 Functor_privateData(type, NULL)
520 struct Message_privateData :
525 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
526 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
532 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
533 Instance::Flags flags;
536 flags = Instance::Transient;
538 flags = Instance::None;
539 object = [object retain];
542 return Instance::Make(context, object, flags);
545 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
547 return [value UTF8String];
549 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
550 char *string(new(pool) char[size]);
551 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
552 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
557 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
558 return JSValueMakeBoolean(context, value);
561 JSValueRef CYCastJSValue(JSContextRef context, double value) {
562 return JSValueMakeNumber(context, value);
565 #define CYCastJSValue_(Type_) \
566 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
567 return JSValueMakeNumber(context, static_cast<double>(value)); \
571 CYCastJSValue_(unsigned int)
572 CYCastJSValue_(long int)
573 CYCastJSValue_(long unsigned int)
574 CYCastJSValue_(long long int)
575 CYCastJSValue_(long long unsigned int)
577 JSValueRef CYJSUndefined(JSContextRef context) {
578 return JSValueMakeUndefined(context);
581 size_t CYGetIndex(const char *value) {
582 if (value[0] != '0') {
584 size_t index(strtoul(value, &end, 10));
585 if (value + strlen(value) == end)
587 } else if (value[1] == '\0')
592 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
593 return CYGetIndex(CYPoolCString(pool, value));
596 bool CYGetOffset(const char *value, ssize_t &index) {
597 if (value[0] != '0') {
599 index = strtol(value, &end, 10);
600 if (value + strlen(value) == end)
602 } else if (value[1] == '\0') {
610 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
611 return CYGetOffset(CYPoolCString(pool, value), index);
614 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
616 @interface NSMethodSignature (Cycript)
617 - (NSString *) _typeString;
620 @interface NSObject (Cycript)
622 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
623 - (JSType) cy$JSType;
625 - (NSObject *) cy$toJSON:(NSString *)key;
626 - (NSString *) cy$toCYON;
627 - (NSString *) cy$toKey;
629 - (bool) cy$hasProperty:(NSString *)name;
630 - (NSObject *) cy$getProperty:(NSString *)name;
631 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
632 - (bool) cy$deleteProperty:(NSString *)name;
637 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
640 @interface NSString (Cycript)
641 - (void *) cy$symbol;
644 struct PropertyAttributes {
649 const char *variable;
662 PropertyAttributes(objc_property_t property) :
674 name = property_getName(property);
675 const char *attributes(property_getAttributes(property));
677 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
679 case 'R': readonly = true; break;
680 case 'C': copy = true; break;
681 case '&': retain = true; break;
682 case 'N': nonatomic = true; break;
683 case 'G': getter_ = token + 1; break;
684 case 'S': setter_ = token + 1; break;
685 case 'V': variable = token + 1; break;
689 /*if (variable == NULL) {
690 variable = property_getName(property);
691 size_t size(strlen(variable));
692 char *name(new(pool_) char[size + 2]);
694 memcpy(name + 1, variable, size);
695 name[size + 1] = '\0';
700 const char *Getter() {
702 getter_ = apr_pstrdup(pool_, name);
706 const char *Setter() {
707 if (setter_ == NULL && !readonly) {
708 size_t length(strlen(name));
710 char *temp(new(pool_) char[length + 5]);
716 temp[3] = toupper(name[0]);
717 memcpy(temp + 4, name + 1, length - 1);
720 temp[length + 3] = ':';
721 temp[length + 4] = '\0';
730 @implementation NSProxy (Cycript)
732 - (NSObject *) cy$toJSON:(NSString *)key {
733 return [self description];
736 - (NSString *) cy$toCYON {
737 return [[self cy$toJSON:@""] cy$toCYON];
742 @implementation NSObject (Cycript)
744 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
745 return CYMakeInstance(context, self, false);
748 - (JSType) cy$JSType {
749 return kJSTypeObject;
752 - (NSObject *) cy$toJSON:(NSString *)key {
753 return [self description];
756 - (NSString *) cy$toCYON {
757 return [[self cy$toJSON:@""] cy$toCYON];
760 - (NSString *) cy$toKey {
761 return [self cy$toCYON];
764 - (bool) cy$hasProperty:(NSString *)name {
768 - (NSObject *) cy$getProperty:(NSString *)name {
772 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
776 - (bool) cy$deleteProperty:(NSString *)name {
782 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
783 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
786 @implementation WebUndefined (Cycript)
788 - (JSType) cy$JSType {
789 return kJSTypeUndefined;
792 - (NSObject *) cy$toJSON:(NSString *)key {
796 - (NSString *) cy$toCYON {
800 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
801 return CYJSUndefined(context);
806 @implementation NSNull (Cycript)
808 - (JSType) cy$JSType {
812 - (NSObject *) cy$toJSON:(NSString *)key {
816 - (NSString *) cy$toCYON {
822 @implementation NSArray (Cycript)
824 - (NSString *) cy$toCYON {
825 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
826 [json appendString:@"["];
829 for (id object in self) {
831 [json appendString:@","];
834 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
835 [json appendString:CYPoolNSCYON(NULL, object)];
837 [json appendString:@","];
842 [json appendString:@"]"];
846 - (bool) cy$hasProperty:(NSString *)name {
847 if ([name isEqualToString:@"length"])
850 size_t index(CYGetIndex(NULL, name));
851 if (index == _not(size_t) || index >= [self count])
852 return [super cy$hasProperty:name];
857 - (NSObject *) cy$getProperty:(NSString *)name {
858 if ([name isEqualToString:@"length"])
859 return [NSNumber numberWithUnsignedInteger:[self count]];
861 size_t index(CYGetIndex(NULL, name));
862 if (index == _not(size_t) || index >= [self count])
863 return [super cy$getProperty:name];
865 return [self objectAtIndex:index];
870 @implementation NSMutableArray (Cycript)
872 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
873 if ([name isEqualToString:@"length"]) {
874 // XXX: is this not intelligent?
875 NSUInteger size([(NSNumber *)value unsignedIntegerValue]);
876 NSUInteger count([self count]);
878 [self removeObjectsInRange:NSMakeRange(size, count - size)];
879 else if (size != count) {
880 WebUndefined *undefined([WebUndefined undefined]);
881 for (size_t i(count); i != size; ++i)
882 [self addObject:undefined];
887 size_t index(CYGetIndex(NULL, name));
888 if (index == _not(size_t))
889 return [super cy$setProperty:name to:value];
891 id object(value ?: [NSNull null]);
893 size_t count([self count]);
895 [self replaceObjectAtIndex:index withObject:object];
897 if (index != count) {
898 WebUndefined *undefined([WebUndefined undefined]);
899 for (size_t i(count); i != index; ++i)
900 [self addObject:undefined];
903 [self addObject:object];
909 - (bool) cy$deleteProperty:(NSString *)name {
910 size_t index(CYGetIndex(NULL, name));
911 if (index == _not(size_t) || index >= [self count])
912 return [super cy$deleteProperty:name];
913 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
919 @implementation NSDictionary (Cycript)
921 - (NSString *) cy$toCYON {
922 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
923 [json appendString:@"{"];
926 for (id key in self) {
928 [json appendString:@","];
931 [json appendString:[key cy$toKey]];
932 [json appendString:@":"];
933 NSObject *object([self objectForKey:key]);
934 [json appendString:CYPoolNSCYON(NULL, object)];
937 [json appendString:@"}"];
941 - (bool) cy$hasProperty:(NSString *)name {
942 return [self objectForKey:name] != nil;
945 - (NSObject *) cy$getProperty:(NSString *)name {
946 return [self objectForKey:name];
951 @implementation NSMutableDictionary (Cycript)
953 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
954 [self setObject:(value ?: [NSNull null]) forKey:name];
958 - (bool) cy$deleteProperty:(NSString *)name {
959 if ([self objectForKey:name] == nil)
962 [self removeObjectForKey:name];
969 @implementation NSNumber (Cycript)
971 - (JSType) cy$JSType {
972 // XXX: this just seems stupid
973 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
976 - (NSObject *) cy$toJSON:(NSString *)key {
980 - (NSString *) cy$toCYON {
981 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
984 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
985 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
990 @implementation NSString (Cycript)
992 - (JSType) cy$JSType {
993 return kJSTypeString;
996 - (NSObject *) cy$toJSON:(NSString *)key {
1000 - (NSString *) cy$toCYON {
1001 // XXX: this should use the better code from Output.cpp
1002 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
1004 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
1005 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
1006 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
1007 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
1008 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
1010 CFStringInsert(json, 0, CFSTR("\""));
1011 CFStringAppend(json, CFSTR("\""));
1013 return [reinterpret_cast<const NSString *>(json) autorelease];
1016 - (NSString *) cy$toKey {
1017 const char *value([self UTF8String]);
1018 size_t size(strlen(value));
1023 if (DigitRange_[value[0]]) {
1024 size_t index(CYGetIndex(NULL, self));
1025 if (index == _not(size_t))
1028 if (!WordStartRange_[value[0]])
1030 for (size_t i(1); i != size; ++i)
1031 if (!WordEndRange_[value[i]])
1038 return [self cy$toCYON];
1041 - (void *) cy$symbol {
1043 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1048 @interface CYJSObject : NSMutableDictionary {
1049 JSObjectRef object_;
1050 JSContextRef context_;
1053 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1055 - (NSString *) cy$toJSON:(NSString *)key;
1057 - (NSUInteger) count;
1058 - (id) objectForKey:(id)key;
1059 - (NSEnumerator *) keyEnumerator;
1060 - (void) setObject:(id)object forKey:(id)key;
1061 - (void) removeObjectForKey:(id)key;
1065 @interface CYJSArray : NSMutableArray {
1066 JSObjectRef object_;
1067 JSContextRef context_;
1070 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1072 - (NSUInteger) count;
1073 - (id) objectAtIndex:(NSUInteger)index;
1075 - (void) addObject:(id)anObject;
1076 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1077 - (void) removeLastObject;
1078 - (void) removeObjectAtIndex:(NSUInteger)index;
1079 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1083 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1084 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1085 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1090 @catch (id error) { \
1091 CYThrow(context, error, exception); \
1095 void CYThrow(JSContextRef context, JSValueRef value);
1097 apr_status_t CYPoolRelease_(void *data) {
1098 id object(reinterpret_cast<id>(data));
1103 id CYPoolRelease(apr_pool_t *pool, id object) {
1106 else if (pool == NULL)
1107 return [object autorelease];
1109 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1114 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1115 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1118 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1119 JSValueRef exception(NULL);
1120 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1121 CYThrow(context, exception);
1122 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1123 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1126 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1127 if (!JSValueIsObjectOfClass(context, object, Instance_))
1128 return CYCastNSObject_(pool, context, object);
1130 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1131 return internal->GetValue();
1135 JSStringRef CYCopyJSString(id value) {
1136 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
1139 JSStringRef CYCopyJSString(const char *value) {
1140 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
1143 JSStringRef CYCopyJSString(JSStringRef value) {
1144 return value == NULL ? NULL : JSStringRetain(value);
1147 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
1148 if (JSValueIsNull(context, value))
1150 JSValueRef exception(NULL);
1151 JSStringRef string(JSValueToStringCopy(context, value, &exception));
1152 CYThrow(context, exception);
1158 JSStringRef string_;
1161 if (string_ != NULL)
1162 JSStringRelease(string_);
1166 CYJSString(const CYJSString &rhs) :
1167 string_(CYCopyJSString(rhs.string_))
1171 template <typename Arg0_>
1172 CYJSString(Arg0_ arg0) :
1173 string_(CYCopyJSString(arg0))
1177 template <typename Arg0_, typename Arg1_>
1178 CYJSString(Arg0_ arg0, Arg1_ arg1) :
1179 string_(CYCopyJSString(arg0, arg1))
1183 CYJSString &operator =(const CYJSString &rhs) {
1185 string_ = CYCopyJSString(rhs.string_);
1198 operator JSStringRef() const {
1203 CFStringRef CYCopyCFString(JSStringRef value) {
1204 return JSStringCopyCFString(kCFAllocatorDefault, value);
1207 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1208 return CYCopyCFString(CYJSString(context, value));
1211 double CYCastDouble(const char *value, size_t size) {
1213 double number(strtod(value, &end));
1214 if (end != value + size)
1219 double CYCastDouble(const char *value) {
1220 return CYCastDouble(value, strlen(value));
1223 double CYCastDouble(JSContextRef context, JSValueRef value) {
1224 JSValueRef exception(NULL);
1225 double number(JSValueToNumber(context, value, &exception));
1226 CYThrow(context, exception);
1230 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1231 double number(CYCastDouble(context, value));
1232 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1235 CFStringRef CYCopyCFString(const char *value) {
1236 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1239 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1240 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1243 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1244 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1247 bool CYCastBool(JSContextRef context, JSValueRef value) {
1248 return JSValueToBoolean(context, value);
1251 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1255 switch (JSType type = JSValueGetType(context, value)) {
1256 case kJSTypeUndefined:
1257 object = [WebUndefined undefined];
1265 case kJSTypeBoolean:
1266 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1271 object = CYCopyCFNumber(context, value);
1276 object = CYCopyCFString(context, value);
1281 // XXX: this might could be more efficient
1282 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1287 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1294 return CYPoolRelease(pool, object);
1296 return CFRetain(object);
1299 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1300 return CYCFType(pool, context, value, true);
1303 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1304 return CYCFType(pool, context, value, false);
1307 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1309 size_t size(JSPropertyNameArrayGetCount(names));
1310 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1311 for (size_t index(0); index != size; ++index)
1312 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1316 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1317 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1320 void CYThrow(JSContextRef context, JSValueRef value) {
1323 @throw CYCastNSObject(NULL, context, value);
1326 JSValueRef CYJSNull(JSContextRef context) {
1327 return JSValueMakeNull(context);
1330 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1331 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1334 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1335 return CYCastJSValue(context, CYJSString(value));
1338 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1340 return CYJSNull(context);
1341 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1342 return [value cy$JSValueInContext:context];
1344 return CYMakeInstance(context, value, false);
1347 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1348 JSValueRef exception(NULL);
1349 JSObjectRef object(JSValueToObject(context, value, &exception));
1350 CYThrow(context, exception);
1354 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1355 JSValueRef exception(NULL);
1356 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1357 CYThrow(context, exception);
1361 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1362 JSValueRef exception(NULL);
1363 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1364 CYThrow(context, exception);
1368 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
1369 JSValueRef exception(NULL);
1370 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
1371 CYThrow(context, exception);
1374 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1375 JSValueRef exception(NULL);
1376 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1377 CYThrow(context, exception);
1380 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1381 if (exception == NULL)
1383 *exception = CYCastJSValue(context, error);
1386 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1387 JSValueRef exception(NULL);
1388 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1389 CYThrow(context, exception);
1393 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1394 // XXX: this isn't actually correct
1395 return value != NULL && JSValueIsObject(context, value);
1398 @implementation CYJSObject
1400 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1401 if ((self = [super init]) != nil) {
1407 - (NSObject *) cy$toJSON:(NSString *)key {
1408 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1409 if (!CYIsCallable(context_, toJSON))
1410 return [super cy$toJSON:key];
1412 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1413 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1414 // XXX: do I really want an NSNull here?!
1415 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1419 - (NSString *) cy$toCYON {
1420 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1421 if (!CYIsCallable(context_, toCYON))
1422 return [super cy$toCYON];
1424 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1425 return CYCastNSString(NULL, CYJSString(context_, value));
1429 - (NSUInteger) count {
1430 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1431 size_t size(JSPropertyNameArrayGetCount(names));
1432 JSPropertyNameArrayRelease(names);
1436 - (id) objectForKey:(id)key {
1437 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1440 - (NSEnumerator *) keyEnumerator {
1441 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1442 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1443 JSPropertyNameArrayRelease(names);
1447 - (void) setObject:(id)object forKey:(id)key {
1448 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1451 - (void) removeObjectForKey:(id)key {
1452 JSValueRef exception(NULL);
1453 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1454 CYThrow(context_, exception);
1459 @implementation CYJSArray
1461 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1462 if ((self = [super init]) != nil) {
1468 - (NSUInteger) count {
1469 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1472 - (id) objectAtIndex:(NSUInteger)index {
1473 if (index >= CYCastDouble(context_, CYGetProperty(context_, object_, length_)))
1475 JSValueRef exception(NULL);
1476 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1477 CYThrow(context_, exception);
1478 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1481 - (void) addObject:(id)object {
1482 JSValueRef exception(NULL);
1483 JSValueRef arguments[1];
1484 arguments[0] = CYCastJSValue(context_, object);
1485 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1486 CYThrow(context_, exception);
1489 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1490 JSValueRef exception(NULL);
1491 JSValueRef arguments[3];
1492 arguments[0] = CYCastJSValue(context_, index);
1493 arguments[1] = CYCastJSValue(context_, 0);
1494 arguments[2] = CYCastJSValue(context_, object);
1495 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1496 CYThrow(context_, exception);
1499 - (void) removeLastObject {
1500 JSValueRef exception(NULL);
1501 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1502 CYThrow(context_, exception);
1505 - (void) removeObjectAtIndex:(NSUInteger)index {
1506 JSValueRef exception(NULL);
1507 JSValueRef arguments[2];
1508 arguments[0] = CYCastJSValue(context_, index);
1509 arguments[1] = CYCastJSValue(context_, 1);
1510 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1511 CYThrow(context_, exception);
1514 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1515 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1520 NSString *CYCopyNSCYON(id value) {
1526 Class _class(object_getClass(value));
1527 SEL sel(@selector(cy$toCYON));
1529 if (Method toCYON = class_getInstanceMethod(_class, sel))
1530 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1531 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1532 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1533 string = [value cy$toCYON];
1536 if (value == NSZombie_)
1537 string = @"_NSZombie_";
1538 else if (_class == NSZombie_)
1539 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1540 // XXX: frowny /in/ the pants
1541 else if (value == NSMessageBuilder_ || value == Object_)
1544 string = [NSString stringWithFormat:@"%@", value];
1547 // XXX: frowny pants
1549 string = @"undefined";
1552 return [string retain];
1555 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1556 if (JSValueIsNull(context, value))
1557 return [@"null" retain];
1561 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1566 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1567 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1570 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1571 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1572 const char *string(CYPoolCString(pool, json));
1578 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1582 JSObjectRef object_;
1590 // XXX: delete object_? ;(
1593 static CYInternal *Get(id self) {
1594 CYInternal *internal(NULL);
1595 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1596 // XXX: do something epic? ;P
1602 static CYInternal *Set(id self) {
1603 CYInternal *internal(NULL);
1604 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1605 if (internal == NULL) {
1606 internal = new CYInternal();
1607 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1610 // XXX: do something epic? ;P
1616 bool HasProperty(JSContextRef context, JSStringRef name) {
1617 if (object_ == NULL)
1619 return JSObjectHasProperty(context, object_, name);
1622 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1623 if (object_ == NULL)
1625 return CYGetProperty(context, object_, name);
1628 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1629 if (object_ == NULL)
1630 object_ = JSObjectMake(context, NULL, NULL);
1631 CYSetProperty(context, object_, name, value);
1635 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1636 Selector_privateData *internal(new Selector_privateData(sel));
1637 return JSObjectMake(context, Selector_, internal);
1640 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1641 Pointer *internal(new Pointer(pointer, type, owner));
1642 return JSObjectMake(context, Pointer_, internal);
1645 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1646 Functor_privateData *internal(new Functor_privateData(type, function));
1647 return JSObjectMake(context, Functor_, internal);
1650 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1652 const char *string([CYCastNSString(NULL, value) UTF8String]);
1655 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1656 char *string(new(pool) char[size]);
1657 JSStringGetUTF8CString(value, string, size);
1662 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1663 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1666 bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1667 return CYGetOffset(CYPoolCString(pool, value), index);
1670 // XXX: this macro is unhygenic
1671 #define CYCastCString(context, value) ({ \
1673 if (value == NULL) \
1675 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1676 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1677 utf8 = reinterpret_cast<char *>(alloca(size)); \
1678 JSStringGetUTF8CString(string, utf8, size); \
1679 JSStringRelease(string); \
1685 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1686 switch (JSValueGetType(context, value)) {
1689 /*case kJSTypeString:
1690 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1692 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1693 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1694 return internal->value_;
1697 double number(CYCastDouble(context, value));
1698 if (std::isnan(number))
1699 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1700 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1704 template <typename Type_>
1705 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1706 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1709 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1710 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1711 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1712 return reinterpret_cast<SEL>(internal->value_);
1714 return CYCastPointer<SEL>(context, value);
1717 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1718 switch (type->primitive) {
1719 case sig::boolean_P:
1720 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1723 #define CYPoolFFI_(primitive, native) \
1724 case sig::primitive ## _P: \
1725 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1728 CYPoolFFI_(uchar, unsigned char)
1729 CYPoolFFI_(char, char)
1730 CYPoolFFI_(ushort, unsigned short)
1731 CYPoolFFI_(short, short)
1732 CYPoolFFI_(ulong, unsigned long)
1733 CYPoolFFI_(long, long)
1734 CYPoolFFI_(uint, unsigned int)
1735 CYPoolFFI_(int, int)
1736 CYPoolFFI_(ulonglong, unsigned long long)
1737 CYPoolFFI_(longlong, long long)
1738 CYPoolFFI_(float, float)
1739 CYPoolFFI_(double, double)
1742 case sig::typename_P:
1743 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1746 case sig::selector_P:
1747 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1750 case sig::pointer_P:
1751 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1755 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1758 case sig::struct_P: {
1759 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1760 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1761 for (size_t index(0); index != type->data.signature.count; ++index) {
1762 sig::Element *element(&type->data.signature.elements[index]);
1763 ffi_type *field(ffi->elements[index]);
1766 if (aggregate == NULL)
1769 rhs = CYGetProperty(context, aggregate, index);
1770 if (JSValueIsUndefined(context, rhs)) {
1771 if (element->name != NULL)
1772 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1775 if (JSValueIsUndefined(context, rhs)) undefined:
1776 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1780 CYPoolFFI(pool, context, element->type, field, base, rhs);
1782 base += field->size;
1790 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1795 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1798 switch (type->primitive) {
1799 case sig::boolean_P:
1800 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1803 #define CYFromFFI_(primitive, native) \
1804 case sig::primitive ## _P: \
1805 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1808 CYFromFFI_(uchar, unsigned char)
1809 CYFromFFI_(char, char)
1810 CYFromFFI_(ushort, unsigned short)
1811 CYFromFFI_(short, short)
1812 CYFromFFI_(ulong, unsigned long)
1813 CYFromFFI_(long, long)
1814 CYFromFFI_(uint, unsigned int)
1815 CYFromFFI_(int, int)
1816 CYFromFFI_(ulonglong, unsigned long long)
1817 CYFromFFI_(longlong, long long)
1818 CYFromFFI_(float, float)
1819 CYFromFFI_(double, double)
1821 case sig::object_P: {
1822 if (id object = *reinterpret_cast<id *>(data)) {
1823 value = CYCastJSValue(context, object);
1829 case sig::typename_P:
1830 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1833 case sig::selector_P:
1834 if (SEL sel = *reinterpret_cast<SEL *>(data))
1835 value = CYMakeSelector(context, sel);
1839 case sig::pointer_P:
1840 if (void *pointer = *reinterpret_cast<void **>(data))
1841 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1846 if (char *utf8 = *reinterpret_cast<char **>(data))
1847 value = CYCastJSValue(context, utf8);
1852 value = CYMakeStruct(context, data, type, ffi, owner);
1856 value = CYJSUndefined(context);
1860 value = CYJSNull(context);
1864 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1871 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1872 if (Method method = class_getInstanceMethod(_class, selector)) {
1876 method_getReturnType(method, type, sizeof(type));
1881 // XXX: possibly use a more "awesome" check?
1885 const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
1887 return method_getTypeEncoding(method);
1888 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1889 return CYPoolCString(pool, type);
1894 void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1895 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1897 JSContextRef context(internal->context_);
1899 size_t count(internal->cif_.nargs);
1900 JSValueRef values[count];
1902 for (size_t index(0); index != count; ++index)
1903 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1905 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
1906 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1909 void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1910 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1912 JSContextRef context(internal->context_);
1914 size_t count(internal->cif_.nargs);
1915 JSValueRef values[count];
1917 for (size_t index(0); index != count; ++index)
1918 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1920 JSObjectRef _this(CYCastJSObject(context, values[0]));
1922 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1923 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1926 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
1927 // XXX: in case of exceptions this will leak
1928 // XXX: in point of fact, this may /need/ to leak :(
1929 Closure_privateData *internal(new Closure_privateData(type));
1931 ffi_closure *closure((ffi_closure *) _syscall(mmap(
1932 NULL, sizeof(ffi_closure),
1933 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1937 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
1938 _assert(status == FFI_OK);
1940 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1942 internal->value_ = closure;
1944 internal->context_ = CYGetJSContext();
1945 internal->function_ = function;
1950 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1951 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
1952 return JSObjectMake(context, Functor_, internal);
1955 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
1956 JSValueRef exception(NULL);
1957 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
1958 CYThrow(context, exception);
1961 JSObjectRef function(CYCastJSObject(context, value));
1962 return CYMakeFunctor(context, function, type);
1964 void (*function)()(CYCastPointer<void (*)()>(context, value));
1965 return CYMakeFunctor(context, function, type);
1969 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1970 Message_privateData *internal(new Message_privateData(sel, type, imp));
1971 return JSObjectMake(context, Message_, internal);
1974 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1975 JSObjectRef function(CYCastJSObject(context, value));
1976 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1977 return reinterpret_cast<IMP>(internal->GetValue());
1980 static bool Prototype_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1981 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1982 Class _class(internal->GetValue());
1985 const char *name(CYPoolCString(pool, property));
1987 if (SEL sel = sel_getUid(name))
1988 if (class_getInstanceMethod(_class, sel) != NULL)
1994 static JSValueRef Prototype_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1995 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1996 Class _class(internal->GetValue());
1999 const char *name(CYPoolCString(pool, property));
2001 if (SEL sel = sel_getUid(name))
2002 if (Method method = class_getInstanceMethod(_class, sel))
2003 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2008 static bool Prototype_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2009 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
2010 Class _class(internal->GetValue());
2013 const char *name(CYPoolCString(pool, property));
2015 SEL sel(sel_registerName(name));
2017 Method method(class_getInstanceMethod(_class, sel));
2022 if (JSValueIsObjectOfClass(context, value, Message_)) {
2023 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2024 type = sig::Unparse(pool, &message->signature_);
2025 imp = reinterpret_cast<IMP>(message->GetValue());
2027 type = CYPoolTypeEncoding(pool, _class, sel, method);
2028 imp = CYMakeMessage(context, value, type);
2032 method_setImplementation(method, imp);
2034 class_replaceMethod(_class, sel, imp, type);
2040 static bool Prototype_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2041 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
2042 Class _class(internal->GetValue());
2045 const char *name(CYPoolCString(pool, property));
2047 if (SEL sel = sel_getUid(name))
2048 if (Method method = class_getInstanceMethod(_class, sel)) {
2049 objc_method_list list = {NULL, 1, {method}};
2050 class_removeMethods(_class, &list);
2058 static void Prototype_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2059 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
2060 Class _class(internal->GetValue());
2063 Method *data(class_copyMethodList(_class, &size));
2064 for (size_t i(0); i != size; ++i)
2065 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2069 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2070 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2071 id self(internal->GetValue());
2073 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2077 NSString *name(CYCastNSString(pool, property));
2079 if (CYInternal *internal = CYInternal::Get(self))
2080 if (internal->HasProperty(context, property))
2084 if ([self cy$hasProperty:name])
2086 } CYPoolCatch(false)
2088 const char *string(CYPoolCString(pool, name));
2089 Class _class(object_getClass(self));
2091 if (class_getProperty(_class, string) != NULL)
2094 if (SEL sel = sel_getUid(string))
2095 if (CYImplements(self, _class, sel, true))
2101 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2102 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2103 id self(internal->GetValue());
2105 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2106 return Internal::Make(context, self, object);
2110 NSString *name(CYCastNSString(pool, property));
2112 if (CYInternal *internal = CYInternal::Get(self))
2113 if (JSValueRef value = internal->GetProperty(context, property))
2117 if (NSObject *data = [self cy$getProperty:name])
2118 return CYCastJSValue(context, data);
2121 const char *string(CYPoolCString(pool, name));
2122 Class _class(object_getClass(self));
2124 if (objc_property_t property = class_getProperty(_class, string)) {
2125 PropertyAttributes attributes(property);
2126 SEL sel(sel_registerName(attributes.Getter()));
2127 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2130 if (SEL sel = sel_getUid(string))
2131 if (CYImplements(self, _class, sel, true))
2132 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2138 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2139 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2140 id self(internal->GetValue());
2145 NSString *name(CYCastNSString(pool, property));
2146 NSString *data(CYCastNSObject(pool, context, value));
2149 if ([self cy$setProperty:name to:data])
2153 const char *string(CYPoolCString(pool, name));
2154 Class _class(object_getClass(self));
2156 if (objc_property_t property = class_getProperty(_class, string)) {
2157 PropertyAttributes attributes(property);
2158 if (const char *setter = attributes.Setter()) {
2159 SEL sel(sel_registerName(setter));
2160 JSValueRef arguments[1] = {value};
2161 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2166 size_t length(strlen(string));
2168 char set[length + 5];
2174 if (string[0] != '\0') {
2175 set[3] = toupper(string[0]);
2176 memcpy(set + 4, string + 1, length - 1);
2179 set[length + 3] = ':';
2180 set[length + 4] = '\0';
2182 if (SEL sel = sel_getUid(set))
2183 if (CYImplements(self, _class, sel, false)) {
2184 JSValueRef arguments[1] = {value};
2185 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2188 if (CYInternal *internal = CYInternal::Set(self)) {
2189 internal->SetProperty(context, property, value);
2197 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2198 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2199 id self(internal->GetValue());
2203 NSString *name(CYCastNSString(NULL, property));
2204 return [self cy$deleteProperty:name];
2209 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2210 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2211 id self(internal->GetValue());
2214 Class _class(object_getClass(self));
2218 objc_property_t *data(class_copyPropertyList(_class, &size));
2219 for (size_t i(0); i != size; ++i)
2220 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2225 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2227 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2228 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2233 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2234 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2237 id self(internal->GetValue());
2238 const char *name(CYPoolCString(pool, property));
2240 if (object_getInstanceVariable(self, name, NULL) != NULL)
2246 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2247 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2251 id self(internal->GetValue());
2252 const char *name(CYPoolCString(pool, property));
2254 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2255 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2256 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2263 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2264 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2268 id self(internal->GetValue());
2269 const char *name(CYPoolCString(pool, property));
2271 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2272 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2273 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2281 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2282 if (Class super = class_getSuperclass(_class))
2283 Internal_getPropertyNames_(super, names);
2286 Ivar *data(class_copyIvarList(_class, &size));
2287 for (size_t i(0); i != size; ++i)
2288 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2292 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2293 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2296 id self(internal->GetValue());
2297 Class _class(object_getClass(self));
2299 Internal_getPropertyNames_(_class, names);
2302 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2303 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2304 return internal->owner_;
2307 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2308 Type_privateData *typical(internal->type_);
2309 sig::Type *type(typical->type_);
2313 const char *name(CYPoolCString(pool, property));
2314 size_t length(strlen(name));
2315 double number(CYCastDouble(name, length));
2317 size_t count(type->data.signature.count);
2319 if (std::isnan(number)) {
2320 if (property == NULL)
2323 sig::Element *elements(type->data.signature.elements);
2325 for (size_t local(0); local != count; ++local) {
2326 sig::Element *element(&elements[local]);
2327 if (element->name != NULL && strcmp(name, element->name) == 0) {
2335 index = static_cast<ssize_t>(number);
2336 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2341 ffi_type **elements(typical->GetFFI()->elements);
2343 base = reinterpret_cast<uint8_t *>(internal->value_);
2344 for (ssize_t local(0); local != index; ++local)
2345 base += elements[local]->size;
2350 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2351 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2352 Type_privateData *typical(internal->type_);
2354 ffi_type *ffi(typical->GetFFI());
2356 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2357 base += ffi->size * index;
2359 JSObjectRef owner(internal->owner_ ?: object);
2362 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2366 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2368 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2369 Type_privateData *typical(internal->type_);
2371 if (typical->type_ == NULL)
2375 if (!CYGetOffset(pool, property, offset))
2378 return Pointer_getIndex(context, object, offset, exception);
2381 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2382 return Pointer_getIndex(context, object, 0, exception);
2385 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2386 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2387 Type_privateData *typical(internal->type_);
2389 ffi_type *ffi(typical->GetFFI());
2391 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2392 base += ffi->size * index;
2395 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2400 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2402 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2403 Type_privateData *typical(internal->type_);
2405 if (typical->type_ == NULL)
2409 if (!CYGetOffset(pool, property, offset))
2412 return Pointer_setIndex(context, object, offset, value, exception);
2415 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2416 return Pointer_setIndex(context, object, 0, value, exception);
2419 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2420 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2421 Type_privateData *typical(internal->type_);
2422 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2425 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2427 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2428 Type_privateData *typical(internal->type_);
2433 if (!Index_(pool, internal, property, index, base))
2436 JSObjectRef owner(internal->owner_ ?: object);
2439 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2443 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2445 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2446 Type_privateData *typical(internal->type_);
2451 if (!Index_(pool, internal, property, index, base))
2455 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2460 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2461 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2462 Type_privateData *typical(internal->type_);
2463 sig::Type *type(typical->type_);
2468 size_t count(type->data.signature.count);
2469 sig::Element *elements(type->data.signature.elements);
2473 for (size_t index(0); index != count; ++index) {
2475 name = elements[index].name;
2478 sprintf(number, "%lu", index);
2482 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2486 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)()) {
2488 if (setups + count != signature->count - 1)
2489 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2491 size_t size(setups + count);
2493 memcpy(values, setup, sizeof(void *) * setups);
2495 for (size_t index(setups); index != size; ++index) {
2496 sig::Element *element(&signature->elements[index + 1]);
2497 ffi_type *ffi(cif->arg_types[index]);
2499 values[index] = new(pool) uint8_t[ffi->size];
2500 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2503 uint8_t value[cif->rtype->size];
2504 ffi_call(cif, function, value, values);
2506 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2510 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2513 NSString *name(CYCastNSString(pool, property));
2514 if (Class _class = NSClassFromString(name))
2515 return CYMakeInstance(context, _class, true);
2520 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2521 size_t size(objc_getClassList(NULL, 0));
2522 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2525 size_t writ(objc_getClassList(data, size));
2528 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2534 for (size_t i(0); i != writ; ++i)
2535 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2541 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2542 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2546 const char *name(CYPoolCString(pool, property));
2548 const char **data(objc_copyClassNamesForImage(internal, &size));
2550 for (size_t i(0); i != size; ++i)
2551 if (strcmp(name, data[i]) == 0) {
2552 if (Class _class = objc_getClass(name)) {
2553 value = CYMakeInstance(context, _class, true);
2565 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2566 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2568 const char **data(objc_copyClassNamesForImage(internal, &size));
2569 for (size_t i(0); i != size; ++i)
2570 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2574 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2577 const char *name(CYPoolCString(pool, property));
2579 const char **data(objc_copyImageNames(&size));
2580 for (size_t i(0); i != size; ++i)
2581 if (strcmp(name, data[i]) == 0) {
2590 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2591 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2596 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2598 const char **data(objc_copyImageNames(&size));
2599 for (size_t i(0); i != size; ++i)
2600 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2604 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2607 NSString *name(CYCastNSString(pool, property));
2608 if (Protocol *protocol = NSProtocolFromString(name))
2609 return CYMakeInstance(context, protocol, true);
2614 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2616 Protocol **data(objc_copyProtocolList(&size));
2617 for (size_t i(0); i != size; ++i)
2618 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2622 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2623 if (JSStringIsEqualToUTF8CString(property, "nil"))
2624 return Instance::Make(context, nil);
2628 NSString *name(CYCastNSString(pool, property));
2629 if (Class _class = NSClassFromString(name))
2630 return CYMakeInstance(context, _class, true);
2631 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2632 switch ([[entry objectAtIndex:0] intValue]) {
2634 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2636 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2638 // XXX: this is horrendously inefficient
2639 sig::Signature signature;
2640 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2642 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2643 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2649 bool stret(ffi_type *ffi_type) {
2650 return ffi_type->type == FFI_TYPE_STRUCT && (
2651 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2652 struct_forward_array[ffi_type->size] != 0
2657 int *_NSGetArgc(void);
2658 char ***_NSGetArgv(void);
2659 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2662 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2664 NSLog(@"%s", CYCastCString(context, arguments[0]));
2665 return CYJSUndefined(context);
2669 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2672 Class _class(object_getClass(self));
2673 if (Method method = class_getInstanceMethod(_class, _cmd))
2674 type = method_getTypeEncoding(method);
2678 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2680 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2681 type = CYPoolCString(pool, [method _typeString]);
2690 sig::Signature signature;
2691 sig::Parse(pool, &signature, type, &Structor_);
2694 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2696 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2697 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2700 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2710 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2712 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2713 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2714 self = internal->GetValue();
2715 uninitialized = internal->IsUninitialized();
2717 internal->value_ = nil;
2719 self = CYCastNSObject(pool, context, arguments[0]);
2720 uninitialized = false;
2724 return CYJSNull(context);
2726 _cmd = CYCastSEL(context, arguments[1]);
2729 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2732 MSHook(void, CYDealloc, id self, SEL sel) {
2733 CYInternal *internal;
2734 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2735 if (internal != NULL)
2737 _CYDealloc(self, sel);
2740 MSHook(void, objc_registerClassPair, Class _class) {
2741 Class super(class_getSuperclass(_class));
2742 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2743 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2744 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2747 _objc_registerClassPair(_class);
2750 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2753 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2755 Class _class(CYCastNSObject(pool, context, arguments[0]));
2756 $objc_registerClassPair(_class);
2757 return CYJSUndefined(context);
2761 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2762 JSValueRef setup[count + 2];
2765 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2766 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2769 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2771 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2773 // XXX: handle Instance::Uninitialized?
2774 id self(CYCastNSObject(pool, context, _this));
2778 setup[1] = &internal->sel_;
2780 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2783 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2785 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2786 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2789 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2792 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2793 const char *name(CYCastCString(context, arguments[0]));
2794 return CYMakeSelector(context, sel_registerName(name));
2798 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2801 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2803 void *value(CYCastPointer<void *>(context, arguments[0]));
2804 const char *type(CYCastCString(context, arguments[1]));
2808 sig::Signature signature;
2809 sig::Parse(pool, &signature, type, &Structor_);
2811 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2815 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2816 Type_privateData *internal(new Type_privateData(NULL, type));
2817 return JSObjectMake(context, Type_, internal);
2820 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2823 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2824 const char *type(CYCastCString(context, arguments[0]));
2825 return CYMakeType(context, object, type);
2829 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2832 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2833 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2834 sig::Type *type(internal->type_);
2835 ffi_type *ffi(internal->GetFFI());
2837 uint8_t value[ffi->size];
2839 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2840 return CYFromFFI(context, type, ffi, value);
2844 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2847 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2848 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2849 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2851 void *value(malloc(internal->GetFFI()->size * size));
2852 return CYMakePointer(context, value, internal->type_, internal->ffi_, NULL);
2856 JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2859 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
2860 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2861 return Instance::Make(context, self);
2865 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2868 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2869 const char *type(CYCastCString(context, arguments[1]));
2870 return CYMakeFunctor(context, arguments[0], type);
2874 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2875 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2876 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2879 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2880 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2881 Type_privateData *typical(internal->GetType());
2886 if (typical == NULL) {
2890 type = typical->type_;
2891 ffi = typical->ffi_;
2894 return CYMakePointer(context, &internal->value_, type, ffi, object);
2897 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2898 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2901 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2905 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2906 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2909 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2910 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2912 sprintf(string, "%p", internal->value_);
2915 return CYCastJSValue(context, string);
2919 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2920 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2921 return Instance::Make(context, object_getClass(internal->GetValue()));
2924 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2925 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2926 id self(internal->GetValue());
2927 // XXX: this is a lame object_isClass
2928 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
2929 return CYJSUndefined(context);
2930 return Prototype::Make(context, self);
2933 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2934 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2938 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
2943 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2944 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2948 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2949 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
2954 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2955 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2959 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
2964 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2965 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2968 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2972 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2973 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2976 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2977 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2978 const char *name(sel_getName(internal->GetValue()));
2982 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2987 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2990 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2992 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2993 Class _class(CYCastNSObject(pool, context, arguments[0]));
2994 SEL sel(internal->GetValue());
2995 Method method(class_getInstanceMethod(_class, sel));
2996 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
2997 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3001 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3003 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3005 const char *type(sig::Unparse(pool, internal->type_));
3007 return CYCastJSValue(context, CYJSString(type));
3012 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3014 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3016 const char *type(sig::Unparse(pool, internal->type_));
3018 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
3023 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3024 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3027 static JSStaticValue CYValue_staticValues[2] = {
3028 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3029 {NULL, NULL, NULL, 0}
3032 static JSStaticValue Pointer_staticValues[2] = {
3033 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3034 {NULL, NULL, NULL, 0}
3037 static JSStaticFunction Pointer_staticFunctions[4] = {
3038 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3039 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3040 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3044 static JSStaticFunction Struct_staticFunctions[2] = {
3045 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3049 static JSStaticFunction Functor_staticFunctions[4] = {
3050 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3051 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3052 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3056 static JSStaticValue Instance_staticValues[4] = {
3057 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3058 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3059 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3060 {NULL, NULL, NULL, 0}
3063 static JSStaticFunction Instance_staticFunctions[5] = {
3064 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3065 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3066 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3067 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3071 static JSStaticFunction Internal_staticFunctions[2] = {
3072 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3076 static JSStaticFunction Selector_staticFunctions[5] = {
3077 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3078 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3079 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3080 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3084 static JSStaticFunction Type_staticFunctions[4] = {
3085 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3086 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3087 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3091 CYDriver::CYDriver(const std::string &filename) :
3096 filename_(filename),
3102 CYDriver::~CYDriver() {
3106 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
3107 CYDriver::Error error;
3108 error.location_ = location;
3109 error.message_ = message;
3110 driver.errors_.push_back(error);
3113 void CYSetArgs(int argc, const char *argv[]) {
3114 JSContextRef context(CYGetJSContext());
3115 JSValueRef args[argc];
3116 for (int i(0); i != argc; ++i)
3117 args[i] = CYCastJSValue(context, argv[i]);
3118 JSValueRef exception(NULL);
3119 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3120 CYThrow(context, exception);
3121 CYSetProperty(context, System_, CYJSString("args"), array);
3124 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3125 return JSContextGetGlobalObject(context);
3128 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3129 JSContextRef context(CYGetJSContext());
3130 JSValueRef exception(NULL), result;
3133 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3134 } catch (const char *error) {
3138 if (exception != NULL) { error:
3143 if (JSValueIsUndefined(context, result))
3146 const char *json(CYPoolCCYON(pool, context, result, &exception));
3147 if (exception != NULL)
3150 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3154 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
3155 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
3163 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
3164 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
3176 const char * volatile data_;
3179 // XXX: this is "tre lame"
3180 @interface CYClient_ : NSObject {
3183 - (void) execute:(NSValue *)value;
3187 @implementation CYClient_
3189 - (void) execute:(NSValue *)value {
3190 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3191 const char *data(execute->data_);
3192 execute->data_ = NULL;
3193 execute->data_ = CYExecute(execute->pool_, data);
3202 apr_thread_t *thread_;
3204 CYClient(int socket) :
3210 _syscall(close(socket_));
3213 void Handle() { _pooled
3214 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3218 if (!CYRecvAll(socket_, &size, sizeof(size)))
3222 char *data(new(pool) char[size + 1]);
3223 if (!CYRecvAll(socket_, data, size))
3227 CYDriver driver("");
3228 cy::parser parser(driver);
3230 driver.data_ = data;
3231 driver.size_ = size;
3234 if (parser.parse() != 0 || !driver.errors_.empty()) {
3236 size = _not(size_t);
3238 std::ostringstream str;
3239 driver.source_->Show(str);
3240 std::string code(str.str());
3241 CYExecute_ execute = {pool, code.c_str()};
3242 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3243 json = execute.data_;
3244 size = json == NULL ? _not(size_t) : strlen(json);
3247 if (!CYSendAll(socket_, &size, sizeof(size)))
3250 if (!CYSendAll(socket_, json, size))
3256 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3257 CYClient *client(reinterpret_cast<CYClient *>(data));
3263 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3264 CYClient *client(new(pool) CYClient(socket));
3265 apr_threadattr_t *attr;
3266 _aprcall(apr_threadattr_create(&attr, client->pool_));
3267 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3270 MSInitialize { _pooled
3271 _aprcall(apr_initialize());
3272 _aprcall(apr_pool_create(&Pool_, NULL));
3274 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3275 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3277 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3279 NSArray_ = objc_getClass("NSArray");
3280 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3281 NSCFType_ = objc_getClass("NSCFType");
3282 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3283 NSZombie_ = objc_getClass("_NSZombie_");
3284 Object_ = objc_getClass("Object");
3287 JSGlobalContextRef CYGetJSContext() {
3288 if (Context_ == NULL) {
3289 JSClassDefinition definition;
3291 definition = kJSClassDefinitionEmpty;
3292 definition.className = "Functor";
3293 definition.staticFunctions = Functor_staticFunctions;
3294 definition.callAsFunction = &Functor_callAsFunction;
3295 definition.finalize = &Finalize;
3296 Functor_ = JSClassCreate(&definition);
3298 definition = kJSClassDefinitionEmpty;
3299 definition.className = "Instance";
3300 definition.staticValues = Instance_staticValues;
3301 definition.staticFunctions = Instance_staticFunctions;
3302 definition.hasProperty = &Instance_hasProperty;
3303 definition.getProperty = &Instance_getProperty;
3304 definition.setProperty = &Instance_setProperty;
3305 definition.deleteProperty = &Instance_deleteProperty;
3306 definition.getPropertyNames = &Instance_getPropertyNames;
3307 definition.callAsConstructor = &Instance_callAsConstructor;
3308 definition.finalize = &Finalize;
3309 Instance_ = JSClassCreate(&definition);
3311 definition = kJSClassDefinitionEmpty;
3312 definition.className = "Internal";
3313 definition.staticFunctions = Internal_staticFunctions;
3314 definition.hasProperty = &Internal_hasProperty;
3315 definition.getProperty = &Internal_getProperty;
3316 definition.setProperty = &Internal_setProperty;
3317 definition.getPropertyNames = &Internal_getPropertyNames;
3318 definition.finalize = &Finalize;
3319 Internal_ = JSClassCreate(&definition);
3321 definition = kJSClassDefinitionEmpty;
3322 definition.className = "Message";
3323 definition.staticFunctions = Functor_staticFunctions;
3324 definition.callAsFunction = &Message_callAsFunction;
3325 definition.finalize = &Finalize;
3326 Message_ = JSClassCreate(&definition);
3328 definition = kJSClassDefinitionEmpty;
3329 definition.className = "Pointer";
3330 definition.staticValues = Pointer_staticValues;
3331 definition.staticFunctions = Pointer_staticFunctions;
3332 definition.getProperty = &Pointer_getProperty;
3333 definition.setProperty = &Pointer_setProperty;
3334 definition.finalize = &Finalize;
3335 Pointer_ = JSClassCreate(&definition);
3337 definition = kJSClassDefinitionEmpty;
3338 definition.className = "Prototype";
3339 definition.hasProperty = &Prototype_hasProperty;
3340 definition.getProperty = &Prototype_getProperty;
3341 definition.setProperty = &Prototype_setProperty;
3343 definition.deleteProperty = &Prototype_deleteProperty;
3345 definition.getPropertyNames = &Prototype_getPropertyNames;
3346 definition.finalize = &Finalize;
3347 Prototype_ = JSClassCreate(&definition);
3349 definition = kJSClassDefinitionEmpty;
3350 definition.className = "Selector";
3351 definition.staticValues = CYValue_staticValues;
3352 definition.staticFunctions = Selector_staticFunctions;
3353 definition.callAsFunction = &Selector_callAsFunction;
3354 definition.finalize = &Finalize;
3355 Selector_ = JSClassCreate(&definition);
3357 definition = kJSClassDefinitionEmpty;
3358 definition.className = "Struct";
3359 definition.staticFunctions = Struct_staticFunctions;
3360 definition.getProperty = &Struct_getProperty;
3361 definition.setProperty = &Struct_setProperty;
3362 definition.getPropertyNames = &Struct_getPropertyNames;
3363 definition.finalize = &Finalize;
3364 Struct_ = JSClassCreate(&definition);
3366 definition = kJSClassDefinitionEmpty;
3367 definition.className = "Type";
3368 definition.staticFunctions = Type_staticFunctions;
3369 //definition.getProperty = &Type_getProperty;
3370 definition.callAsFunction = &Type_callAsFunction;
3371 definition.callAsConstructor = &Type_callAsConstructor;
3372 definition.finalize = &Finalize;
3373 Type_ = JSClassCreate(&definition);
3375 definition = kJSClassDefinitionEmpty;
3376 definition.className = "Runtime";
3377 definition.getProperty = &Runtime_getProperty;
3378 Runtime_ = JSClassCreate(&definition);
3380 definition = kJSClassDefinitionEmpty;
3381 definition.className = "ObjectiveC::Classes";
3382 definition.getProperty = &ObjectiveC_Classes_getProperty;
3383 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3384 ObjectiveC_Classes_ = JSClassCreate(&definition);
3386 definition = kJSClassDefinitionEmpty;
3387 definition.className = "ObjectiveC::Images";
3388 definition.getProperty = &ObjectiveC_Images_getProperty;
3389 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3390 ObjectiveC_Images_ = JSClassCreate(&definition);
3392 definition = kJSClassDefinitionEmpty;
3393 definition.className = "ObjectiveC::Image::Classes";
3394 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3395 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3396 definition.finalize = &Finalize;
3397 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3399 definition = kJSClassDefinitionEmpty;
3400 definition.className = "ObjectiveC::Protocols";
3401 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3402 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3403 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3405 definition = kJSClassDefinitionEmpty;
3406 //definition.getProperty = &Global_getProperty;
3407 JSClassRef Global(JSClassCreate(&definition));
3409 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3412 JSObjectRef global(CYGetGlobalObject(context));
3414 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3415 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3416 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3418 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3419 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3420 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3422 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3423 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3425 length_ = JSStringCreateWithUTF8CString("length");
3426 message_ = JSStringCreateWithUTF8CString("message");
3427 name_ = JSStringCreateWithUTF8CString("name");
3428 prototype_ = JSStringCreateWithUTF8CString("prototype");
3429 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3430 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3432 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3433 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3434 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3435 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3437 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3438 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3439 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3441 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3442 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3443 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3444 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3446 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3447 CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, &Instance_new));
3448 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3449 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3450 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3452 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3454 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3456 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3457 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3459 System_ = JSObjectMake(context, NULL, NULL);
3460 CYSetProperty(context, global, CYJSString("system"), System_);
3461 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3462 //CYSetProperty(context, System_, CYJSString("global"), global);
3464 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3466 Result_ = JSStringCreateWithUTF8CString("_");