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"
53 #include <CoreFoundation/CoreFoundation.h>
54 #include <CoreFoundation/CFLogUtilities.h>
56 #include <WebKit/WebScriptObject.h>
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
64 #include <ext/stdio_filebuf.h>
71 #include "Cycript.tab.hh"
76 #define _assert(test) do { \
78 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
81 #define _trace() do { \
82 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
87 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
89 #define CYPoolCatch(value) \
90 @catch (NSException *error) { \
91 _saved = [error retain]; \
97 [_saved autorelease]; \
101 static JSGlobalContextRef Context_;
102 static JSObjectRef System_;
104 static JSClassRef Functor_;
105 static JSClassRef Instance_;
106 static JSClassRef Pointer_;
107 static JSClassRef Runtime_;
108 static JSClassRef Selector_;
109 static JSClassRef Struct_;
111 static JSObjectRef Array_;
112 static JSObjectRef Function_;
114 static JSStringRef length_;
115 static JSStringRef message_;
116 static JSStringRef name_;
117 static JSStringRef toCYON_;
118 static JSStringRef toJSON_;
120 static Class NSCFBoolean_;
122 static NSArray *Bridge_;
130 void *operator new(size_t size) {
132 apr_pool_create(&pool, NULL);
133 void *data(apr_palloc(pool, size));
134 reinterpret_cast<CYData *>(data)->pool_ = pool;
138 static void Finalize(JSObjectRef object) {
139 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
141 apr_pool_destroy(data->pool_);
145 struct Pointer_privateData :
151 Pointer_privateData() {
154 Pointer_privateData(void *value) :
160 struct Selector_privateData : Pointer_privateData {
161 Selector_privateData(SEL value) :
162 Pointer_privateData(value)
166 SEL GetValue() const {
167 return reinterpret_cast<SEL>(value_);
171 struct Instance_privateData :
176 Instance_privateData(id value, bool transient) :
177 Pointer_privateData(value)
181 virtual ~Instance_privateData() {
183 [GetValue() release];
186 id GetValue() const {
187 return reinterpret_cast<id>(value_);
193 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
195 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
196 lhs.name = apr_pstrdup(pool, rhs.name);
197 if (rhs.type == NULL)
200 lhs.type = new(pool) Type;
201 Copy(pool, *lhs.type, *rhs.type);
203 lhs.offset = rhs.offset;
206 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
207 size_t count(rhs.count);
209 lhs.elements = new(pool) Element[count];
210 for (size_t index(0); index != count; ++index)
211 Copy(pool, lhs.elements[index], rhs.elements[index]);
214 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
215 lhs.primitive = rhs.primitive;
216 lhs.name = apr_pstrdup(pool, rhs.name);
217 lhs.flags = rhs.flags;
219 if (sig::IsAggregate(rhs.primitive))
220 Copy(pool, lhs.data.signature, rhs.data.signature);
222 if (rhs.data.data.type != NULL) {
223 lhs.data.data.type = new(pool) Type;
224 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
227 lhs.data.data.size = rhs.data.data.size;
231 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
233 lhs.alignment = rhs.alignment;
235 if (rhs.elements == NULL)
239 while (rhs.elements[count] != NULL)
242 lhs.elements = new(pool) ffi_type *[count + 1];
243 lhs.elements[count] = NULL;
245 for (size_t index(0); index != count; ++index) {
246 // XXX: if these are libffi native then you can just take them
247 ffi_type *ffi(new(pool) ffi_type);
248 lhs.elements[index] = ffi;
249 sig::Copy(pool, *ffi, *rhs.elements[index]);
256 struct CStringMapLess :
257 std::binary_function<const char *, const char *, bool>
259 _finline bool operator ()(const char *lhs, const char *rhs) const {
260 return strcmp(lhs, rhs) < 0;
264 struct Type_privateData {
268 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) {
269 sig::Copy(pool, type_, *type);
270 sig::Copy(pool, ffi_, *ffi);
274 struct Struct_privateData :
278 Type_privateData *type_;
280 Struct_privateData() {
284 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
285 static TypeMap Types_;
287 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
288 Struct_privateData *internal(new Struct_privateData());
289 apr_pool_t *pool(internal->pool_);
290 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
291 internal->type_ = typical;
294 internal->owner_ = owner;
295 internal->value_ = data;
297 internal->owner_ = NULL;
299 size_t size(typical->ffi_.size);
300 void *copy(apr_palloc(internal->pool_, size));
301 memcpy(copy, data, size);
302 internal->value_ = copy;
305 return JSObjectMake(context, Struct_, internal);
308 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *type) {
310 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]]) {
311 switch ([[entry objectAtIndex:0] intValue]) {
314 sig::Parse(Pool_, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
321 struct Functor_privateData :
324 sig::Signature signature_;
327 Functor_privateData(const char *type, void (*value)()) :
328 Pointer_privateData(reinterpret_cast<void *>(value))
330 sig::Parse(pool_, &signature_, type, &Structor_);
331 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
338 JSContextRef context_;
339 JSObjectRef function_;
341 ffoData(const char *type) :
342 Functor_privateData(type, NULL)
347 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
349 object = [object retain];
350 Instance_privateData *data(new Instance_privateData(object, transient));
351 return JSObjectMake(context, Instance_, data);
354 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
356 return [value UTF8String];
358 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
359 char *string(new(pool) char[size]);
360 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
361 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
366 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
367 return JSValueMakeBoolean(context, value);
370 JSValueRef CYCastJSValue(JSContextRef context, double value) {
371 return JSValueMakeNumber(context, value);
374 #define CYCastJSValue_(Type_) \
375 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
376 return JSValueMakeNumber(context, static_cast<double>(value)); \
380 CYCastJSValue_(unsigned int)
381 CYCastJSValue_(long int)
382 CYCastJSValue_(long unsigned int)
383 CYCastJSValue_(long long int)
384 CYCastJSValue_(long long unsigned int)
386 JSValueRef CYJSUndefined(JSContextRef context) {
387 return JSValueMakeUndefined(context);
390 size_t CYCastIndex(const char *value) {
391 if (value[0] == '0') {
392 if (value[1] == '\0')
396 size_t index(strtoul(value, &end, 10));
397 if (value + strlen(value) == end)
404 size_t CYCastIndex(NSString *value) {
405 return CYCastIndex([value UTF8String]);
408 @interface NSMethodSignature (Cycript)
409 - (NSString *) _typeString;
412 @interface NSObject (Cycript)
414 - (JSType) cy$JSType;
416 - (NSObject *) cy$toJSON:(NSString *)key;
417 - (NSString *) cy$toCYON;
418 - (NSString *) cy$toKey;
420 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
422 - (NSObject *) cy$getProperty:(NSString *)name;
423 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
424 - (bool) cy$deleteProperty:(NSString *)name;
428 @interface NSString (Cycript)
429 - (void *) cy$symbol;
432 @interface NSNumber (Cycript)
433 - (void *) cy$symbol;
436 struct PropertyAttributes {
441 const char *variable;
454 PropertyAttributes(objc_property_t property) :
466 name = property_getName(property);
467 const char *attributes(property_getAttributes(property));
469 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
471 case 'R': readonly = true; break;
472 case 'C': copy = true; break;
473 case '&': retain = true; break;
474 case 'N': nonatomic = true; break;
475 case 'G': getter_ = token + 1; break;
476 case 'S': setter_ = token + 1; break;
477 case 'V': variable = token + 1; break;
481 /*if (variable == NULL) {
482 variable = property_getName(property);
483 size_t size(strlen(variable));
484 char *name(new(pool_) char[size + 2]);
486 memcpy(name + 1, variable, size);
487 name[size + 1] = '\0';
492 const char *Getter() {
494 getter_ = apr_pstrdup(pool_, name);
498 const char *Setter() {
499 if (setter_ == NULL && !readonly) {
500 size_t length(strlen(name));
502 char *temp(new(pool_) char[length + 5]);
508 temp[3] = toupper(name[0]);
509 memcpy(temp + 4, name + 1, length - 1);
512 temp[length + 3] = ':';
513 temp[length + 4] = '\0';
522 @implementation NSObject (Cycript)
524 - (JSType) cy$JSType {
525 return kJSTypeObject;
528 - (NSObject *) cy$toJSON:(NSString *)key {
529 return [self description];
532 - (NSString *) cy$toCYON {
533 return [[self cy$toJSON:@""] cy$toCYON];
536 - (NSString *) cy$toKey {
537 return [self cy$toCYON];
540 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
541 return CYMakeInstance(context, self, transient);
544 - (NSObject *) cy$getProperty:(NSString *)name {
545 /*if (![name isEqualToString:@"prototype"])
546 NSLog(@"get:%@", name);*/
550 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
551 //NSLog(@"set:%@", name);
555 - (bool) cy$deleteProperty:(NSString *)name {
556 //NSLog(@"delete:%@", name);
562 @implementation WebUndefined (Cycript)
564 - (JSType) cy$JSType {
565 return kJSTypeUndefined;
568 - (NSObject *) cy$toJSON:(NSString *)key {
572 - (NSString *) cy$toCYON {
576 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
577 return CYJSUndefined(context);
582 @implementation NSNull (Cycript)
584 - (JSType) cy$JSType {
588 - (NSObject *) cy$toJSON:(NSString *)key {
592 - (NSString *) cy$toCYON {
598 @implementation NSArray (Cycript)
600 - (NSString *) cy$toCYON {
601 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
602 [json appendString:@"["];
605 for (id object in self) {
607 [json appendString:@","];
610 if ([object cy$JSType] != kJSTypeUndefined)
611 [json appendString:[object cy$toCYON]];
613 [json appendString:@","];
618 [json appendString:@"]"];
622 - (NSObject *) cy$getProperty:(NSString *)name {
623 if ([name isEqualToString:@"length"])
624 return [NSNumber numberWithUnsignedInteger:[self count]];
626 size_t index(CYCastIndex(name));
627 if (index == _not(size_t) || index >= [self count])
628 return [super cy$getProperty:name];
630 return [self objectAtIndex:index];
635 @implementation NSMutableArray (Cycript)
637 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
638 size_t index(CYCastIndex(name));
639 if (index == _not(size_t) || index >= [self count])
640 return [super cy$setProperty:name to:value];
642 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
647 - (bool) cy$deleteProperty:(NSString *)name {
648 size_t index(CYCastIndex(name));
649 if (index == _not(size_t) || index >= [self count])
650 return [super cy$deleteProperty:name];
652 [self removeObjectAtIndex:index];
659 @implementation NSDictionary (Cycript)
661 - (NSString *) cy$toCYON {
662 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
663 [json appendString:@"{"];
666 for (id key in self) {
668 [json appendString:@","];
671 [json appendString:[key cy$toKey]];
672 [json appendString:@":"];
673 NSObject *object([self objectForKey:key]);
674 [json appendString:[object cy$toCYON]];
677 [json appendString:@"}"];
681 - (NSObject *) cy$getProperty:(NSString *)name {
682 return [self objectForKey:name];
687 @implementation NSMutableDictionary (Cycript)
689 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
690 [self setObject:(value ?: [NSNull null]) forKey:name];
694 - (bool) cy$deleteProperty:(NSString *)name {
695 if ([self objectForKey:name] == nil)
698 [self removeObjectForKey:name];
705 @implementation NSNumber (Cycript)
707 - (JSType) cy$JSType {
708 // XXX: this just seems stupid
709 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
712 - (NSObject *) cy$toJSON:(NSString *)key {
716 - (NSString *) cy$toCYON {
717 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
720 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
721 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
724 - (void *) cy$symbol {
725 return [self pointerValue];
730 @implementation NSString (Cycript)
732 - (JSType) cy$JSType {
733 return kJSTypeString;
736 - (NSObject *) cy$toJSON:(NSString *)key {
740 - (NSString *) cy$toCYON {
741 // XXX: this should use the better code from Output.cpp
742 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
744 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
745 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
746 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
747 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
748 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
750 CFStringInsert(json, 0, CFSTR("\""));
751 CFStringAppend(json, CFSTR("\""));
753 return [reinterpret_cast<const NSString *>(json) autorelease];
756 - (NSString *) cy$toKey {
757 const char *value([self UTF8String]);
758 size_t size(strlen(value));
763 if (DigitRange_[value[0]]) {
764 if (CYCastIndex(self) == _not(size_t))
767 if (!WordStartRange_[value[0]])
769 for (size_t i(1); i != size; ++i)
770 if (!WordEndRange_[value[i]])
777 return [self cy$toCYON];
780 - (void *) cy$symbol {
782 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
787 @interface CYJSObject : NSDictionary {
789 JSContextRef context_;
792 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
794 - (NSString *) cy$toJSON:(NSString *)key;
796 - (NSUInteger) count;
797 - (id) objectForKey:(id)key;
798 - (NSEnumerator *) keyEnumerator;
799 - (void) setObject:(id)object forKey:(id)key;
800 - (void) removeObjectForKey:(id)key;
804 @interface CYJSArray : NSArray {
806 JSContextRef context_;
809 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
811 - (NSUInteger) count;
812 - (id) objectAtIndex:(NSUInteger)index;
816 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
817 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
818 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
820 JSGlobalContextRef CYGetJSContext() {
827 @catch (id error) { \
828 CYThrow(context, error, exception); \
832 void CYThrow(JSContextRef context, JSValueRef value);
834 apr_status_t CYPoolRelease_(void *data) {
835 id object(reinterpret_cast<id>(data));
840 id CYPoolRelease(apr_pool_t *pool, id object) {
843 else if (pool == NULL)
844 return [object autorelease];
846 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
851 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
852 return (CFTypeRef) CYPoolRelease(pool, (id) object);
855 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
856 if (JSValueIsObjectOfClass(context, object, Instance_)) {
857 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
858 return data->GetValue();
861 JSValueRef exception(NULL);
862 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
863 CYThrow(context, exception);
864 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
865 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
868 JSStringRef CYCopyJSString(id value) {
869 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
872 JSStringRef CYCopyJSString(const char *value) {
873 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
876 JSStringRef CYCopyJSString(JSStringRef value) {
877 return value == NULL ? NULL : JSStringRetain(value);
880 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
881 if (JSValueIsNull(context, value))
883 JSValueRef exception(NULL);
884 JSStringRef string(JSValueToStringCopy(context, value, &exception));
885 CYThrow(context, exception);
895 JSStringRelease(string_);
899 CYJSString(const CYJSString &rhs) :
900 string_(CYCopyJSString(rhs.string_))
904 template <typename Arg0_>
905 CYJSString(Arg0_ arg0) :
906 string_(CYCopyJSString(arg0))
910 template <typename Arg0_, typename Arg1_>
911 CYJSString(Arg0_ arg0, Arg1_ arg1) :
912 string_(CYCopyJSString(arg0, arg1))
916 CYJSString &operator =(const CYJSString &rhs) {
918 string_ = CYCopyJSString(rhs.string_);
931 operator JSStringRef() const {
936 CFStringRef CYCopyCFString(JSStringRef value) {
937 return JSStringCopyCFString(kCFAllocatorDefault, value);
940 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
941 return CYCopyCFString(CYJSString(context, value));
944 double CYCastDouble(const char *value, size_t size) {
946 double number(strtod(value, &end));
947 if (end != value + size)
952 double CYCastDouble(const char *value) {
953 return CYCastDouble(value, strlen(value));
956 double CYCastDouble(JSContextRef context, JSValueRef value) {
957 JSValueRef exception(NULL);
958 double number(JSValueToNumber(context, value, &exception));
959 CYThrow(context, exception);
963 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
964 double number(CYCastDouble(context, value));
965 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
968 CFStringRef CYCopyCFString(const char *value) {
969 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
972 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
973 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
976 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
977 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
980 bool CYCastBool(JSContextRef context, JSValueRef value) {
981 return JSValueToBoolean(context, value);
984 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
988 switch (JSType type = JSValueGetType(context, value)) {
989 case kJSTypeUndefined:
990 object = [WebUndefined undefined];
999 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1004 object = CYCopyCFNumber(context, value);
1009 object = CYCopyCFString(context, value);
1014 // XXX: this might could be more efficient
1015 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1020 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1027 return CYPoolRelease(pool, object);
1029 return CFRetain(object);
1032 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1033 return CYCFType(pool, context, value, true);
1036 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1037 return CYCFType(pool, context, value, false);
1040 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1042 size_t size(JSPropertyNameArrayGetCount(names));
1043 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1044 for (size_t index(0); index != size; ++index)
1045 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1049 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1050 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1053 void CYThrow(JSContextRef context, JSValueRef value) {
1056 @throw CYCastNSObject(NULL, context, value);
1059 JSValueRef CYJSNull(JSContextRef context) {
1060 return JSValueMakeNull(context);
1063 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1064 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1067 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1068 return CYCastJSValue(context, CYJSString(value));
1071 JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
1072 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
1075 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1076 JSValueRef exception(NULL);
1077 JSObjectRef object(JSValueToObject(context, value, &exception));
1078 CYThrow(context, exception);
1082 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1083 JSValueRef exception(NULL);
1084 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1085 CYThrow(context, exception);
1089 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1090 JSValueRef exception(NULL);
1091 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1092 CYThrow(context, exception);
1096 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1097 JSValueRef exception(NULL);
1098 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1099 CYThrow(context, exception);
1102 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1103 if (exception == NULL)
1105 *exception = CYCastJSValue(context, error);
1108 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1109 JSValueRef exception(NULL);
1110 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1111 CYThrow(context, exception);
1115 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1116 // XXX: this isn't actually correct
1117 return value != NULL && JSValueIsObject(context, value);
1120 @implementation CYJSObject
1122 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1123 if ((self = [super init]) != nil) {
1129 - (NSObject *) cy$toJSON:(NSString *)key {
1130 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1131 if (!CYIsCallable(context_, toJSON))
1132 return [super cy$toJSON:key];
1134 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1135 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1136 // XXX: do I really want an NSNull here?!
1137 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1141 - (NSString *) cy$toCYON {
1142 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1143 if (!CYIsCallable(context_, toCYON))
1144 return [super cy$toCYON];
1146 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1147 return CYCastNSString(NULL, CYJSString(context_, value));
1151 - (NSUInteger) count {
1152 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1153 size_t size(JSPropertyNameArrayGetCount(names));
1154 JSPropertyNameArrayRelease(names);
1158 - (id) objectForKey:(id)key {
1159 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1162 - (NSEnumerator *) keyEnumerator {
1163 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1164 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1165 JSPropertyNameArrayRelease(names);
1169 - (void) setObject:(id)object forKey:(id)key {
1170 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1173 - (void) removeObjectForKey:(id)key {
1174 JSValueRef exception(NULL);
1175 // XXX: this returns a bool... throw exception, or ignore?
1176 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1177 CYThrow(context_, exception);
1182 @implementation CYJSArray
1184 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1185 if ((self = [super init]) != nil) {
1191 - (NSUInteger) count {
1192 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1195 - (id) objectAtIndex:(NSUInteger)index {
1196 JSValueRef exception(NULL);
1197 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1198 CYThrow(context_, exception);
1199 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1204 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1207 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1208 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
1213 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1214 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
1215 const char *string(CYPoolCString(pool, json));
1221 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1225 NSString *self(CYCastNSObject(pool, context, object));
1226 NSString *name(CYCastNSString(pool, property));
1229 if (NSObject *data = [self cy$getProperty:name])
1230 return CYCastJSValue(context, data);
1233 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1234 PropertyAttributes attributes(property);
1235 SEL sel(sel_registerName(attributes.Getter()));
1236 return CYSendMessage(pool, context, self, sel, 0, NULL, exception);
1243 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1247 NSString *self(CYCastNSObject(pool, context, object));
1248 NSString *name(CYCastNSString(pool, property));
1249 NSString *data(CYCastNSObject(pool, context, value));
1252 if ([self cy$setProperty:name to:data])
1256 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1257 PropertyAttributes attributes(property);
1258 if (const char *setter = attributes.Setter()) {
1259 SEL sel(sel_registerName(setter));
1260 JSValueRef arguments[1] = {value};
1261 CYSendMessage(pool, context, self, sel, 1, arguments, exception);
1270 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1273 NSString *self(CYCastNSObject(NULL, context, object));
1274 NSString *name(CYCastNSString(NULL, property));
1275 return [self cy$deleteProperty:name];
1280 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1282 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
1283 return CYMakeInstance(context, [data->GetValue() alloc], true);
1287 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1288 Selector_privateData *data(new Selector_privateData(sel));
1289 return JSObjectMake(context, Selector_, data);
1292 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
1293 Pointer_privateData *data(new Pointer_privateData(pointer));
1294 return JSObjectMake(context, Pointer_, data);
1297 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1298 Functor_privateData *data(new Functor_privateData(type, function));
1299 return JSObjectMake(context, Functor_, data);
1302 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1304 const char *string([CYCastNSString(NULL, value) UTF8String]);
1306 *length = strlen(string);
1309 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1310 char *string(new(pool) char[size]);
1311 JSStringGetUTF8CString(value, string, size);
1312 // XXX: this is ironic
1314 *length = strlen(string);
1319 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1320 if (!JSValueIsNull(context, value))
1321 return CYPoolCString(pool, CYJSString(context, value), length);
1329 // XXX: this macro is unhygenic
1330 #define CYCastCString(context, value) ({ \
1332 if (value == NULL) \
1334 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1335 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1336 utf8 = reinterpret_cast<char *>(alloca(size)); \
1337 JSStringGetUTF8CString(string, utf8, size); \
1338 JSStringRelease(string); \
1344 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1345 switch (JSValueGetType(context, value)) {
1348 /*case kJSTypeString:
1349 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1351 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1352 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1353 return data->value_;
1356 double number(CYCastDouble(context, value));
1357 if (std::isnan(number))
1358 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1359 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1363 template <typename Type_>
1364 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1365 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1368 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1369 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1370 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1371 return reinterpret_cast<SEL>(data->value_);
1373 return CYCastPointer<SEL>(context, value);
1376 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1377 switch (type->primitive) {
1378 case sig::boolean_P:
1379 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1382 #define CYPoolFFI_(primitive, native) \
1383 case sig::primitive ## _P: \
1384 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1387 CYPoolFFI_(uchar, unsigned char)
1388 CYPoolFFI_(char, char)
1389 CYPoolFFI_(ushort, unsigned short)
1390 CYPoolFFI_(short, short)
1391 CYPoolFFI_(ulong, unsigned long)
1392 CYPoolFFI_(long, long)
1393 CYPoolFFI_(uint, unsigned int)
1394 CYPoolFFI_(int, int)
1395 CYPoolFFI_(ulonglong, unsigned long long)
1396 CYPoolFFI_(longlong, long long)
1397 CYPoolFFI_(float, float)
1398 CYPoolFFI_(double, double)
1401 case sig::typename_P:
1402 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1405 case sig::selector_P:
1406 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1409 case sig::pointer_P:
1410 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1414 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1417 case sig::struct_P: {
1418 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1419 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1420 for (size_t index(0); index != type->data.signature.count; ++index) {
1421 sig::Element *element(&type->data.signature.elements[index]);
1422 ffi_type *field(ffi->elements[index]);
1425 if (aggregate == NULL)
1428 rhs = CYGetProperty(context, aggregate, index);
1429 if (JSValueIsUndefined(context, rhs)) {
1430 if (element->name != NULL)
1431 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1434 if (JSValueIsUndefined(context, rhs)) undefined:
1435 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1439 CYPoolFFI(pool, context, element->type, field, base, rhs);
1441 base += field->size;
1449 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1454 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
1457 switch (type->primitive) {
1458 case sig::boolean_P:
1459 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1462 #define CYFromFFI_(primitive, native) \
1463 case sig::primitive ## _P: \
1464 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1467 CYFromFFI_(uchar, unsigned char)
1468 CYFromFFI_(char, char)
1469 CYFromFFI_(ushort, unsigned short)
1470 CYFromFFI_(short, short)
1471 CYFromFFI_(ulong, unsigned long)
1472 CYFromFFI_(long, long)
1473 CYFromFFI_(uint, unsigned int)
1474 CYFromFFI_(int, int)
1475 CYFromFFI_(ulonglong, unsigned long long)
1476 CYFromFFI_(longlong, long long)
1477 CYFromFFI_(float, float)
1478 CYFromFFI_(double, double)
1481 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
1484 case sig::typename_P:
1485 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1488 case sig::selector_P:
1489 if (SEL sel = *reinterpret_cast<SEL *>(data))
1490 value = CYMakeSelector(context, sel);
1494 case sig::pointer_P:
1495 if (void *pointer = *reinterpret_cast<void **>(data))
1496 value = CYMakePointer(context, pointer);
1501 if (char *utf8 = *reinterpret_cast<char **>(data))
1502 value = CYCastJSValue(context, utf8);
1507 value = CYMakeStruct(context, data, type, ffi, owner);
1511 value = CYJSUndefined(context);
1515 value = CYJSNull(context);
1519 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1526 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1527 Type_privateData *typical(internal->type_);
1530 const char *name(CYPoolCString(pool, property, &length));
1531 double number(CYCastDouble(name, length));
1533 size_t count(typical->type_.data.signature.count);
1535 if (std::isnan(number)) {
1536 if (property == NULL)
1539 sig::Element *elements(typical->type_.data.signature.elements);
1541 for (size_t local(0); local != count; ++local) {
1542 sig::Element *element(&elements[local]);
1543 if (element->name != NULL && strcmp(name, element->name) == 0) {
1551 index = static_cast<ssize_t>(number);
1552 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1557 base = reinterpret_cast<uint8_t *>(internal->value_);
1558 for (ssize_t local(0); local != index; ++local)
1559 base += typical->ffi_.elements[local]->size;
1564 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1566 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1567 Type_privateData *typical(internal->type_);
1572 if (!Index_(pool, internal, property, index, base))
1576 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
1580 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1582 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1583 Type_privateData *typical(internal->type_);
1588 if (!Index_(pool, internal, property, index, base))
1592 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1597 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1598 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1599 Type_privateData *typical(internal->type_);
1601 size_t count(typical->type_.data.signature.count);
1602 sig::Element *elements(typical->type_.data.signature.elements);
1606 for (size_t index(0); index != count; ++index) {
1608 name = elements[index].name;
1611 sprintf(number, "%lu", index);
1615 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1619 JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1621 if (setups + count != signature->count - 1)
1622 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1624 size_t size(setups + count);
1626 memcpy(values, setup, sizeof(void *) * setups);
1628 for (size_t index(setups); index != size; ++index) {
1629 sig::Element *element(&signature->elements[index + 1]);
1630 ffi_type *ffi(cif->arg_types[index]);
1632 values[index] = new(pool) uint8_t[ffi->size];
1633 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1636 uint8_t value[cif->rtype->size];
1637 ffi_call(cif, function, value, values);
1639 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
1643 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1644 ffoData *data(reinterpret_cast<ffoData *>(arg));
1646 JSContextRef context(data->context_);
1648 size_t count(data->cif_.nargs);
1649 JSValueRef values[count];
1651 for (size_t index(0); index != count; ++index)
1652 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1654 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1655 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1658 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1659 // XXX: in case of exceptions this will leak
1660 ffoData *data(new ffoData(type));
1662 ffi_closure *closure;
1663 _syscall(closure = (ffi_closure *) mmap(
1664 NULL, sizeof(ffi_closure),
1665 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1669 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1670 _assert(status == FFI_OK);
1672 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1674 data->value_ = closure;
1676 data->context_ = CYGetJSContext();
1677 data->function_ = function;
1679 return JSObjectMake(context, Functor_, data);
1682 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1685 NSString *name(CYCastNSString(pool, property));
1686 if (Class _class = NSClassFromString(name))
1687 return CYMakeInstance(context, _class, true);
1688 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1689 switch ([[entry objectAtIndex:0] intValue]) {
1691 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1693 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1695 // XXX: this is horrendously inefficient
1696 sig::Signature signature;
1697 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
1699 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1700 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
1706 bool stret(ffi_type *ffi_type) {
1707 return ffi_type->type == FFI_TYPE_STRUCT && (
1708 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1709 struct_forward_array[ffi_type->size] != 0
1714 int *_NSGetArgc(void);
1715 char ***_NSGetArgv(void);
1716 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1719 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1721 NSLog(@"%s", CYCastCString(context, arguments[0]));
1722 return CYJSUndefined(context);
1726 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1730 int argc(CYCastDouble(context, arguments[0]));
1731 char **argv(CYCastPointer<char **>(context, arguments[1]));
1732 NSString *principal(CYCastNSObject(pool, context, arguments[2]));
1733 NSString *delegate(CYCastNSObject(pool, context, arguments[3]));
1735 argc = *_NSGetArgc() - 1;
1736 argv = *_NSGetArgv() + 1;
1737 for (int i(0); i != argc; ++i)
1738 NSLog(@"argv[%i]=%s", i, argv[i]);
1741 return CYCastJSValue(context, UIApplicationMain(argc, argv, principal, delegate));
1745 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1748 Class _class(object_getClass(self));
1749 if (Method method = class_getInstanceMethod(_class, _cmd))
1750 type = method_getTypeEncoding(method);
1753 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1755 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1756 type = CYPoolCString(pool, [method _typeString]);
1764 sig::Signature signature;
1765 sig::Parse(pool, &signature, type, &Structor_);
1768 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1770 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1771 return CYCallFunction(pool, context, 2, setup, count, arguments, exception, &signature, &cif, function);
1774 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1782 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1784 self = CYCastNSObject(pool, context, arguments[0]);
1786 return CYJSNull(context);
1788 _cmd = CYCastSEL(context, arguments[1]);
1791 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, exception);
1794 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1795 JSValueRef setup[count + 2];
1798 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
1799 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1802 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1804 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1805 return CYCallFunction(pool, context, 0, NULL, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1808 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1811 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1812 const char *name(CYCastCString(context, arguments[0]));
1813 return CYMakeSelector(context, sel_registerName(name));
1817 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1820 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1821 const char *type(CYCastCString(context, arguments[1]));
1822 JSValueRef exception(NULL);
1823 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1824 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1825 return CYMakeFunctor(context, function, type);
1826 } else if (exception != NULL) {
1829 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1830 return CYMakeFunctor(context, function, type);
1835 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1836 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
1837 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1840 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1844 static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1846 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1847 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1851 static JSValueRef Pointer_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1852 return Pointer_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1855 static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1857 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1859 sprintf(string, "%p", data->value_);
1860 return CYCastJSValue(context, string);
1864 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1866 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1868 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
1873 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1875 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1877 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
1878 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
1883 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1885 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1887 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
1892 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1894 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1895 return CYCastJSValue(context, sel_getName(data->GetValue()));
1899 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1900 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
1903 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1905 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1906 const char *name(sel_getName(data->GetValue()));
1908 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
1913 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1916 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1918 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1919 Class _class(CYCastNSObject(pool, context, arguments[0]));
1920 bool instance(CYCastBool(context, arguments[1]));
1921 SEL sel(data->GetValue());
1922 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1923 return CYCastJSValue(context, method_getTypeEncoding(method));
1924 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1925 return CYCastJSValue(context, CYJSString(type));
1927 return CYJSNull(context);
1931 static JSStaticValue Pointer_staticValues[2] = {
1932 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1933 {NULL, NULL, NULL, 0}
1936 static JSStaticFunction Pointer_staticFunctions[4] = {
1937 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1938 {"toJSON", &Pointer_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1939 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1943 /*static JSStaticValue Selector_staticValues[2] = {
1944 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1945 {NULL, NULL, NULL, 0}
1948 static JSStaticFunction Instance_staticFunctions[4] = {
1949 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1950 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1951 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1955 static JSStaticFunction Selector_staticFunctions[5] = {
1956 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1957 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1958 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1959 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1963 CYDriver::CYDriver(const std::string &filename) :
1967 filename_(filename),
1973 CYDriver::~CYDriver() {
1977 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1978 CYDriver::Error error;
1979 error.location_ = location;
1980 error.message_ = message;
1981 driver.errors_.push_back(error);
1984 void CYSetArgs(int argc, const char *argv[]) {
1985 JSContextRef context(CYGetJSContext());
1986 JSValueRef args[argc];
1987 for (int i(0); i != argc; ++i)
1988 args[i] = CYCastJSValue(context, argv[i]);
1989 JSValueRef exception(NULL);
1990 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1991 CYThrow(context, exception);
1992 CYSetProperty(context, System_, CYJSString("args"), array);
1995 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1996 return JSContextGetGlobalObject(context);
1999 MSInitialize { _pooled
2002 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2004 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2006 JSClassDefinition definition;
2008 definition = kJSClassDefinitionEmpty;
2009 definition.className = "Pointer";
2010 definition.staticValues = Pointer_staticValues;
2011 definition.staticFunctions = Pointer_staticFunctions;
2012 definition.finalize = &CYData::Finalize;
2013 Pointer_ = JSClassCreate(&definition);
2015 definition = kJSClassDefinitionEmpty;
2016 definition.className = "Functor";
2017 definition.staticValues = Pointer_staticValues;
2018 definition.staticFunctions = Pointer_staticFunctions;
2019 definition.callAsFunction = &Functor_callAsFunction;
2020 definition.finalize = &CYData::Finalize;
2021 Functor_ = JSClassCreate(&definition);
2023 definition = kJSClassDefinitionEmpty;
2024 definition.className = "Struct";
2025 definition.getProperty = &Struct_getProperty;
2026 definition.setProperty = &Struct_setProperty;
2027 definition.getPropertyNames = &Struct_getPropertyNames;
2028 definition.finalize = &CYData::Finalize;
2029 Struct_ = JSClassCreate(&definition);
2031 definition = kJSClassDefinitionEmpty;
2032 definition.className = "Selector";
2033 definition.staticValues = Pointer_staticValues;
2034 //definition.staticValues = Selector_staticValues;
2035 definition.staticFunctions = Selector_staticFunctions;
2036 definition.callAsFunction = &Selector_callAsFunction;
2037 definition.finalize = &CYData::Finalize;
2038 Selector_ = JSClassCreate(&definition);
2040 definition = kJSClassDefinitionEmpty;
2041 definition.className = "Instance";
2042 definition.staticValues = Pointer_staticValues;
2043 definition.staticFunctions = Instance_staticFunctions;
2044 definition.getProperty = &Instance_getProperty;
2045 definition.setProperty = &Instance_setProperty;
2046 definition.deleteProperty = &Instance_deleteProperty;
2047 definition.callAsConstructor = &Instance_callAsConstructor;
2048 definition.finalize = &CYData::Finalize;
2049 Instance_ = JSClassCreate(&definition);
2051 definition = kJSClassDefinitionEmpty;
2052 definition.className = "Runtime";
2053 definition.getProperty = &Runtime_getProperty;
2054 Runtime_ = JSClassCreate(&definition);
2056 definition = kJSClassDefinitionEmpty;
2057 //definition.getProperty = &Global_getProperty;
2058 JSClassRef Global(JSClassCreate(&definition));
2060 JSGlobalContextRef context(JSGlobalContextCreate(Global));
2063 JSObjectRef global(CYGetGlobalObject(context));
2065 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
2066 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
2068 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
2069 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
2071 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
2072 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2074 System_ = JSObjectMake(context, NULL, NULL);
2075 CYSetProperty(context, global, CYJSString("system"), System_);
2076 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
2077 //CYSetProperty(context, System_, CYJSString("global"), global);
2079 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2081 length_ = JSStringCreateWithUTF8CString("length");
2082 message_ = JSStringCreateWithUTF8CString("message");
2083 name_ = JSStringCreateWithUTF8CString("name");
2084 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2085 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
2087 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2088 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));