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 @interface NSMethodSignature (Cycript)
391 - (NSString *) _typeString;
394 @interface NSObject (Cycript)
396 - (JSType) cy$JSType;
398 - (NSObject *) cy$toJSON:(NSString *)key;
399 - (NSString *) cy$toCYON;
400 - (NSString *) cy$toKey;
402 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
404 - (NSObject *) cy$getProperty:(NSString *)name;
405 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
406 - (bool) cy$deleteProperty:(NSString *)name;
410 @interface NSString (Cycript)
411 - (void *) cy$symbol;
414 @interface NSNumber (Cycript)
415 - (void *) cy$symbol;
418 struct PropertyAttributes {
423 const char *variable;
436 PropertyAttributes(objc_property_t property) :
448 name = property_getName(property);
449 const char *attributes(property_getAttributes(property));
451 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
453 case 'R': readonly = true; break;
454 case 'C': copy = true; break;
455 case '&': retain = true; break;
456 case 'N': nonatomic = true; break;
457 case 'G': getter_ = token + 1; break;
458 case 'S': setter_ = token + 1; break;
459 case 'V': variable = token + 1; break;
463 /*if (variable == NULL) {
464 variable = property_getName(property);
465 size_t size(strlen(variable));
466 char *name(new(pool_) char[size + 2]);
468 memcpy(name + 1, variable, size);
469 name[size + 1] = '\0';
474 const char *Getter() {
476 getter_ = apr_pstrdup(pool_, name);
480 const char *Setter() {
481 if (setter_ == NULL && !readonly) {
482 size_t length(strlen(name));
484 char *temp(new(pool_) char[length + 5]);
490 temp[3] = toupper(name[0]);
491 memcpy(temp + 4, name + 1, length - 1);
494 temp[length + 3] = ':';
495 temp[length + 4] = '\0';
504 @implementation NSObject (Cycript)
506 - (JSType) cy$JSType {
507 return kJSTypeObject;
510 - (NSObject *) cy$toJSON:(NSString *)key {
511 return [self description];
514 - (NSString *) cy$toCYON {
515 return [[self cy$toJSON:@""] cy$toCYON];
518 - (NSString *) cy$toKey {
519 return [self cy$toCYON];
522 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
523 return CYMakeInstance(context, self, transient);
526 - (NSObject *) cy$getProperty:(NSString *)name {
527 /*if (![name isEqualToString:@"prototype"])
528 NSLog(@"get:%@", name);*/
532 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
533 //NSLog(@"set:%@", name);
537 - (bool) cy$deleteProperty:(NSString *)name {
538 //NSLog(@"delete:%@", name);
544 @implementation WebUndefined (Cycript)
546 - (JSType) cy$JSType {
547 return kJSTypeUndefined;
550 - (NSObject *) cy$toJSON:(NSString *)key {
554 - (NSString *) cy$toCYON {
558 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
559 return CYJSUndefined(context);
564 @implementation NSNull (Cycript)
566 - (JSType) cy$JSType {
570 - (NSObject *) cy$toJSON:(NSString *)key {
574 - (NSString *) cy$toCYON {
580 @implementation NSArray (Cycript)
582 - (NSString *) cy$toCYON {
583 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
584 [json appendString:@"["];
587 for (id object in self) {
589 [json appendString:@","];
592 if ([object cy$JSType] != kJSTypeUndefined)
593 [json appendString:[object cy$toCYON]];
595 [json appendString:@","];
600 [json appendString:@"]"];
604 - (NSObject *) cy$getProperty:(NSString *)name {
605 if ([name isEqualToString:@"length"])
606 return [NSNumber numberWithUnsignedInteger:[self count]];
608 int index([name intValue]);
609 if (index < 0 || index >= static_cast<int>([self count]))
610 return [super cy$getProperty:name];
612 return [self objectAtIndex:index];
617 @implementation NSMutableArray (Cycript)
619 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
620 int index([name intValue]);
621 if (index < 0 || index >= static_cast<int>([self count]))
622 return [super cy$setProperty:name to:value];
624 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
629 - (bool) cy$deleteProperty:(NSString *)name {
630 int index([name intValue]);
631 if (index < 0 || index >= static_cast<int>([self count]))
632 return [super cy$deleteProperty:name];
634 [self removeObjectAtIndex:index];
641 @implementation NSDictionary (Cycript)
643 - (NSString *) cy$toCYON {
644 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
645 [json appendString:@"{"];
648 for (id key in self) {
650 [json appendString:@","];
653 [json appendString:[key cy$toKey]];
654 [json appendString:@":"];
655 NSObject *object([self objectForKey:key]);
656 [json appendString:[object cy$toCYON]];
659 [json appendString:@"}"];
663 - (NSObject *) cy$getProperty:(NSString *)name {
664 return [self objectForKey:name];
669 @implementation NSMutableDictionary (Cycript)
671 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
672 [self setObject:(value ?: [NSNull null]) forKey:name];
676 - (bool) cy$deleteProperty:(NSString *)name {
677 if ([self objectForKey:name] == nil)
680 [self removeObjectForKey:name];
687 @implementation NSNumber (Cycript)
689 - (JSType) cy$JSType {
690 // XXX: this just seems stupid
691 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
694 - (NSObject *) cy$toJSON:(NSString *)key {
698 - (NSString *) cy$toCYON {
699 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
702 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
703 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
706 - (void *) cy$symbol {
707 return [self pointerValue];
712 @implementation NSString (Cycript)
714 - (JSType) cy$JSType {
715 return kJSTypeString;
718 - (NSObject *) cy$toJSON:(NSString *)key {
722 - (NSString *) cy$toCYON {
723 // XXX: this should use the better code from Output.cpp
724 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
726 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
727 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
728 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
729 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
730 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
732 CFStringInsert(json, 0, CFSTR("\""));
733 CFStringAppend(json, CFSTR("\""));
735 return [reinterpret_cast<const NSString *>(json) autorelease];
738 - (NSString *) cy$toKey {
739 const char *value([self UTF8String]);
740 size_t size(strlen(value));
742 if (size == 0 || !WordStartRange_[value[0]])
744 for (size_t i(1); i != size; ++i)
745 if (!WordEndRange_[value[i]])
750 return [self cy$toCYON];
753 - (void *) cy$symbol {
755 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
760 @interface CYJSObject : NSDictionary {
762 JSContextRef context_;
765 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
767 - (NSString *) cy$toJSON:(NSString *)key;
769 - (NSUInteger) count;
770 - (id) objectForKey:(id)key;
771 - (NSEnumerator *) keyEnumerator;
772 - (void) setObject:(id)object forKey:(id)key;
773 - (void) removeObjectForKey:(id)key;
777 @interface CYJSArray : NSArray {
779 JSContextRef context_;
782 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
784 - (NSUInteger) count;
785 - (id) objectAtIndex:(NSUInteger)index;
789 CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
790 CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
792 JSGlobalContextRef CYGetJSContext() {
799 @catch (id error) { \
800 CYThrow(context, error, exception); \
804 void CYThrow(JSContextRef context, JSValueRef value);
806 apr_status_t CYPoolRelease_(void *data) {
807 id object(reinterpret_cast<id>(data));
812 id CYPoolRelease(apr_pool_t *pool, id object) {
815 else if (pool == NULL)
816 return [object autorelease];
818 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
823 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
824 return (CFTypeRef) CYPoolRelease(pool, (id) object);
827 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
828 if (JSValueIsObjectOfClass(context, object, Instance_)) {
829 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
830 return data->GetValue();
833 JSValueRef exception(NULL);
834 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
835 CYThrow(context, exception);
836 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
837 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
840 JSStringRef CYCopyJSString(id value) {
841 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
844 JSStringRef CYCopyJSString(const char *value) {
845 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
848 JSStringRef CYCopyJSString(JSStringRef value) {
849 return value == NULL ? NULL : JSStringRetain(value);
852 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
853 if (JSValueIsNull(context, value))
855 JSValueRef exception(NULL);
856 JSStringRef string(JSValueToStringCopy(context, value, &exception));
857 CYThrow(context, exception);
866 JSStringRelease(string_);
870 CYJSString(const CYJSString &rhs) :
871 string_(CYCopyJSString(rhs.string_))
875 template <typename Arg0_>
876 CYJSString(Arg0_ arg0) :
877 string_(CYCopyJSString(arg0))
881 template <typename Arg0_, typename Arg1_>
882 CYJSString(Arg0_ arg0, Arg1_ arg1) :
883 string_(CYCopyJSString(arg0, arg1))
887 CYJSString &operator =(const CYJSString &rhs) {
889 string_ = CYCopyJSString(rhs.string_);
902 operator JSStringRef() const {
907 CFStringRef CYCopyCFString(JSStringRef value) {
908 return JSStringCopyCFString(kCFAllocatorDefault, value);
911 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
912 return CYCopyCFString(CYJSString(context, value));
915 double CYCastDouble(const char *value, size_t size) {
917 double number(strtod(value, &end));
918 if (end != value + size)
923 double CYCastDouble(const char *value) {
924 return CYCastDouble(value, strlen(value));
927 double CYCastDouble(JSContextRef context, JSValueRef value) {
928 JSValueRef exception(NULL);
929 double number(JSValueToNumber(context, value, &exception));
930 CYThrow(context, exception);
934 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
935 double number(CYCastDouble(context, value));
936 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
939 CFStringRef CYCopyCFString(const char *value) {
940 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
943 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
944 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
947 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
948 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
951 bool CYCastBool(JSContextRef context, JSValueRef value) {
952 return JSValueToBoolean(context, value);
955 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
959 switch (JSType type = JSValueGetType(context, value)) {
960 case kJSTypeUndefined:
961 object = [WebUndefined undefined];
970 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
975 object = CYCopyCFNumber(context, value);
980 object = CYCopyCFString(context, value);
985 // XXX: this might could be more efficient
986 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
991 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
998 return CYPoolRelease(pool, object);
1000 return CFRetain(object);
1003 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1004 return CYCFType(pool, context, value, true);
1007 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1008 return CYCFType(pool, context, value, false);
1011 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1013 size_t size(JSPropertyNameArrayGetCount(names));
1014 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1015 for (size_t index(0); index != size; ++index)
1016 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1020 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1021 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1024 void CYThrow(JSContextRef context, JSValueRef value) {
1027 @throw CYCastNSObject(NULL, context, value);
1030 JSValueRef CYJSNull(JSContextRef context) {
1031 return JSValueMakeNull(context);
1034 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1035 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1038 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1039 return CYCastJSValue(context, CYJSString(value));
1042 JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
1043 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
1046 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1047 JSValueRef exception(NULL);
1048 JSObjectRef object(JSValueToObject(context, value, &exception));
1049 CYThrow(context, exception);
1053 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1054 JSValueRef exception(NULL);
1055 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1056 CYThrow(context, exception);
1060 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1061 JSValueRef exception(NULL);
1062 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1063 CYThrow(context, exception);
1067 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1068 JSValueRef exception(NULL);
1069 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1070 CYThrow(context, exception);
1073 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1074 if (exception == NULL)
1076 *exception = CYCastJSValue(context, error);
1079 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1080 JSValueRef exception(NULL);
1081 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1082 CYThrow(context, exception);
1086 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1087 // XXX: this isn't actually correct
1088 return value != NULL && JSValueIsObject(context, value);
1091 @implementation CYJSObject
1093 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1094 if ((self = [super init]) != nil) {
1100 - (NSObject *) cy$toJSON:(NSString *)key {
1101 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1102 if (!CYIsCallable(context_, toJSON))
1103 return [super cy$toJSON:key];
1105 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1106 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1107 // XXX: do I really want an NSNull here?!
1108 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1112 - (NSString *) cy$toCYON {
1113 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1114 if (!CYIsCallable(context_, toCYON))
1115 return [super cy$toCYON];
1117 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1118 return CYCastNSString(NULL, CYJSString(context_, value));
1122 - (NSUInteger) count {
1123 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1124 size_t size(JSPropertyNameArrayGetCount(names));
1125 JSPropertyNameArrayRelease(names);
1129 - (id) objectForKey:(id)key {
1130 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1133 - (NSEnumerator *) keyEnumerator {
1134 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1135 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1136 JSPropertyNameArrayRelease(names);
1140 - (void) setObject:(id)object forKey:(id)key {
1141 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1144 - (void) removeObjectForKey:(id)key {
1145 JSValueRef exception(NULL);
1146 // XXX: this returns a bool... throw exception, or ignore?
1147 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1148 CYThrow(context_, exception);
1153 @implementation CYJSArray
1155 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1156 if ((self = [super init]) != nil) {
1162 - (NSUInteger) count {
1163 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1166 - (id) objectAtIndex:(NSUInteger)index {
1167 JSValueRef exception(NULL);
1168 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1169 CYThrow(context_, exception);
1170 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1175 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1178 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1179 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
1184 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1185 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
1186 const char *string(CYPoolCString(pool, json));
1192 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1196 NSString *self(CYCastNSObject(pool, context, object));
1197 NSString *name(CYCastNSString(pool, property));
1200 if (NSObject *data = [self cy$getProperty:name])
1201 return CYCastJSValue(context, data);
1204 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1205 PropertyAttributes attributes(property);
1206 SEL sel(sel_registerName(attributes.Getter()));
1207 return CYSendMessage(pool, context, self, sel, 0, NULL, exception);
1214 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1218 NSString *self(CYCastNSObject(pool, context, object));
1219 NSString *name(CYCastNSString(pool, property));
1220 NSString *data(CYCastNSObject(pool, context, value));
1223 if ([self cy$setProperty:name to:data])
1227 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1228 PropertyAttributes attributes(property);
1229 if (const char *setter = attributes.Setter()) {
1230 SEL sel(sel_registerName(setter));
1231 JSValueRef arguments[1] = {value};
1232 CYSendMessage(pool, context, self, sel, 1, arguments, exception);
1241 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1244 NSString *self(CYCastNSObject(NULL, context, object));
1245 NSString *name(CYCastNSString(NULL, property));
1246 return [self cy$deleteProperty:name];
1251 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1253 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
1254 return CYMakeInstance(context, [data->GetValue() alloc], true);
1258 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1259 Selector_privateData *data(new Selector_privateData(sel));
1260 return JSObjectMake(context, Selector_, data);
1263 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
1264 Pointer_privateData *data(new Pointer_privateData(pointer));
1265 return JSObjectMake(context, Pointer_, data);
1268 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1269 Functor_privateData *data(new Functor_privateData(type, function));
1270 return JSObjectMake(context, Functor_, data);
1273 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1275 const char *string([CYCastNSString(NULL, value) UTF8String]);
1277 *length = strlen(string);
1280 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1281 char *string(new(pool) char[size]);
1282 JSStringGetUTF8CString(value, string, size);
1283 // XXX: this is ironic
1285 *length = strlen(string);
1290 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1291 if (!JSValueIsNull(context, value))
1292 return CYPoolCString(pool, CYJSString(context, value), length);
1300 // XXX: this macro is unhygenic
1301 #define CYCastCString(context, value) ({ \
1303 if (value == NULL) \
1305 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1306 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1307 utf8 = reinterpret_cast<char *>(alloca(size)); \
1308 JSStringGetUTF8CString(string, utf8, size); \
1309 JSStringRelease(string); \
1315 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1316 switch (JSValueGetType(context, value)) {
1319 /*case kJSTypeString:
1320 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1322 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1323 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1324 return data->value_;
1327 double number(CYCastDouble(context, value));
1328 if (std::isnan(number))
1329 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1330 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1334 template <typename Type_>
1335 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1336 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1339 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1340 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1341 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1342 return reinterpret_cast<SEL>(data->value_);
1344 return CYCastPointer<SEL>(context, value);
1347 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1348 switch (type->primitive) {
1349 case sig::boolean_P:
1350 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1353 #define CYPoolFFI_(primitive, native) \
1354 case sig::primitive ## _P: \
1355 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1358 CYPoolFFI_(uchar, unsigned char)
1359 CYPoolFFI_(char, char)
1360 CYPoolFFI_(ushort, unsigned short)
1361 CYPoolFFI_(short, short)
1362 CYPoolFFI_(ulong, unsigned long)
1363 CYPoolFFI_(long, long)
1364 CYPoolFFI_(uint, unsigned int)
1365 CYPoolFFI_(int, int)
1366 CYPoolFFI_(ulonglong, unsigned long long)
1367 CYPoolFFI_(longlong, long long)
1368 CYPoolFFI_(float, float)
1369 CYPoolFFI_(double, double)
1372 case sig::typename_P:
1373 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1376 case sig::selector_P:
1377 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1380 case sig::pointer_P:
1381 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1385 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1388 case sig::struct_P: {
1389 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1390 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1391 for (size_t index(0); index != type->data.signature.count; ++index) {
1392 sig::Element *element(&type->data.signature.elements[index]);
1393 ffi_type *field(ffi->elements[index]);
1396 if (aggregate == NULL)
1399 rhs = CYGetProperty(context, aggregate, index);
1400 if (JSValueIsUndefined(context, rhs)) {
1401 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1402 if (JSValueIsUndefined(context, rhs))
1403 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1407 CYPoolFFI(pool, context, element->type, field, base, rhs);
1409 base += field->size;
1417 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1422 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
1425 switch (type->primitive) {
1426 case sig::boolean_P:
1427 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1430 #define CYFromFFI_(primitive, native) \
1431 case sig::primitive ## _P: \
1432 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1435 CYFromFFI_(uchar, unsigned char)
1436 CYFromFFI_(char, char)
1437 CYFromFFI_(ushort, unsigned short)
1438 CYFromFFI_(short, short)
1439 CYFromFFI_(ulong, unsigned long)
1440 CYFromFFI_(long, long)
1441 CYFromFFI_(uint, unsigned int)
1442 CYFromFFI_(int, int)
1443 CYFromFFI_(ulonglong, unsigned long long)
1444 CYFromFFI_(longlong, long long)
1445 CYFromFFI_(float, float)
1446 CYFromFFI_(double, double)
1449 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
1452 case sig::typename_P:
1453 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1456 case sig::selector_P:
1457 if (SEL sel = *reinterpret_cast<SEL *>(data))
1458 value = CYMakeSelector(context, sel);
1462 case sig::pointer_P:
1463 if (void *pointer = *reinterpret_cast<void **>(data))
1464 value = CYMakePointer(context, pointer);
1469 if (char *utf8 = *reinterpret_cast<char **>(data))
1470 value = CYCastJSValue(context, utf8);
1475 value = CYMakeStruct(context, data, type, ffi, owner);
1479 value = CYJSUndefined(context);
1483 value = CYJSNull(context);
1487 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1494 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1495 Type_privateData *typical(internal->type_);
1498 const char *name(CYPoolCString(pool, property, &length));
1499 double number(CYCastDouble(name, length));
1501 size_t count(typical->type_.data.signature.count);
1503 if (std::isnan(number)) {
1504 if (property == NULL)
1507 sig::Element *elements(typical->type_.data.signature.elements);
1509 for (size_t local(0); local != count; ++local)
1510 if (strcmp(name, elements[local].name) == 0) {
1517 index = static_cast<ssize_t>(number);
1518 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1523 base = reinterpret_cast<uint8_t *>(internal->value_);
1524 for (ssize_t local(0); local != index; ++local)
1525 base += typical->ffi_.elements[local]->size;
1530 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1532 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1533 Type_privateData *typical(internal->type_);
1538 if (!Index_(pool, internal, property, index, base))
1542 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
1546 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1548 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1549 Type_privateData *typical(internal->type_);
1554 if (!Index_(pool, internal, property, index, base))
1558 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1563 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1564 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1565 Type_privateData *typical(internal->type_);
1567 size_t count(typical->type_.data.signature.count);
1568 sig::Element *elements(typical->type_.data.signature.elements);
1570 for (size_t index(0); index != count; ++index)
1571 JSPropertyNameAccumulatorAddName(names, CYJSString(elements[index].name));
1574 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)()) {
1576 if (setups + count != signature->count - 1)
1577 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1579 size_t size(setups + count);
1581 memcpy(values, setup, sizeof(void *) * setups);
1583 for (size_t index(setups); index != size; ++index) {
1584 sig::Element *element(&signature->elements[index + 1]);
1585 ffi_type *ffi(cif->arg_types[index]);
1587 values[index] = new(pool) uint8_t[ffi->size];
1588 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1591 uint8_t value[cif->rtype->size];
1592 ffi_call(cif, function, value, values);
1594 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
1598 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1599 ffoData *data(reinterpret_cast<ffoData *>(arg));
1601 JSContextRef context(data->context_);
1603 size_t count(data->cif_.nargs);
1604 JSValueRef values[count];
1606 for (size_t index(0); index != count; ++index)
1607 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1609 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1610 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1613 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1614 // XXX: in case of exceptions this will leak
1615 ffoData *data(new ffoData(type));
1617 ffi_closure *closure;
1618 _syscall(closure = (ffi_closure *) mmap(
1619 NULL, sizeof(ffi_closure),
1620 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1624 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1625 _assert(status == FFI_OK);
1627 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1629 data->value_ = closure;
1631 data->context_ = CYGetJSContext();
1632 data->function_ = function;
1634 return JSObjectMake(context, Functor_, data);
1637 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1640 NSString *name(CYCastNSString(pool, property));
1641 if (Class _class = NSClassFromString(name))
1642 return CYMakeInstance(context, _class, true);
1643 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1644 switch ([[entry objectAtIndex:0] intValue]) {
1646 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1648 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1650 // XXX: this is horrendously inefficient
1651 sig::Signature signature;
1652 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
1654 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1655 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
1661 bool stret(ffi_type *ffi_type) {
1662 return ffi_type->type == FFI_TYPE_STRUCT && (
1663 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1664 struct_forward_array[ffi_type->size] != 0
1669 int *_NSGetArgc(void);
1670 char ***_NSGetArgv(void);
1671 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1674 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1676 NSLog(@"%s", CYCastCString(context, arguments[0]));
1677 return CYJSUndefined(context);
1681 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1684 NSString *name(CYCastNSObject(pool, context, arguments[0]));
1685 int argc(*_NSGetArgc());
1686 char **argv(*_NSGetArgv());
1687 for (int i(0); i != argc; ++i)
1688 NSLog(@"argv[%i]=%s", i, argv[i]);
1690 return CYCastJSValue(context, UIApplicationMain(argc, argv, name, name));
1694 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1697 Class _class(object_getClass(self));
1698 if (Method method = class_getInstanceMethod(_class, _cmd))
1699 type = method_getTypeEncoding(method);
1702 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1704 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1705 type = CYPoolCString(pool, [method _typeString]);
1713 sig::Signature signature;
1714 sig::Parse(pool, &signature, type, &Structor_);
1717 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1719 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1720 return CYCallFunction(pool, context, 2, setup, count, arguments, exception, &signature, &cif, function);
1723 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1731 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1733 self = CYCastNSObject(pool, context, arguments[0]);
1735 return CYJSNull(context);
1737 _cmd = CYCastSEL(context, arguments[1]);
1740 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, exception);
1743 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1744 JSValueRef setup[count + 2];
1747 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
1748 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1751 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1753 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1754 return CYCallFunction(pool, context, 0, NULL, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1757 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1760 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1761 const char *name(CYCastCString(context, arguments[0]));
1762 return CYMakeSelector(context, sel_registerName(name));
1766 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1769 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1770 const char *type(CYCastCString(context, arguments[1]));
1771 JSValueRef exception(NULL);
1772 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1773 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1774 return CYMakeFunctor(context, function, type);
1775 } else if (exception != NULL) {
1778 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1779 return CYMakeFunctor(context, function, type);
1784 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1785 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
1786 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1789 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1793 static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1795 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1796 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1800 static JSValueRef Pointer_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1801 return Pointer_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1804 static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1806 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1808 sprintf(string, "%p", data->value_);
1809 return CYCastJSValue(context, string);
1813 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1815 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1817 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
1822 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1824 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1826 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
1827 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
1832 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1834 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1836 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
1841 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1843 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1844 return CYCastJSValue(context, sel_getName(data->GetValue()));
1848 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1849 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
1852 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1854 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1855 const char *name(sel_getName(data->GetValue()));
1857 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
1862 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1865 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1867 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1868 Class _class(CYCastNSObject(pool, context, arguments[0]));
1869 bool instance(CYCastBool(context, arguments[1]));
1870 SEL sel(data->GetValue());
1871 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1872 return CYCastJSValue(context, method_getTypeEncoding(method));
1873 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1874 return CYCastJSValue(context, CYJSString(type));
1876 return CYJSNull(context);
1880 static JSStaticValue Pointer_staticValues[2] = {
1881 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1882 {NULL, NULL, NULL, 0}
1885 static JSStaticFunction Pointer_staticFunctions[4] = {
1886 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1887 {"toJSON", &Pointer_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1888 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1892 /*static JSStaticValue Selector_staticValues[2] = {
1893 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1894 {NULL, NULL, NULL, 0}
1897 static JSStaticFunction Instance_staticFunctions[4] = {
1898 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1899 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1900 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1904 static JSStaticFunction Selector_staticFunctions[5] = {
1905 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1906 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1907 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1908 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1912 CYDriver::CYDriver(const std::string &filename) :
1916 filename_(filename),
1922 CYDriver::~CYDriver() {
1926 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1927 CYDriver::Error error;
1928 error.location_ = location;
1929 error.message_ = message;
1930 driver.errors_.push_back(error);
1933 void CYSetArgs(int argc, const char *argv[]) {
1934 JSContextRef context(CYGetJSContext());
1935 JSValueRef args[argc];
1936 for (int i(0); i != argc; ++i)
1937 args[i] = CYCastJSValue(context, argv[i]);
1938 JSValueRef exception(NULL);
1939 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1940 CYThrow(context, exception);
1941 CYSetProperty(context, System_, CYJSString("args"), array);
1944 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1945 return JSContextGetGlobalObject(context);
1948 MSInitialize { _pooled
1951 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1953 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1955 JSClassDefinition definition;
1957 definition = kJSClassDefinitionEmpty;
1958 definition.className = "Pointer";
1959 definition.staticValues = Pointer_staticValues;
1960 definition.staticFunctions = Pointer_staticFunctions;
1961 definition.finalize = &CYData::Finalize;
1962 Pointer_ = JSClassCreate(&definition);
1964 definition = kJSClassDefinitionEmpty;
1965 definition.className = "Functor";
1966 definition.staticValues = Pointer_staticValues;
1967 definition.staticFunctions = Pointer_staticFunctions;
1968 definition.callAsFunction = &Functor_callAsFunction;
1969 definition.finalize = &CYData::Finalize;
1970 Functor_ = JSClassCreate(&definition);
1972 definition = kJSClassDefinitionEmpty;
1973 definition.className = "Struct";
1974 definition.getProperty = &Struct_getProperty;
1975 definition.setProperty = &Struct_setProperty;
1976 definition.getPropertyNames = &Struct_getPropertyNames;
1977 definition.finalize = &CYData::Finalize;
1978 Struct_ = JSClassCreate(&definition);
1980 definition = kJSClassDefinitionEmpty;
1981 definition.className = "Selector";
1982 definition.staticValues = Pointer_staticValues;
1983 //definition.staticValues = Selector_staticValues;
1984 definition.staticFunctions = Selector_staticFunctions;
1985 definition.callAsFunction = &Selector_callAsFunction;
1986 definition.finalize = &CYData::Finalize;
1987 Selector_ = JSClassCreate(&definition);
1989 definition = kJSClassDefinitionEmpty;
1990 definition.className = "Instance";
1991 definition.staticValues = Pointer_staticValues;
1992 definition.staticFunctions = Instance_staticFunctions;
1993 definition.getProperty = &Instance_getProperty;
1994 definition.setProperty = &Instance_setProperty;
1995 definition.deleteProperty = &Instance_deleteProperty;
1996 definition.callAsConstructor = &Instance_callAsConstructor;
1997 definition.finalize = &CYData::Finalize;
1998 Instance_ = JSClassCreate(&definition);
2000 definition = kJSClassDefinitionEmpty;
2001 definition.className = "Runtime";
2002 definition.getProperty = &Runtime_getProperty;
2003 Runtime_ = JSClassCreate(&definition);
2005 definition = kJSClassDefinitionEmpty;
2006 //definition.getProperty = &Global_getProperty;
2007 JSClassRef Global(JSClassCreate(&definition));
2009 JSGlobalContextRef context(JSGlobalContextCreate(Global));
2012 JSObjectRef global(CYGetGlobalObject(context));
2014 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
2015 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
2017 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
2018 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
2020 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
2021 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2023 System_ = JSObjectMake(context, NULL, NULL);
2024 CYSetProperty(context, global, CYJSString("system"), System_);
2025 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
2026 //CYSetProperty(context, System_, CYJSString("global"), global);
2028 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2030 length_ = JSStringCreateWithUTF8CString("length");
2031 message_ = JSStringCreateWithUTF8CString("message");
2032 name_ = JSStringCreateWithUTF8CString("name");
2033 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2034 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
2036 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2037 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));