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 Functor_privateData :
163 sig::Signature signature_;
166 Functor_privateData(const char *type, void (*value)()) :
167 Pointer_privateData(reinterpret_cast<void *>(value))
169 sig::Parse(pool_, &signature_, type);
170 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
177 JSContextRef context_;
178 JSObjectRef function_;
180 ffoData(const char *type) :
181 Functor_privateData(type, NULL)
186 struct Selector_privateData : Pointer_privateData {
187 Selector_privateData(SEL value) :
188 Pointer_privateData(value)
192 SEL GetValue() const {
193 return reinterpret_cast<SEL>(value_);
197 struct Instance_privateData :
202 Instance_privateData(id value, bool transient) :
203 Pointer_privateData(value)
207 virtual ~Instance_privateData() {
209 [GetValue() release];
212 id GetValue() const {
213 return reinterpret_cast<id>(value_);
219 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
221 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
222 lhs.name = apr_pstrdup(pool, rhs.name);
223 if (rhs.type == NULL)
226 lhs.type = new(pool) Type;
227 Copy(pool, *lhs.type, *rhs.type);
229 lhs.offset = rhs.offset;
232 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
233 size_t count(rhs.count);
235 lhs.elements = new(pool) Element[count];
236 for (size_t index(0); index != count; ++index)
237 Copy(pool, lhs.elements[index], rhs.elements[index]);
240 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
241 lhs.primitive = rhs.primitive;
242 lhs.name = apr_pstrdup(pool, rhs.name);
243 lhs.flags = rhs.flags;
245 if (sig::IsAggregate(rhs.primitive))
246 Copy(pool, lhs.data.signature, rhs.data.signature);
248 if (rhs.data.data.type != NULL) {
249 lhs.data.data.type = new(pool) Type;
250 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
253 lhs.data.data.size = rhs.data.data.size;
257 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
259 lhs.alignment = rhs.alignment;
261 if (rhs.elements == NULL)
265 while (rhs.elements[count] != NULL)
268 lhs.elements = new(pool) ffi_type *[count + 1];
269 lhs.elements[count] = NULL;
271 for (size_t index(0); index != count; ++index) {
272 // XXX: if these are libffi native then you can just take them
273 ffi_type *ffi(new(pool) ffi_type);
274 lhs.elements[index] = ffi;
275 sig::Copy(pool, *ffi, *rhs.elements[index]);
282 struct Type_privateData {
286 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) {
287 sig::Copy(pool, type_, *type);
288 sig::Copy(pool, ffi_, *ffi);
292 struct Struct_privateData :
296 Type_privateData *type_;
298 Struct_privateData() {
302 struct CStringMapLess :
303 std::binary_function<const char *, const char *, bool>
305 _finline bool operator ()(const char *lhs, const char *rhs) const {
306 return strcmp(lhs, rhs) < 0;
310 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
311 static TypeMap Types_;
313 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
314 Struct_privateData *internal(new Struct_privateData());
315 apr_pool_t *pool(internal->pool_);
316 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
317 internal->type_ = typical;
320 internal->owner_ = owner;
321 internal->value_ = data;
323 internal->owner_ = NULL;
325 size_t size(typical->ffi_.size);
326 void *copy(apr_palloc(internal->pool_, size));
327 memcpy(copy, data, size);
328 internal->value_ = copy;
331 return JSObjectMake(context, Struct_, internal);
334 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
336 object = [object retain];
337 Instance_privateData *data(new Instance_privateData(object, transient));
338 return JSObjectMake(context, Instance_, data);
341 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
343 return [value UTF8String];
345 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
346 char *string(new(pool) char[size]);
347 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
348 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
353 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
354 return JSValueMakeBoolean(context, value);
357 JSValueRef CYCastJSValue(JSContextRef context, double value) {
358 return JSValueMakeNumber(context, value);
361 #define CYCastJSValue_(Type_) \
362 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
363 return JSValueMakeNumber(context, static_cast<double>(value)); \
367 CYCastJSValue_(unsigned int)
368 CYCastJSValue_(long int)
369 CYCastJSValue_(long unsigned int)
370 CYCastJSValue_(long long int)
371 CYCastJSValue_(long long unsigned int)
373 JSValueRef CYJSUndefined(JSContextRef context) {
374 return JSValueMakeUndefined(context);
377 @interface NSMethodSignature (Cycript)
378 - (NSString *) _typeString;
381 @interface NSObject (Cycript)
383 - (JSType) cy$JSType;
385 - (NSObject *) cy$toJSON:(NSString *)key;
386 - (NSString *) cy$toCYON;
388 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
390 - (NSObject *) cy$getProperty:(NSString *)name;
391 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
392 - (bool) cy$deleteProperty:(NSString *)name;
396 @interface NSString (Cycript)
397 - (void *) cy$symbol;
400 @interface NSNumber (Cycript)
401 - (void *) cy$symbol;
404 struct PropertyAttributes {
409 const char *variable;
422 PropertyAttributes(objc_property_t property) :
434 name = property_getName(property);
435 const char *attributes(property_getAttributes(property));
437 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
439 case 'R': readonly = true; break;
440 case 'C': copy = true; break;
441 case '&': retain = true; break;
442 case 'N': nonatomic = true; break;
443 case 'G': getter_ = token + 1; break;
444 case 'S': setter_ = token + 1; break;
445 case 'V': variable = token + 1; break;
449 /*if (variable == NULL) {
450 variable = property_getName(property);
451 size_t size(strlen(variable));
452 char *name(new(pool_) char[size + 2]);
454 memcpy(name + 1, variable, size);
455 name[size + 1] = '\0';
460 const char *Getter() {
462 getter_ = apr_pstrdup(pool_, name);
466 const char *Setter() {
467 if (setter_ == NULL && !readonly) {
468 size_t length(strlen(name));
470 char *temp(new(pool_) char[length + 5]);
476 temp[3] = toupper(name[0]);
477 memcpy(temp + 4, name + 1, length - 1);
480 temp[length + 3] = ':';
481 temp[length + 4] = '\0';
490 @implementation NSObject (Cycript)
492 - (JSType) cy$JSType {
493 return kJSTypeObject;
496 - (NSObject *) cy$toJSON:(NSString *)key {
497 return [self description];
500 - (NSString *) cy$toCYON {
501 return [[self cy$toJSON:@""] cy$toCYON];
504 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
505 return CYMakeInstance(context, self, transient);
508 - (NSObject *) cy$getProperty:(NSString *)name {
509 /*if (![name isEqualToString:@"prototype"])
510 NSLog(@"get:%@", name);*/
514 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
515 //NSLog(@"set:%@", name);
519 - (bool) cy$deleteProperty:(NSString *)name {
520 //NSLog(@"delete:%@", name);
526 @implementation WebUndefined (Cycript)
528 - (JSType) cy$JSType {
529 return kJSTypeUndefined;
532 - (NSObject *) cy$toJSON:(NSString *)key {
536 - (NSString *) cy$toCYON {
540 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
541 return CYJSUndefined(context);
546 @implementation NSNull (Cycript)
548 - (JSType) cy$JSType {
552 - (NSObject *) cy$toJSON:(NSString *)key {
556 - (NSString *) cy$toCYON {
562 @implementation NSArray (Cycript)
564 - (NSString *) cy$toCYON {
565 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
566 [json appendString:@"["];
569 for (id object in self) {
571 [json appendString:@","];
574 if ([object cy$JSType] != kJSTypeUndefined)
575 [json appendString:[object cy$toCYON]];
577 [json appendString:@","];
582 [json appendString:@"]"];
586 - (NSObject *) cy$getProperty:(NSString *)name {
587 if ([name isEqualToString:@"length"])
588 return [NSNumber numberWithUnsignedInteger:[self count]];
590 int index([name intValue]);
591 if (index < 0 || index >= static_cast<int>([self count]))
592 return [super cy$getProperty:name];
594 return [self objectAtIndex:index];
599 @implementation NSMutableArray (Cycript)
601 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
602 int index([name intValue]);
603 if (index < 0 || index >= static_cast<int>([self count]))
604 return [super cy$setProperty:name to:value];
606 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
611 - (bool) cy$deleteProperty:(NSString *)name {
612 int index([name intValue]);
613 if (index < 0 || index >= static_cast<int>([self count]))
614 return [super cy$deleteProperty:name];
616 [self removeObjectAtIndex:index];
623 @implementation NSDictionary (Cycript)
625 - (NSString *) cy$toCYON {
626 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
627 [json appendString:@"({"];
630 for (id key in self) {
632 [json appendString:@","];
635 [json appendString:[key cy$toCYON]];
636 [json appendString:@":"];
637 NSObject *object([self objectForKey:key]);
638 [json appendString:[object cy$toCYON]];
641 [json appendString:@"})"];
645 - (NSObject *) cy$getProperty:(NSString *)name {
646 return [self objectForKey:name];
651 @implementation NSMutableDictionary (Cycript)
653 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
654 [self setObject:(value ?: [NSNull null]) forKey:name];
658 - (bool) cy$deleteProperty:(NSString *)name {
659 if ([self objectForKey:name] == nil)
662 [self removeObjectForKey:name];
669 @implementation NSNumber (Cycript)
671 - (JSType) cy$JSType {
672 // XXX: this just seems stupid
673 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
676 - (NSObject *) cy$toJSON:(NSString *)key {
680 - (NSString *) cy$toCYON {
681 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
684 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
685 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
688 - (void *) cy$symbol {
689 return [self pointerValue];
694 @implementation NSString (Cycript)
696 - (JSType) cy$JSType {
697 return kJSTypeString;
700 - (NSObject *) cy$toJSON:(NSString *)key {
704 - (NSString *) cy$toCYON {
705 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
707 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
708 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
709 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
710 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
711 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
713 CFStringInsert(json, 0, CFSTR("\""));
714 CFStringAppend(json, CFSTR("\""));
716 return [reinterpret_cast<const NSString *>(json) autorelease];
719 - (void *) cy$symbol {
721 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
726 @interface CYJSObject : NSDictionary {
728 JSContextRef context_;
731 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
733 - (NSString *) cy$toJSON:(NSString *)key;
735 - (NSUInteger) count;
736 - (id) objectForKey:(id)key;
737 - (NSEnumerator *) keyEnumerator;
738 - (void) setObject:(id)object forKey:(id)key;
739 - (void) removeObjectForKey:(id)key;
743 @interface CYJSArray : NSArray {
745 JSContextRef context_;
748 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
750 - (NSUInteger) count;
751 - (id) objectAtIndex:(NSUInteger)index;
755 CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
756 CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
758 JSGlobalContextRef CYGetJSContext() {
765 @catch (id error) { \
766 CYThrow(context, error, exception); \
770 void CYThrow(JSContextRef context, JSValueRef value);
772 apr_status_t CYPoolRelease_(void *data) {
773 id object(reinterpret_cast<id>(data));
778 id CYPoolRelease(apr_pool_t *pool, id object) {
781 else if (pool == NULL)
782 return [object autorelease];
784 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
789 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
790 return (CFTypeRef) CYPoolRelease(pool, (id) object);
793 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
794 if (JSValueIsObjectOfClass(context, object, Instance_)) {
795 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
796 return data->GetValue();
799 JSValueRef exception(NULL);
800 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
801 CYThrow(context, exception);
802 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
803 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
806 JSStringRef CYCopyJSString(id value) {
807 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
810 JSStringRef CYCopyJSString(const char *value) {
811 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
814 JSStringRef CYCopyJSString(JSStringRef value) {
815 return value == NULL ? NULL : JSStringRetain(value);
818 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
819 if (JSValueIsNull(context, value))
821 JSValueRef exception(NULL);
822 JSStringRef string(JSValueToStringCopy(context, value, &exception));
823 CYThrow(context, exception);
832 JSStringRelease(string_);
836 CYJSString(const CYJSString &rhs) :
837 string_(CYCopyJSString(rhs.string_))
841 template <typename Arg0_>
842 CYJSString(Arg0_ arg0) :
843 string_(CYCopyJSString(arg0))
847 template <typename Arg0_, typename Arg1_>
848 CYJSString(Arg0_ arg0, Arg1_ arg1) :
849 string_(CYCopyJSString(arg0, arg1))
853 CYJSString &operator =(const CYJSString &rhs) {
855 string_ = CYCopyJSString(rhs.string_);
868 operator JSStringRef() const {
873 CFStringRef CYCopyCFString(JSStringRef value) {
874 return JSStringCopyCFString(kCFAllocatorDefault, value);
877 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
878 return CYCopyCFString(CYJSString(context, value));
881 double CYCastDouble(const char *value, size_t size) {
883 double number(strtod(value, &end));
884 if (end != value + size)
889 double CYCastDouble(const char *value) {
890 return CYCastDouble(value, strlen(value));
893 double CYCastDouble(JSContextRef context, JSValueRef value) {
894 JSValueRef exception(NULL);
895 double number(JSValueToNumber(context, value, &exception));
896 CYThrow(context, exception);
900 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
901 double number(CYCastDouble(context, value));
902 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
905 CFStringRef CYCopyCFString(const char *value) {
906 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
909 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
910 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
913 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
914 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
917 bool CYCastBool(JSContextRef context, JSValueRef value) {
918 return JSValueToBoolean(context, value);
921 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
925 switch (JSType type = JSValueGetType(context, value)) {
926 case kJSTypeUndefined:
927 object = [WebUndefined undefined];
936 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
941 object = CYCopyCFNumber(context, value);
946 object = CYCopyCFString(context, value);
951 // XXX: this might could be more efficient
952 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
957 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
964 return CYPoolRelease(pool, object);
966 return CFRetain(object);
969 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
970 return CYCFType(pool, context, value, true);
973 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
974 return CYCFType(pool, context, value, false);
977 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
979 size_t size(JSPropertyNameArrayGetCount(names));
980 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
981 for (size_t index(0); index != size; ++index)
982 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
986 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
987 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
990 void CYThrow(JSContextRef context, JSValueRef value) {
993 @throw CYCastNSObject(NULL, context, value);
996 JSValueRef CYJSNull(JSContextRef context) {
997 return JSValueMakeNull(context);
1000 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1001 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1004 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1005 return CYCastJSValue(context, CYJSString(value));
1008 JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
1009 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
1012 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1013 JSValueRef exception(NULL);
1014 JSObjectRef object(JSValueToObject(context, value, &exception));
1015 CYThrow(context, exception);
1019 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1020 JSValueRef exception(NULL);
1021 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1022 CYThrow(context, exception);
1026 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1027 JSValueRef exception(NULL);
1028 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1029 CYThrow(context, exception);
1033 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1034 JSValueRef exception(NULL);
1035 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1036 CYThrow(context, exception);
1039 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1040 if (exception == NULL)
1042 *exception = CYCastJSValue(context, error);
1045 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1046 JSValueRef exception(NULL);
1047 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1048 CYThrow(context, exception);
1052 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1053 // XXX: this isn't actually correct
1054 return value != NULL && JSValueIsObject(context, value);
1057 @implementation CYJSObject
1059 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1060 if ((self = [super init]) != nil) {
1066 - (NSObject *) cy$toJSON:(NSString *)key {
1067 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1068 if (!CYIsCallable(context_, toJSON))
1069 return [super cy$toJSON:key];
1071 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1072 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1073 // XXX: do I really want an NSNull here?!
1074 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1078 - (NSString *) cy$toCYON {
1079 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1080 if (!CYIsCallable(context_, toCYON))
1081 return [super cy$toCYON];
1083 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1084 return CYCastNSString(NULL, CYJSString(context_, value));
1088 - (NSUInteger) count {
1089 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1090 size_t size(JSPropertyNameArrayGetCount(names));
1091 JSPropertyNameArrayRelease(names);
1095 - (id) objectForKey:(id)key {
1096 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1099 - (NSEnumerator *) keyEnumerator {
1100 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1101 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1102 JSPropertyNameArrayRelease(names);
1106 - (void) setObject:(id)object forKey:(id)key {
1107 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1110 - (void) removeObjectForKey:(id)key {
1111 JSValueRef exception(NULL);
1112 // XXX: this returns a bool... throw exception, or ignore?
1113 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1114 CYThrow(context_, exception);
1119 @implementation CYJSArray
1121 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1122 if ((self = [super init]) != nil) {
1128 - (NSUInteger) count {
1129 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1132 - (id) objectAtIndex:(NSUInteger)index {
1133 JSValueRef exception(NULL);
1134 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1135 CYThrow(context_, exception);
1136 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1141 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1144 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1145 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
1150 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1151 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
1152 const char *string(CYPoolCString(pool, json));
1158 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1162 NSString *self(CYCastNSObject(pool, context, object));
1163 NSString *name(CYCastNSString(pool, property));
1166 if (NSObject *data = [self cy$getProperty:name])
1167 return CYCastJSValue(context, data);
1170 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1171 PropertyAttributes attributes(property);
1172 SEL sel(sel_registerName(attributes.Getter()));
1173 return CYSendMessage(pool, context, self, sel, 0, NULL, exception);
1180 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1184 NSString *self(CYCastNSObject(pool, context, object));
1185 NSString *name(CYCastNSString(pool, property));
1186 NSString *data(CYCastNSObject(pool, context, value));
1189 if ([self cy$setProperty:name to:data])
1193 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1194 PropertyAttributes attributes(property);
1195 if (const char *setter = attributes.Setter()) {
1196 SEL sel(sel_registerName(setter));
1197 JSValueRef arguments[1] = {value};
1198 CYSendMessage(pool, context, self, sel, 1, arguments, exception);
1207 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1210 NSString *self(CYCastNSObject(NULL, context, object));
1211 NSString *name(CYCastNSString(NULL, property));
1212 return [self cy$deleteProperty:name];
1217 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1219 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
1220 return CYMakeInstance(context, [data->GetValue() alloc], true);
1224 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1225 Selector_privateData *data(new Selector_privateData(sel));
1226 return JSObjectMake(context, Selector_, data);
1229 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
1230 Pointer_privateData *data(new Pointer_privateData(pointer));
1231 return JSObjectMake(context, Pointer_, data);
1234 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1235 Functor_privateData *data(new Functor_privateData(type, function));
1236 return JSObjectMake(context, Functor_, data);
1239 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1241 const char *string([CYCastNSString(NULL, value) UTF8String]);
1243 *length = strlen(string);
1246 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1247 char *string(new(pool) char[size]);
1248 JSStringGetUTF8CString(value, string, size);
1249 // XXX: this is ironic
1251 *length = strlen(string);
1256 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1257 if (!JSValueIsNull(context, value))
1258 return CYPoolCString(pool, CYJSString(context, value), length);
1266 // XXX: this macro is unhygenic
1267 #define CYCastCString(context, value) ({ \
1269 if (value == NULL) \
1271 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1272 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1273 utf8 = reinterpret_cast<char *>(alloca(size)); \
1274 JSStringGetUTF8CString(string, utf8, size); \
1275 JSStringRelease(string); \
1281 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1282 switch (JSValueGetType(context, value)) {
1285 /*case kJSTypeString:
1286 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1288 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1289 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1290 return data->value_;
1293 double number(CYCastDouble(context, value));
1294 if (std::isnan(number))
1295 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1296 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1300 template <typename Type_>
1301 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1302 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1305 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1306 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1307 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1308 return reinterpret_cast<SEL>(data->value_);
1310 return CYCastPointer<SEL>(context, value);
1313 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1314 switch (type->primitive) {
1315 case sig::boolean_P:
1316 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1319 #define CYPoolFFI_(primitive, native) \
1320 case sig::primitive ## _P: \
1321 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1324 CYPoolFFI_(uchar, unsigned char)
1325 CYPoolFFI_(char, char)
1326 CYPoolFFI_(ushort, unsigned short)
1327 CYPoolFFI_(short, short)
1328 CYPoolFFI_(ulong, unsigned long)
1329 CYPoolFFI_(long, long)
1330 CYPoolFFI_(uint, unsigned int)
1331 CYPoolFFI_(int, int)
1332 CYPoolFFI_(ulonglong, unsigned long long)
1333 CYPoolFFI_(longlong, long long)
1334 CYPoolFFI_(float, float)
1335 CYPoolFFI_(double, double)
1338 case sig::typename_P:
1339 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1342 case sig::selector_P:
1343 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1346 case sig::pointer_P:
1347 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1351 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1354 case sig::struct_P: {
1355 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1356 bool aggregate(JSValueIsObject(context, value));
1357 for (size_t index(0); index != type->data.signature.count; ++index) {
1358 ffi_type *element(ffi->elements[index]);
1359 JSValueRef rhs(aggregate ? CYGetProperty(context, (JSObjectRef) value, index) : value);
1360 CYPoolFFI(pool, context, type->data.signature.elements[index].type, element, base, rhs);
1362 base += element->size;
1370 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1375 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
1378 switch (type->primitive) {
1379 case sig::boolean_P:
1380 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1383 #define CYFromFFI_(primitive, native) \
1384 case sig::primitive ## _P: \
1385 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1388 CYFromFFI_(uchar, unsigned char)
1389 CYFromFFI_(char, char)
1390 CYFromFFI_(ushort, unsigned short)
1391 CYFromFFI_(short, short)
1392 CYFromFFI_(ulong, unsigned long)
1393 CYFromFFI_(long, long)
1394 CYFromFFI_(uint, unsigned int)
1395 CYFromFFI_(int, int)
1396 CYFromFFI_(ulonglong, unsigned long long)
1397 CYFromFFI_(longlong, long long)
1398 CYFromFFI_(float, float)
1399 CYFromFFI_(double, double)
1402 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
1405 case sig::typename_P:
1406 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1409 case sig::selector_P:
1410 if (SEL sel = *reinterpret_cast<SEL *>(data))
1411 value = CYMakeSelector(context, sel);
1415 case sig::pointer_P:
1416 if (void *pointer = *reinterpret_cast<void **>(data))
1417 value = CYMakePointer(context, pointer);
1422 if (char *utf8 = *reinterpret_cast<char **>(data))
1423 value = CYCastJSValue(context, utf8);
1428 value = CYMakeStruct(context, data, type, ffi, owner);
1432 value = CYJSUndefined(context);
1436 value = CYJSNull(context);
1440 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1447 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1448 Type_privateData *typical(internal->type_);
1451 const char *name(CYPoolCString(pool, property, &length));
1452 double number(CYCastDouble(name, length));
1454 if (std::isnan(number)) {
1455 if (property == NULL)
1461 index = static_cast<ssize_t>(number);
1462 if (index != number || index < 0 || static_cast<size_t>(index) >= typical->type_.data.signature.count)
1466 base = reinterpret_cast<uint8_t *>(internal->value_);
1467 for (ssize_t local(0); local != index; ++local)
1468 base += typical->ffi_.elements[local]->size;
1473 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1476 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1477 Type_privateData *typical(internal->type_);
1482 if (!Index_(pool, internal, property, index, base))
1485 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
1489 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1492 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1493 Type_privateData *typical(internal->type_);
1498 if (!Index_(pool, internal, property, index, base))
1501 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1506 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)()) {
1508 if (setups + count != signature->count - 1)
1509 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1511 size_t size(setups + count);
1513 memcpy(values, setup, sizeof(void *) * setups);
1515 for (size_t index(setups); index != size; ++index) {
1516 sig::Element *element(&signature->elements[index + 1]);
1517 ffi_type *ffi(cif->arg_types[index]);
1519 values[index] = new(pool) uint8_t[ffi->size];
1520 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1523 uint8_t value[cif->rtype->size];
1524 ffi_call(cif, function, value, values);
1526 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
1530 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1531 ffoData *data(reinterpret_cast<ffoData *>(arg));
1533 JSContextRef context(data->context_);
1535 size_t count(data->cif_.nargs);
1536 JSValueRef values[count];
1538 for (size_t index(0); index != count; ++index)
1539 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1541 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1542 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1545 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1546 // XXX: in case of exceptions this will leak
1547 ffoData *data(new ffoData(type));
1549 ffi_closure *closure;
1550 _syscall(closure = (ffi_closure *) mmap(
1551 NULL, sizeof(ffi_closure),
1552 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1556 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1557 _assert(status == FFI_OK);
1559 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1561 data->value_ = closure;
1563 data->context_ = CYGetJSContext();
1564 data->function_ = function;
1566 return JSObjectMake(context, Functor_, data);
1569 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1572 NSString *name(CYCastNSString(pool, property));
1573 if (Class _class = NSClassFromString(name))
1574 return CYMakeInstance(context, _class, true);
1575 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1576 switch ([[entry objectAtIndex:0] intValue]) {
1578 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1580 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1582 // XXX: this is horrendously inefficient
1583 sig::Signature signature;
1584 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]));
1586 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1587 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
1593 bool stret(ffi_type *ffi_type) {
1594 return ffi_type->type == FFI_TYPE_STRUCT && (
1595 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1596 struct_forward_array[ffi_type->size] != 0
1601 int *_NSGetArgc(void);
1602 char ***_NSGetArgv(void);
1603 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1606 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1608 NSLog(@"%s", CYCastCString(context, arguments[0]));
1609 return CYJSUndefined(context);
1613 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1616 NSString *name(CYCastNSObject(pool, context, arguments[0]));
1617 int argc(*_NSGetArgc());
1618 char **argv(*_NSGetArgv());
1619 for (int i(0); i != argc; ++i)
1620 NSLog(@"argv[%i]=%s", i, argv[i]);
1622 return CYCastJSValue(context, UIApplicationMain(argc, argv, name, name));
1626 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1629 Class _class(object_getClass(self));
1630 if (Method method = class_getInstanceMethod(_class, _cmd))
1631 type = method_getTypeEncoding(method);
1634 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1636 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1637 type = CYPoolCString(pool, [method _typeString]);
1645 sig::Signature signature;
1646 sig::Parse(pool, &signature, type);
1649 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1651 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1652 return CYCallFunction(pool, context, 2, setup, count, arguments, exception, &signature, &cif, function);
1655 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1663 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1665 self = CYCastNSObject(pool, context, arguments[0]);
1667 return CYJSNull(context);
1669 _cmd = CYCastSEL(context, arguments[1]);
1672 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, exception);
1675 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1676 JSValueRef setup[count + 2];
1679 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
1680 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1683 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1685 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1686 return CYCallFunction(pool, context, 0, NULL, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1689 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1692 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1693 const char *name(CYCastCString(context, arguments[0]));
1694 return CYMakeSelector(context, sel_registerName(name));
1698 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1701 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1702 const char *type(CYCastCString(context, arguments[1]));
1703 JSValueRef exception(NULL);
1704 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1705 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1706 return CYMakeFunctor(context, function, type);
1707 } else if (exception != NULL) {
1710 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1711 return CYMakeFunctor(context, function, type);
1716 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1717 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
1718 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1721 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1725 static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1727 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1728 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1732 static JSValueRef Pointer_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1733 return Pointer_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1736 static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1738 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1740 sprintf(string, "%p", data->value_);
1741 return CYCastJSValue(context, string);
1745 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1747 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1749 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
1754 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1756 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1758 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
1759 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
1764 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1766 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1768 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
1773 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1775 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1776 return CYCastJSValue(context, sel_getName(data->GetValue()));
1780 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1781 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
1784 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1786 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1787 const char *name(sel_getName(data->GetValue()));
1789 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
1794 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1797 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1799 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1800 Class _class(CYCastNSObject(pool, context, arguments[0]));
1801 bool instance(CYCastBool(context, arguments[1]));
1802 SEL sel(data->GetValue());
1803 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1804 return CYCastJSValue(context, method_getTypeEncoding(method));
1805 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1806 return CYCastJSValue(context, CYJSString(type));
1808 return CYJSNull(context);
1812 static JSStaticValue Pointer_staticValues[2] = {
1813 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1814 {NULL, NULL, NULL, 0}
1817 static JSStaticFunction Pointer_staticFunctions[4] = {
1818 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1819 {"toJSON", &Pointer_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1820 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1824 /*static JSStaticValue Selector_staticValues[2] = {
1825 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1826 {NULL, NULL, NULL, 0}
1829 static JSStaticFunction Instance_staticFunctions[4] = {
1830 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1831 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1832 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1836 static JSStaticFunction Selector_staticFunctions[5] = {
1837 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1838 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1839 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1840 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1844 CYDriver::CYDriver(const std::string &filename) :
1848 filename_(filename),
1854 CYDriver::~CYDriver() {
1858 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1859 CYDriver::Error error;
1860 error.location_ = location;
1861 error.message_ = message;
1862 driver.errors_.push_back(error);
1865 void CYSetArgs(int argc, const char *argv[]) {
1866 JSContextRef context(CYGetJSContext());
1867 JSValueRef args[argc];
1868 for (int i(0); i != argc; ++i)
1869 args[i] = CYCastJSValue(context, argv[i]);
1870 JSValueRef exception(NULL);
1871 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1872 CYThrow(context, exception);
1873 CYSetProperty(context, System_, CYJSString("args"), array);
1876 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1877 return JSContextGetGlobalObject(context);
1880 MSInitialize { _pooled
1883 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1885 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1887 JSClassDefinition definition;
1889 definition = kJSClassDefinitionEmpty;
1890 definition.className = "Pointer";
1891 definition.staticValues = Pointer_staticValues;
1892 definition.staticFunctions = Pointer_staticFunctions;
1893 definition.finalize = &CYData::Finalize;
1894 Pointer_ = JSClassCreate(&definition);
1896 definition = kJSClassDefinitionEmpty;
1897 definition.className = "Functor";
1898 definition.staticValues = Pointer_staticValues;
1899 definition.staticFunctions = Pointer_staticFunctions;
1900 definition.callAsFunction = &Functor_callAsFunction;
1901 definition.finalize = &CYData::Finalize;
1902 Functor_ = JSClassCreate(&definition);
1904 definition = kJSClassDefinitionEmpty;
1905 definition.className = "Struct";
1906 definition.getProperty = &Struct_getProperty;
1907 definition.setProperty = &Struct_setProperty;
1908 definition.finalize = &CYData::Finalize;
1909 Struct_ = JSClassCreate(&definition);
1911 definition = kJSClassDefinitionEmpty;
1912 definition.className = "Selector";
1913 definition.staticValues = Pointer_staticValues;
1914 //definition.staticValues = Selector_staticValues;
1915 definition.staticFunctions = Selector_staticFunctions;
1916 definition.callAsFunction = &Selector_callAsFunction;
1917 definition.finalize = &CYData::Finalize;
1918 Selector_ = JSClassCreate(&definition);
1920 definition = kJSClassDefinitionEmpty;
1921 definition.className = "Instance";
1922 definition.staticValues = Pointer_staticValues;
1923 definition.staticFunctions = Instance_staticFunctions;
1924 definition.getProperty = &Instance_getProperty;
1925 definition.setProperty = &Instance_setProperty;
1926 definition.deleteProperty = &Instance_deleteProperty;
1927 definition.callAsConstructor = &Instance_callAsConstructor;
1928 definition.finalize = &CYData::Finalize;
1929 Instance_ = JSClassCreate(&definition);
1931 definition = kJSClassDefinitionEmpty;
1932 definition.className = "Runtime";
1933 definition.getProperty = &Runtime_getProperty;
1934 Runtime_ = JSClassCreate(&definition);
1936 definition = kJSClassDefinitionEmpty;
1937 //definition.getProperty = &Global_getProperty;
1938 JSClassRef Global(JSClassCreate(&definition));
1940 JSGlobalContextRef context(JSGlobalContextCreate(Global));
1943 JSObjectRef global(CYGetGlobalObject(context));
1945 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
1946 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
1948 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
1949 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
1951 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
1952 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1954 System_ = JSObjectMake(context, NULL, NULL);
1955 CYSetProperty(context, global, CYJSString("system"), System_);
1956 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
1957 //CYSetProperty(context, System_, CYJSString("global"), global);
1959 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
1961 length_ = JSStringCreateWithUTF8CString("length");
1962 message_ = JSStringCreateWithUTF8CString("message");
1963 name_ = JSStringCreateWithUTF8CString("name");
1964 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
1965 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
1967 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1968 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));