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 {
287 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) {
288 sig::Copy(pool, type_, *type);
289 sig::Copy(pool, ffi_, *ffi);
291 /*sig::Element element;
296 sig::Signature signature;
297 signature.elements = &element;
301 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
304 /*if (type_->type != FFI_TYPE_STRUCT)
308 while (type_->elements[count] != NULL)
315 struct Struct_privateData :
319 Type_privateData *type_;
321 Struct_privateData() {
325 struct CStringMapLess :
326 std::binary_function<const char *, const char *, bool>
328 _finline bool operator ()(const char *lhs, const char *rhs) const {
329 return strcmp(lhs, rhs) < 0;
333 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
334 static TypeMap Types_;
336 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
337 Struct_privateData *internal(new Struct_privateData());
338 apr_pool_t *pool(internal->pool_);
339 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
340 internal->type_ = typical;
343 internal->owner_ = owner;
344 internal->value_ = data;
346 internal->owner_ = NULL;
348 size_t size(typical->ffi_.size);
349 void *copy(apr_palloc(internal->pool_, size));
350 memcpy(copy, data, size);
351 internal->value_ = copy;
354 return JSObjectMake(context, Struct_, internal);
357 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
359 object = [object retain];
360 Instance_privateData *data(new Instance_privateData(object, transient));
361 return JSObjectMake(context, Instance_, data);
364 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
366 return [value UTF8String];
368 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
369 char *string(new(pool) char[size]);
370 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
371 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
376 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
377 return JSValueMakeBoolean(context, value);
380 JSValueRef CYCastJSValue(JSContextRef context, double value) {
381 return JSValueMakeNumber(context, value);
384 #define CYCastJSValue_(Type_) \
385 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
386 return JSValueMakeNumber(context, static_cast<double>(value)); \
390 CYCastJSValue_(unsigned int)
391 CYCastJSValue_(long int)
392 CYCastJSValue_(long unsigned int)
393 CYCastJSValue_(long long int)
394 CYCastJSValue_(long long unsigned int)
396 JSValueRef CYJSUndefined(JSContextRef context) {
397 return JSValueMakeUndefined(context);
400 @interface NSMethodSignature (Cycript)
401 - (NSString *) _typeString;
404 @interface NSObject (Cycript)
406 - (JSType) cy$JSType;
408 - (NSObject *) cy$toJSON:(NSString *)key;
409 - (NSString *) cy$toCYON;
411 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
413 - (NSObject *) cy$getProperty:(NSString *)name;
414 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
415 - (bool) cy$deleteProperty:(NSString *)name;
419 @interface NSString (Cycript)
420 - (void *) cy$symbol;
423 @interface NSNumber (Cycript)
424 - (void *) cy$symbol;
427 @implementation NSObject (Cycript)
429 - (JSType) cy$JSType {
430 return kJSTypeObject;
433 - (NSObject *) cy$toJSON:(NSString *)key {
434 return [self description];
437 - (NSString *) cy$toCYON {
438 return [[self cy$toJSON:@""] cy$toCYON];
441 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
442 return CYMakeInstance(context, self, transient);
445 - (NSObject *) cy$getProperty:(NSString *)name {
446 if (![name isEqualToString:@"prototype"])
447 NSLog(@"get:%@", name);
451 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
452 NSLog(@"set:%@", name);
456 - (bool) cy$deleteProperty:(NSString *)name {
457 NSLog(@"delete:%@", name);
463 @implementation WebUndefined (Cycript)
465 - (JSType) cy$JSType {
466 return kJSTypeUndefined;
469 - (NSObject *) cy$toJSON:(NSString *)key {
473 - (NSString *) cy$toCYON {
477 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
478 return CYJSUndefined(context);
483 @implementation NSNull (Cycript)
485 - (JSType) cy$JSType {
489 - (NSObject *) cy$toJSON:(NSString *)key {
493 - (NSString *) cy$toCYON {
499 @implementation NSArray (Cycript)
501 - (NSString *) cy$toCYON {
502 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
503 [json appendString:@"["];
506 for (id object in self) {
508 [json appendString:@","];
511 if ([object cy$JSType] != kJSTypeUndefined)
512 [json appendString:[object cy$toCYON]];
514 [json appendString:@","];
519 [json appendString:@"]"];
523 - (NSObject *) cy$getProperty:(NSString *)name {
524 int index([name intValue]);
525 if (index < 0 || index >= static_cast<int>([self count]))
526 return [super cy$getProperty:name];
528 return [self objectAtIndex:index];
533 @implementation NSMutableArray (Cycript)
535 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
536 int index([name intValue]);
537 if (index < 0 || index >= static_cast<int>([self count]))
538 return [super cy$setProperty:name to:value];
540 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
545 - (bool) cy$deleteProperty:(NSString *)name {
546 int index([name intValue]);
547 if (index < 0 || index >= static_cast<int>([self count]))
548 return [super cy$deleteProperty:name];
550 [self removeObjectAtIndex:index];
557 @implementation NSDictionary (Cycript)
559 - (NSString *) cy$toCYON {
560 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
561 [json appendString:@"({"];
564 for (id key in self) {
566 [json appendString:@","];
569 [json appendString:[key cy$toCYON]];
570 [json appendString:@":"];
571 NSObject *object([self objectForKey:key]);
572 [json appendString:[object cy$toCYON]];
575 [json appendString:@"})"];
579 - (NSObject *) cy$getProperty:(NSString *)name {
580 return [self objectForKey:name];
585 @implementation NSMutableDictionary (Cycript)
587 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
588 [self setObject:(value ?: [NSNull null]) forKey:name];
592 - (bool) cy$deleteProperty:(NSString *)name {
593 if ([self objectForKey:name] == nil)
596 [self removeObjectForKey:name];
603 @implementation NSNumber (Cycript)
605 - (JSType) cy$JSType {
606 // XXX: this just seems stupid
607 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
610 - (NSObject *) cy$toJSON:(NSString *)key {
614 - (NSString *) cy$toCYON {
615 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
618 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
619 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
622 - (void *) cy$symbol {
623 return [self pointerValue];
628 @implementation NSString (Cycript)
630 - (JSType) cy$JSType {
631 return kJSTypeString;
634 - (NSObject *) cy$toJSON:(NSString *)key {
638 - (NSString *) cy$toCYON {
639 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
641 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
642 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
643 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
644 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
645 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
647 CFStringInsert(json, 0, CFSTR("\""));
648 CFStringAppend(json, CFSTR("\""));
650 return [reinterpret_cast<const NSString *>(json) autorelease];
653 - (void *) cy$symbol {
655 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
660 @interface CYJSObject : NSDictionary {
662 JSContextRef context_;
665 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
667 - (NSString *) cy$toJSON:(NSString *)key;
669 - (NSUInteger) count;
670 - (id) objectForKey:(id)key;
671 - (NSEnumerator *) keyEnumerator;
672 - (void) setObject:(id)object forKey:(id)key;
673 - (void) removeObjectForKey:(id)key;
677 @interface CYJSArray : NSArray {
679 JSContextRef context_;
682 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
684 - (NSUInteger) count;
685 - (id) objectAtIndex:(NSUInteger)index;
689 CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
690 CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
692 JSGlobalContextRef CYGetJSContext() {
699 @catch (id error) { \
700 CYThrow(context, error, exception); \
704 void CYThrow(JSContextRef context, JSValueRef value);
706 apr_status_t CYPoolRelease_(void *data) {
707 id object(reinterpret_cast<id>(data));
712 id CYPoolRelease(apr_pool_t *pool, id object) {
715 else if (pool == NULL)
716 return [object autorelease];
718 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
723 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
724 return (CFTypeRef) CYPoolRelease(pool, (id) object);
727 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
728 if (JSValueIsObjectOfClass(context, object, Instance_)) {
729 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
730 return data->GetValue();
733 JSValueRef exception(NULL);
734 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
735 CYThrow(context, exception);
736 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
737 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
740 JSStringRef CYCopyJSString(id value) {
741 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
744 JSStringRef CYCopyJSString(const char *value) {
745 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
748 JSStringRef CYCopyJSString(JSStringRef value) {
749 return value == NULL ? NULL : JSStringRetain(value);
752 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
753 if (JSValueIsNull(context, value))
755 JSValueRef exception(NULL);
756 JSStringRef string(JSValueToStringCopy(context, value, &exception));
757 CYThrow(context, exception);
766 JSStringRelease(string_);
770 CYJSString(const CYJSString &rhs) :
771 string_(CYCopyJSString(rhs.string_))
775 template <typename Arg0_>
776 CYJSString(Arg0_ arg0) :
777 string_(CYCopyJSString(arg0))
781 template <typename Arg0_, typename Arg1_>
782 CYJSString(Arg0_ arg0, Arg1_ arg1) :
783 string_(CYCopyJSString(arg0, arg1))
787 CYJSString &operator =(const CYJSString &rhs) {
789 string_ = CYCopyJSString(rhs.string_);
802 operator JSStringRef() const {
807 CFStringRef CYCopyCFString(JSStringRef value) {
808 return JSStringCopyCFString(kCFAllocatorDefault, value);
811 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
812 return CYCopyCFString(CYJSString(context, value));
815 double CYCastDouble(const char *value, size_t size) {
817 double number(strtod(value, &end));
818 if (end != value + size)
823 double CYCastDouble(const char *value) {
824 return CYCastDouble(value, strlen(value));
827 double CYCastDouble(JSContextRef context, JSValueRef value) {
828 JSValueRef exception(NULL);
829 double number(JSValueToNumber(context, value, &exception));
830 CYThrow(context, exception);
834 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
835 double number(CYCastDouble(context, value));
836 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
839 CFStringRef CYCopyCFString(const char *value) {
840 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
843 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
844 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
847 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
848 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
851 bool CYCastBool(JSContextRef context, JSValueRef value) {
852 return JSValueToBoolean(context, value);
855 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
859 switch (JSType type = JSValueGetType(context, value)) {
860 case kJSTypeUndefined:
861 object = [WebUndefined undefined];
870 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
875 object = CYCopyCFNumber(context, value);
880 object = CYCopyCFString(context, value);
885 // XXX: this might could be more efficient
886 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
891 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
898 return CYPoolRelease(pool, object);
900 return CFRetain(object);
903 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
904 return CYCFType(pool, context, value, true);
907 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
908 return CYCFType(pool, context, value, false);
911 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
913 size_t size(JSPropertyNameArrayGetCount(names));
914 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
915 for (size_t index(0); index != size; ++index)
916 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
920 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
921 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
924 void CYThrow(JSContextRef context, JSValueRef value) {
927 @throw CYCastNSObject(NULL, context, value);
930 JSValueRef CYJSNull(JSContextRef context) {
931 return JSValueMakeNull(context);
934 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
935 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
938 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
939 return CYCastJSValue(context, CYJSString(value));
942 JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
943 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
946 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
947 JSValueRef exception(NULL);
948 JSObjectRef object(JSValueToObject(context, value, &exception));
949 CYThrow(context, exception);
953 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
954 JSValueRef exception(NULL);
955 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
956 CYThrow(context, exception);
960 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
961 JSValueRef exception(NULL);
962 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
963 CYThrow(context, exception);
967 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
968 JSValueRef exception(NULL);
969 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
970 CYThrow(context, exception);
973 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
974 if (exception == NULL)
976 *exception = CYCastJSValue(context, error);
979 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
980 JSValueRef exception(NULL);
981 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
982 CYThrow(context, exception);
986 bool CYIsCallable(JSContextRef context, JSValueRef value) {
987 // XXX: this isn't actually correct
988 return value != NULL && JSValueIsObject(context, value);
991 @implementation CYJSObject
993 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
994 if ((self = [super init]) != nil) {
1000 - (NSObject *) cy$toJSON:(NSString *)key {
1001 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1002 if (!CYIsCallable(context_, toJSON))
1003 return [super cy$toJSON:key];
1005 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1006 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1007 // XXX: do I really want an NSNull here?!
1008 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1012 - (NSString *) cy$toCYON {
1013 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1014 if (!CYIsCallable(context_, toCYON))
1015 return [super cy$toCYON];
1017 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1018 return CYCastNSString(NULL, CYJSString(context_, value));
1022 - (NSUInteger) count {
1023 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1024 size_t size(JSPropertyNameArrayGetCount(names));
1025 JSPropertyNameArrayRelease(names);
1029 - (id) objectForKey:(id)key {
1030 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1033 - (NSEnumerator *) keyEnumerator {
1034 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1035 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1036 JSPropertyNameArrayRelease(names);
1040 - (void) setObject:(id)object forKey:(id)key {
1041 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1044 - (void) removeObjectForKey:(id)key {
1045 JSValueRef exception(NULL);
1046 // XXX: this returns a bool... throw exception, or ignore?
1047 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1048 CYThrow(context_, exception);
1053 @implementation CYJSArray
1055 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1056 if ((self = [super init]) != nil) {
1062 - (NSUInteger) count {
1063 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1066 - (id) objectAtIndex:(NSUInteger)index {
1067 JSValueRef exception(NULL);
1068 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1069 CYThrow(context_, exception);
1070 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1075 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1078 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1079 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
1084 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1085 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
1086 const char *string(CYPoolCString(pool, json));
1092 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1095 NSString *self(CYCastNSObject(pool, context, object));
1096 NSString *name(CYCastNSString(pool, property));
1097 NSObject *data([self cy$getProperty:name]);
1098 return data == nil ? NULL : CYCastJSValue(context, data);
1102 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1105 NSString *self(CYCastNSObject(pool, context, object));
1106 NSString *name(CYCastNSString(pool, property));
1107 NSString *data(CYCastNSObject(pool, context, value));
1108 return [self cy$setProperty:name to:data];
1112 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1115 NSString *self(CYCastNSObject(pool, context, object));
1116 NSString *name(CYCastNSString(pool, property));
1117 return [self cy$deleteProperty:name];
1121 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1123 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
1124 return CYMakeInstance(context, [data->GetValue() alloc], true);
1128 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1129 Selector_privateData *data(new Selector_privateData(sel));
1130 return JSObjectMake(context, Selector_, data);
1133 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
1134 Pointer_privateData *data(new Pointer_privateData(pointer));
1135 return JSObjectMake(context, Pointer_, data);
1138 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1139 Functor_privateData *data(new Functor_privateData(type, function));
1140 return JSObjectMake(context, Functor_, data);
1143 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1145 const char *string([CYCastNSString(NULL, value) UTF8String]);
1147 *length = strlen(string);
1150 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1151 char *string(new(pool) char[size]);
1152 JSStringGetUTF8CString(value, string, size);
1153 // XXX: this is ironic
1155 *length = strlen(string);
1160 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1161 if (!JSValueIsNull(context, value))
1162 return CYPoolCString(pool, CYJSString(context, value), length);
1170 // XXX: this macro is unhygenic
1171 #define CYCastCString(context, value) ({ \
1173 if (value == NULL) \
1175 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1176 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1177 utf8 = reinterpret_cast<char *>(alloca(size)); \
1178 JSStringGetUTF8CString(string, utf8, size); \
1179 JSStringRelease(string); \
1185 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1186 if (JSValueIsNull(context, value))
1188 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
1189 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1190 return reinterpret_cast<SEL>(data->value_);
1192 return sel_registerName(CYCastCString(context, value));
1195 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1196 switch (JSValueGetType(context, value)) {
1199 /*case kJSTypeString:
1200 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1202 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1203 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1204 return data->value_;
1207 double number(CYCastDouble(context, value));
1208 if (std::isnan(number))
1209 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1210 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1214 template <typename Type_>
1215 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1216 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1219 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1220 switch (type->primitive) {
1221 case sig::boolean_P:
1222 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1225 #define CYPoolFFI_(primitive, native) \
1226 case sig::primitive ## _P: \
1227 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1230 CYPoolFFI_(uchar, unsigned char)
1231 CYPoolFFI_(char, char)
1232 CYPoolFFI_(ushort, unsigned short)
1233 CYPoolFFI_(short, short)
1234 CYPoolFFI_(ulong, unsigned long)
1235 CYPoolFFI_(long, long)
1236 CYPoolFFI_(uint, unsigned int)
1237 CYPoolFFI_(int, int)
1238 CYPoolFFI_(ulonglong, unsigned long long)
1239 CYPoolFFI_(longlong, long long)
1240 CYPoolFFI_(float, float)
1241 CYPoolFFI_(double, double)
1244 case sig::typename_P:
1245 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1248 case sig::selector_P:
1249 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1252 case sig::pointer_P:
1253 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1257 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1260 case sig::struct_P: {
1261 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1262 bool aggregate(JSValueIsObject(context, value));
1263 for (size_t index(0); index != type->data.signature.count; ++index) {
1264 ffi_type *element(ffi->elements[index]);
1265 JSValueRef rhs(aggregate ? CYGetProperty(context, (JSObjectRef) value, index) : value);
1266 CYPoolFFI(pool, context, type->data.signature.elements[index].type, element, base, rhs);
1268 base += element->size;
1276 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1281 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
1284 switch (type->primitive) {
1285 case sig::boolean_P:
1286 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1289 #define CYFromFFI_(primitive, native) \
1290 case sig::primitive ## _P: \
1291 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1294 CYFromFFI_(uchar, unsigned char)
1295 CYFromFFI_(char, char)
1296 CYFromFFI_(ushort, unsigned short)
1297 CYFromFFI_(short, short)
1298 CYFromFFI_(ulong, unsigned long)
1299 CYFromFFI_(long, long)
1300 CYFromFFI_(uint, unsigned int)
1301 CYFromFFI_(int, int)
1302 CYFromFFI_(ulonglong, unsigned long long)
1303 CYFromFFI_(longlong, long long)
1304 CYFromFFI_(float, float)
1305 CYFromFFI_(double, double)
1308 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
1311 case sig::typename_P:
1312 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1315 case sig::selector_P:
1316 if (SEL sel = *reinterpret_cast<SEL *>(data))
1317 value = CYMakeSelector(context, sel);
1321 case sig::pointer_P:
1322 if (void *pointer = *reinterpret_cast<void **>(data))
1323 value = CYMakePointer(context, pointer);
1328 if (char *utf8 = *reinterpret_cast<char **>(data))
1329 value = CYCastJSValue(context, utf8);
1334 value = CYMakeStruct(context, data, type, ffi, owner);
1338 value = CYJSUndefined(context);
1342 value = CYJSNull(context);
1346 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1353 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1354 Type_privateData *typical(internal->type_);
1357 const char *name(CYPoolCString(pool, property, &length));
1358 double number(CYCastDouble(name, length));
1360 if (std::isnan(number)) {
1361 if (property == NULL)
1367 index = static_cast<ssize_t>(number);
1368 if (index != number || index < 0 || static_cast<size_t>(index) >= typical->type_.data.signature.count)
1372 base = reinterpret_cast<uint8_t *>(internal->value_);
1373 for (ssize_t local(0); local != index; ++local)
1374 base += typical->ffi_.elements[local]->size;
1379 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1382 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1383 Type_privateData *typical(internal->type_);
1388 if (!Index_(pool, internal, property, index, base))
1391 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
1395 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1398 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1399 Type_privateData *typical(internal->type_);
1404 if (!Index_(pool, internal, property, index, base))
1407 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1412 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1414 if (count != signature->count - 1)
1415 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1418 void *values[count];
1420 for (unsigned index(0); index != count; ++index) {
1421 sig::Element *element(&signature->elements[index + 1]);
1422 ffi_type *ffi(cif->arg_types[index]);
1424 values[index] = new(pool) uint8_t[ffi->size];
1425 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index]);
1428 uint8_t value[cif->rtype->size];
1429 ffi_call(cif, function, value, values);
1431 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
1435 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1436 ffoData *data(reinterpret_cast<ffoData *>(arg));
1438 JSContextRef context(data->context_);
1440 size_t count(data->cif_.nargs);
1441 JSValueRef values[count];
1443 for (size_t index(0); index != count; ++index)
1444 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1446 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1447 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1450 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1451 // XXX: in case of exceptions this will leak
1452 ffoData *data(new ffoData(type));
1454 ffi_closure *closure;
1455 _syscall(closure = (ffi_closure *) mmap(
1456 NULL, sizeof(ffi_closure),
1457 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1461 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1462 _assert(status == FFI_OK);
1464 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1466 data->value_ = closure;
1468 data->context_ = CYGetJSContext();
1469 data->function_ = function;
1471 return JSObjectMake(context, Functor_, data);
1474 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1477 NSString *name(CYCastNSString(pool, property));
1478 if (Class _class = NSClassFromString(name))
1479 return CYMakeInstance(context, _class, true);
1480 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1481 switch ([[entry objectAtIndex:0] intValue]) {
1483 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1485 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1487 // XXX: this is horrendously inefficient
1488 sig::Signature signature;
1489 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]));
1491 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1492 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
1498 bool stret(ffi_type *ffi_type) {
1499 return ffi_type->type == FFI_TYPE_STRUCT && (
1500 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1501 struct_forward_array[ffi_type->size] != 0
1506 int *_NSGetArgc(void);
1507 char ***_NSGetArgv(void);
1508 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1511 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1513 NSLog(@"%s", CYCastCString(context, arguments[0]));
1514 return CYJSUndefined(context);
1518 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1521 NSString *name(CYCastNSObject(pool, context, arguments[0]));
1522 int argc(*_NSGetArgc());
1523 char **argv(*_NSGetArgv());
1524 for (int i(0); i != argc; ++i)
1525 NSLog(@"argv[%i]=%s", i, argv[i]);
1527 return CYCastJSValue(context, UIApplicationMain(argc, argv, name, name));
1531 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1538 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1540 id self(CYCastNSObject(pool, context, arguments[0]));
1542 return CYJSNull(context);
1544 SEL _cmd(CYCastSEL(context, arguments[1]));
1546 Class _class(object_getClass(self));
1547 if (Method method = class_getInstanceMethod(_class, _cmd))
1548 type = method_getTypeEncoding(method);
1551 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1553 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1554 type = CYPoolCString(pool, [method _typeString]);
1559 sig::Signature signature;
1560 sig::Parse(pool, &signature, type);
1563 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1565 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1566 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
1569 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1570 JSValueRef setup[count + 2];
1573 memmove(setup + 2, arguments, sizeof(JSValueRef) * count);
1574 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1577 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1578 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1579 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1582 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1585 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1586 const char *name(CYCastCString(context, arguments[0]));
1587 return CYMakeSelector(context, sel_registerName(name));
1591 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1594 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1595 const char *type(CYCastCString(context, arguments[1]));
1596 JSValueRef exception(NULL);
1597 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1598 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1599 return CYMakeFunctor(context, function, type);
1600 } else if (exception != NULL) {
1603 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1604 return CYMakeFunctor(context, function, type);
1609 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1610 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
1611 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1614 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1618 static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1620 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1621 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1625 static JSValueRef Pointer_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1626 return Pointer_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1629 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1631 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1633 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
1638 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1640 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1642 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
1643 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
1648 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1650 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1652 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
1657 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1659 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1660 return CYCastJSValue(context, sel_getName(data->GetValue()));
1664 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1665 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
1668 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1670 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1671 const char *name(sel_getName(data->GetValue()));
1673 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
1678 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1681 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1683 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1684 Class _class(CYCastNSObject(pool, context, arguments[0]));
1685 bool instance(CYCastBool(context, arguments[1]));
1686 SEL sel(data->GetValue());
1687 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1688 return CYCastJSValue(context, method_getTypeEncoding(method));
1689 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1690 return CYCastJSValue(context, CYJSString(type));
1692 return CYJSNull(context);
1696 static JSStaticValue Pointer_staticValues[2] = {
1697 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1698 {NULL, NULL, NULL, 0}
1701 static JSStaticFunction Pointer_staticFunctions[3] = {
1702 {"toJSON", &Pointer_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1703 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1707 /*static JSStaticValue Selector_staticValues[2] = {
1708 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1709 {NULL, NULL, NULL, 0}
1712 static JSStaticFunction Instance_staticFunctions[4] = {
1713 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1714 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1715 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1719 static JSStaticFunction Selector_staticFunctions[5] = {
1720 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1721 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1722 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1723 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1727 CYDriver::CYDriver(const std::string &filename) :
1731 filename_(filename),
1737 CYDriver::~CYDriver() {
1741 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1742 CYDriver::Error error;
1743 error.location_ = location;
1744 error.message_ = message;
1745 driver.errors_.push_back(error);
1748 void CYSetArgs(int argc, const char *argv[]) {
1749 JSContextRef context(CYGetJSContext());
1750 JSValueRef args[argc];
1751 for (int i(0); i != argc; ++i)
1752 args[i] = CYCastJSValue(context, argv[i]);
1753 JSValueRef exception(NULL);
1754 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1755 CYThrow(context, exception);
1756 CYSetProperty(context, System_, CYJSString("args"), array);
1759 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1760 return JSContextGetGlobalObject(context);
1763 MSInitialize { _pooled
1766 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1768 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1770 JSClassDefinition definition;
1772 definition = kJSClassDefinitionEmpty;
1773 definition.className = "Pointer";
1774 definition.staticValues = Pointer_staticValues;
1775 definition.staticFunctions = Pointer_staticFunctions;
1776 definition.finalize = &CYData::Finalize;
1777 Pointer_ = JSClassCreate(&definition);
1779 definition = kJSClassDefinitionEmpty;
1780 definition.className = "Functor";
1781 definition.staticValues = Pointer_staticValues;
1782 definition.staticFunctions = Pointer_staticFunctions;
1783 definition.callAsFunction = &Functor_callAsFunction;
1784 definition.finalize = &CYData::Finalize;
1785 Functor_ = JSClassCreate(&definition);
1787 definition = kJSClassDefinitionEmpty;
1788 definition.className = "Struct";
1789 definition.getProperty = &Struct_getProperty;
1790 definition.setProperty = &Struct_setProperty;
1791 definition.finalize = &CYData::Finalize;
1792 Struct_ = JSClassCreate(&definition);
1794 definition = kJSClassDefinitionEmpty;
1795 definition.className = "Selector";
1796 definition.staticValues = Pointer_staticValues;
1797 //definition.staticValues = Selector_staticValues;
1798 definition.staticFunctions = Selector_staticFunctions;
1799 definition.callAsFunction = &Selector_callAsFunction;
1800 definition.finalize = &CYData::Finalize;
1801 Selector_ = JSClassCreate(&definition);
1803 definition = kJSClassDefinitionEmpty;
1804 definition.className = "Instance";
1805 definition.staticValues = Pointer_staticValues;
1806 definition.staticFunctions = Instance_staticFunctions;
1807 definition.getProperty = &Instance_getProperty;
1808 definition.setProperty = &Instance_setProperty;
1809 definition.deleteProperty = &Instance_deleteProperty;
1810 definition.callAsConstructor = &Instance_callAsConstructor;
1811 definition.finalize = &CYData::Finalize;
1812 Instance_ = JSClassCreate(&definition);
1814 definition = kJSClassDefinitionEmpty;
1815 definition.className = "Runtime";
1816 definition.getProperty = &Runtime_getProperty;
1817 Runtime_ = JSClassCreate(&definition);
1819 definition = kJSClassDefinitionEmpty;
1820 //definition.getProperty = &Global_getProperty;
1821 JSClassRef Global(JSClassCreate(&definition));
1823 JSGlobalContextRef context(JSGlobalContextCreate(Global));
1826 JSObjectRef global(CYGetGlobalObject(context));
1828 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
1829 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
1831 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
1832 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
1834 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
1835 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1837 System_ = JSObjectMake(context, NULL, NULL);
1838 CYSetProperty(context, global, CYJSString("system"), System_);
1839 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
1840 //CYSetProperty(context, System_, CYJSString("global"), global);
1842 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
1844 length_ = JSStringCreateWithUTF8CString("length");
1845 message_ = JSStringCreateWithUTF8CString("message");
1846 name_ = JSStringCreateWithUTF8CString("name");
1847 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
1848 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
1850 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1851 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));