1 /* Cycript - Remove Execution Server and Disassembler
2 * Copyright (C) 2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 #include <substrate.h>
43 #include "cycript.hpp"
45 #include "sig/parse.hpp"
46 #include "sig/ffi_type.hpp"
48 #include "Pooling.hpp"
53 #include <CoreFoundation/CoreFoundation.h>
54 #include <CoreFoundation/CFLogUtilities.h>
56 #include <WebKit/WebScriptObject.h>
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
64 #include <ext/stdio_filebuf.h>
71 #include "Cycript.tab.hh"
76 #define _assert(test) do { \
78 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
81 #define _trace() do { \
82 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
87 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
89 #define CYPoolCatch(value) \
90 @catch (NSException *error) { \
91 _saved = [error retain]; \
97 [_saved autorelease]; \
101 static JSGlobalContextRef Context_;
102 static JSObjectRef System_;
104 static JSClassRef Functor_;
105 static JSClassRef Instance_;
106 static JSClassRef Pointer_;
107 static JSClassRef Runtime_;
108 static JSClassRef Selector_;
109 static JSClassRef Struct_;
111 static JSObjectRef Array_;
112 static JSObjectRef Function_;
114 static JSStringRef length_;
115 static JSStringRef message_;
116 static JSStringRef name_;
117 static JSStringRef toCYON_;
118 static JSStringRef toJSON_;
120 static Class NSCFBoolean_;
122 static NSArray *Bridge_;
130 void *operator new(size_t size) {
132 apr_pool_create(&pool, NULL);
133 void *data(apr_palloc(pool, size));
134 reinterpret_cast<CYData *>(data)->pool_ = pool;
138 static void Finalize(JSObjectRef object) {
139 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
141 apr_pool_destroy(data->pool_);
145 struct Pointer_privateData :
151 Pointer_privateData() {
154 Pointer_privateData(void *value) :
160 struct Selector_privateData : Pointer_privateData {
161 Selector_privateData(SEL value) :
162 Pointer_privateData(value)
166 SEL GetValue() const {
167 return reinterpret_cast<SEL>(value_);
171 struct Instance_privateData :
176 Instance_privateData(id value, bool transient) :
177 Pointer_privateData(value)
181 virtual ~Instance_privateData() {
183 [GetValue() release];
186 id GetValue() const {
187 return reinterpret_cast<id>(value_);
193 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
195 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
196 lhs.name = apr_pstrdup(pool, rhs.name);
197 if (rhs.type == NULL)
200 lhs.type = new(pool) Type;
201 Copy(pool, *lhs.type, *rhs.type);
203 lhs.offset = rhs.offset;
206 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
207 size_t count(rhs.count);
209 lhs.elements = new(pool) Element[count];
210 for (size_t index(0); index != count; ++index)
211 Copy(pool, lhs.elements[index], rhs.elements[index]);
214 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
215 lhs.primitive = rhs.primitive;
216 lhs.name = apr_pstrdup(pool, rhs.name);
217 lhs.flags = rhs.flags;
219 if (sig::IsAggregate(rhs.primitive))
220 Copy(pool, lhs.data.signature, rhs.data.signature);
222 if (rhs.data.data.type != NULL) {
223 lhs.data.data.type = new(pool) Type;
224 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
227 lhs.data.data.size = rhs.data.data.size;
231 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
233 lhs.alignment = rhs.alignment;
235 if (rhs.elements == NULL)
239 while (rhs.elements[count] != NULL)
242 lhs.elements = new(pool) ffi_type *[count + 1];
243 lhs.elements[count] = NULL;
245 for (size_t index(0); index != count; ++index) {
246 // XXX: if these are libffi native then you can just take them
247 ffi_type *ffi(new(pool) ffi_type);
248 lhs.elements[index] = ffi;
249 sig::Copy(pool, *ffi, *rhs.elements[index]);
256 struct CStringMapLess :
257 std::binary_function<const char *, const char *, bool>
259 _finline bool operator ()(const char *lhs, const char *rhs) const {
260 return strcmp(lhs, rhs) < 0;
264 struct Type_privateData {
268 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) {
269 sig::Copy(pool, type_, *type);
270 sig::Copy(pool, ffi_, *ffi);
274 struct Struct_privateData :
278 Type_privateData *type_;
280 Struct_privateData() {
284 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
285 static TypeMap Types_;
287 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
288 Struct_privateData *internal(new Struct_privateData());
289 apr_pool_t *pool(internal->pool_);
290 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
291 internal->type_ = typical;
294 internal->owner_ = owner;
295 internal->value_ = data;
297 internal->owner_ = NULL;
299 size_t size(typical->ffi_.size);
300 void *copy(apr_palloc(internal->pool_, size));
301 memcpy(copy, data, size);
302 internal->value_ = copy;
305 return JSObjectMake(context, Struct_, internal);
308 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *type) {
313 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]]) {
314 switch ([[entry objectAtIndex:0] intValue]) {
317 sig::Parse(Pool_, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
324 struct Functor_privateData :
327 sig::Signature signature_;
330 Functor_privateData(const char *type, void (*value)()) :
331 Pointer_privateData(reinterpret_cast<void *>(value))
333 sig::Parse(pool_, &signature_, type, &Structor_);
334 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
341 JSContextRef context_;
342 JSObjectRef function_;
344 ffoData(const char *type) :
345 Functor_privateData(type, NULL)
350 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
352 object = [object retain];
353 Instance_privateData *data(new Instance_privateData(object, transient));
354 return JSObjectMake(context, Instance_, data);
357 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
359 return [value UTF8String];
361 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
362 char *string(new(pool) char[size]);
363 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
364 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
369 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
370 return JSValueMakeBoolean(context, value);
373 JSValueRef CYCastJSValue(JSContextRef context, double value) {
374 return JSValueMakeNumber(context, value);
377 #define CYCastJSValue_(Type_) \
378 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
379 return JSValueMakeNumber(context, static_cast<double>(value)); \
383 CYCastJSValue_(unsigned int)
384 CYCastJSValue_(long int)
385 CYCastJSValue_(long unsigned int)
386 CYCastJSValue_(long long int)
387 CYCastJSValue_(long long unsigned int)
389 JSValueRef CYJSUndefined(JSContextRef context) {
390 return JSValueMakeUndefined(context);
393 size_t CYCastIndex(const char *value) {
394 if (value[0] == '0') {
395 if (value[1] == '\0')
399 size_t index(strtoul(value, &end, 10));
400 if (value + strlen(value) == end)
407 size_t CYCastIndex(NSString *value) {
408 return CYCastIndex([value UTF8String]);
411 @interface NSMethodSignature (Cycript)
412 - (NSString *) _typeString;
415 @interface NSObject (Cycript)
417 - (JSType) cy$JSType;
419 - (NSObject *) cy$toJSON:(NSString *)key;
420 - (NSString *) cy$toCYON;
421 - (NSString *) cy$toKey;
423 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
425 - (NSObject *) cy$getProperty:(NSString *)name;
426 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
427 - (bool) cy$deleteProperty:(NSString *)name;
431 @interface NSString (Cycript)
432 - (void *) cy$symbol;
435 @interface NSNumber (Cycript)
436 - (void *) cy$symbol;
439 struct PropertyAttributes {
444 const char *variable;
457 PropertyAttributes(objc_property_t property) :
469 name = property_getName(property);
470 const char *attributes(property_getAttributes(property));
472 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
474 case 'R': readonly = true; break;
475 case 'C': copy = true; break;
476 case '&': retain = true; break;
477 case 'N': nonatomic = true; break;
478 case 'G': getter_ = token + 1; break;
479 case 'S': setter_ = token + 1; break;
480 case 'V': variable = token + 1; break;
484 /*if (variable == NULL) {
485 variable = property_getName(property);
486 size_t size(strlen(variable));
487 char *name(new(pool_) char[size + 2]);
489 memcpy(name + 1, variable, size);
490 name[size + 1] = '\0';
495 const char *Getter() {
497 getter_ = apr_pstrdup(pool_, name);
501 const char *Setter() {
502 if (setter_ == NULL && !readonly) {
503 size_t length(strlen(name));
505 char *temp(new(pool_) char[length + 5]);
511 temp[3] = toupper(name[0]);
512 memcpy(temp + 4, name + 1, length - 1);
515 temp[length + 3] = ':';
516 temp[length + 4] = '\0';
525 @implementation NSObject (Cycript)
527 - (JSType) cy$JSType {
528 return kJSTypeObject;
531 - (NSObject *) cy$toJSON:(NSString *)key {
532 return [self description];
535 - (NSString *) cy$toCYON {
536 return [[self cy$toJSON:@""] cy$toCYON];
539 - (NSString *) cy$toKey {
540 return [self cy$toCYON];
543 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
544 return CYMakeInstance(context, self, transient);
547 - (NSObject *) cy$getProperty:(NSString *)name {
548 /*if (![name isEqualToString:@"prototype"])
549 NSLog(@"get:%@", name);*/
553 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
554 //NSLog(@"set:%@", name);
558 - (bool) cy$deleteProperty:(NSString *)name {
559 //NSLog(@"delete:%@", name);
565 @implementation WebUndefined (Cycript)
567 - (JSType) cy$JSType {
568 return kJSTypeUndefined;
571 - (NSObject *) cy$toJSON:(NSString *)key {
575 - (NSString *) cy$toCYON {
579 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
580 return CYJSUndefined(context);
585 @implementation NSNull (Cycript)
587 - (JSType) cy$JSType {
591 - (NSObject *) cy$toJSON:(NSString *)key {
595 - (NSString *) cy$toCYON {
601 @implementation NSArray (Cycript)
603 - (NSString *) cy$toCYON {
604 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
605 [json appendString:@"["];
608 for (id object in self) {
610 [json appendString:@","];
613 if ([object cy$JSType] != kJSTypeUndefined)
614 [json appendString:[object cy$toCYON]];
616 [json appendString:@","];
621 [json appendString:@"]"];
625 - (NSObject *) cy$getProperty:(NSString *)name {
626 if ([name isEqualToString:@"length"])
627 return [NSNumber numberWithUnsignedInteger:[self count]];
629 size_t index(CYCastIndex(name));
630 if (index == _not(size_t) || index >= [self count])
631 return [super cy$getProperty:name];
633 return [self objectAtIndex:index];
638 @implementation NSMutableArray (Cycript)
640 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
641 size_t index(CYCastIndex(name));
642 if (index == _not(size_t) || index >= [self count])
643 return [super cy$setProperty:name to:value];
645 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
650 - (bool) cy$deleteProperty:(NSString *)name {
651 size_t index(CYCastIndex(name));
652 if (index == _not(size_t) || index >= [self count])
653 return [super cy$deleteProperty:name];
655 [self removeObjectAtIndex:index];
662 @implementation NSDictionary (Cycript)
664 - (NSString *) cy$toCYON {
665 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
666 [json appendString:@"{"];
669 for (id key in self) {
671 [json appendString:@","];
674 [json appendString:[key cy$toKey]];
675 [json appendString:@":"];
676 NSObject *object([self objectForKey:key]);
677 [json appendString:[object cy$toCYON]];
680 [json appendString:@"}"];
684 - (NSObject *) cy$getProperty:(NSString *)name {
685 return [self objectForKey:name];
690 @implementation NSMutableDictionary (Cycript)
692 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
693 [self setObject:(value ?: [NSNull null]) forKey:name];
697 - (bool) cy$deleteProperty:(NSString *)name {
698 if ([self objectForKey:name] == nil)
701 [self removeObjectForKey:name];
708 @implementation NSNumber (Cycript)
710 - (JSType) cy$JSType {
711 // XXX: this just seems stupid
712 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
715 - (NSObject *) cy$toJSON:(NSString *)key {
719 - (NSString *) cy$toCYON {
720 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
723 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
724 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
727 - (void *) cy$symbol {
728 return [self pointerValue];
733 @implementation NSString (Cycript)
735 - (JSType) cy$JSType {
736 return kJSTypeString;
739 - (NSObject *) cy$toJSON:(NSString *)key {
743 - (NSString *) cy$toCYON {
744 // XXX: this should use the better code from Output.cpp
745 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
747 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
748 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
749 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
750 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
751 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
753 CFStringInsert(json, 0, CFSTR("\""));
754 CFStringAppend(json, CFSTR("\""));
756 return [reinterpret_cast<const NSString *>(json) autorelease];
759 - (NSString *) cy$toKey {
760 const char *value([self UTF8String]);
761 size_t size(strlen(value));
766 if (DigitRange_[value[0]]) {
767 if (CYCastIndex(self) == _not(size_t))
770 if (!WordStartRange_[value[0]])
772 for (size_t i(1); i != size; ++i)
773 if (!WordEndRange_[value[i]])
780 return [self cy$toCYON];
783 - (void *) cy$symbol {
785 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
790 @interface CYJSObject : NSDictionary {
792 JSContextRef context_;
795 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
797 - (NSString *) cy$toJSON:(NSString *)key;
799 - (NSUInteger) count;
800 - (id) objectForKey:(id)key;
801 - (NSEnumerator *) keyEnumerator;
802 - (void) setObject:(id)object forKey:(id)key;
803 - (void) removeObjectForKey:(id)key;
807 @interface CYJSArray : NSArray {
809 JSContextRef context_;
812 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
814 - (NSUInteger) count;
815 - (id) objectAtIndex:(NSUInteger)index;
819 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
820 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
821 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
823 JSGlobalContextRef CYGetJSContext() {
830 @catch (id error) { \
831 CYThrow(context, error, exception); \
835 void CYThrow(JSContextRef context, JSValueRef value);
837 apr_status_t CYPoolRelease_(void *data) {
838 id object(reinterpret_cast<id>(data));
843 id CYPoolRelease(apr_pool_t *pool, id object) {
846 else if (pool == NULL)
847 return [object autorelease];
849 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
854 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
855 return (CFTypeRef) CYPoolRelease(pool, (id) object);
858 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
859 if (JSValueIsObjectOfClass(context, object, Instance_)) {
860 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
861 return data->GetValue();
864 JSValueRef exception(NULL);
865 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
866 CYThrow(context, exception);
867 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
868 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
871 JSStringRef CYCopyJSString(id value) {
872 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
875 JSStringRef CYCopyJSString(const char *value) {
876 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
879 JSStringRef CYCopyJSString(JSStringRef value) {
880 return value == NULL ? NULL : JSStringRetain(value);
883 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
884 if (JSValueIsNull(context, value))
886 JSValueRef exception(NULL);
887 JSStringRef string(JSValueToStringCopy(context, value, &exception));
888 CYThrow(context, exception);
898 JSStringRelease(string_);
902 CYJSString(const CYJSString &rhs) :
903 string_(CYCopyJSString(rhs.string_))
907 template <typename Arg0_>
908 CYJSString(Arg0_ arg0) :
909 string_(CYCopyJSString(arg0))
913 template <typename Arg0_, typename Arg1_>
914 CYJSString(Arg0_ arg0, Arg1_ arg1) :
915 string_(CYCopyJSString(arg0, arg1))
919 CYJSString &operator =(const CYJSString &rhs) {
921 string_ = CYCopyJSString(rhs.string_);
934 operator JSStringRef() const {
939 CFStringRef CYCopyCFString(JSStringRef value) {
940 return JSStringCopyCFString(kCFAllocatorDefault, value);
943 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
944 return CYCopyCFString(CYJSString(context, value));
947 double CYCastDouble(const char *value, size_t size) {
949 double number(strtod(value, &end));
950 if (end != value + size)
955 double CYCastDouble(const char *value) {
956 return CYCastDouble(value, strlen(value));
959 double CYCastDouble(JSContextRef context, JSValueRef value) {
960 JSValueRef exception(NULL);
961 double number(JSValueToNumber(context, value, &exception));
962 CYThrow(context, exception);
966 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
967 double number(CYCastDouble(context, value));
968 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
971 CFStringRef CYCopyCFString(const char *value) {
972 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
975 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
976 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
979 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
980 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
983 bool CYCastBool(JSContextRef context, JSValueRef value) {
984 return JSValueToBoolean(context, value);
987 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
991 switch (JSType type = JSValueGetType(context, value)) {
992 case kJSTypeUndefined:
993 object = [WebUndefined undefined];
1001 case kJSTypeBoolean:
1002 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1007 object = CYCopyCFNumber(context, value);
1012 object = CYCopyCFString(context, value);
1017 // XXX: this might could be more efficient
1018 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1023 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1030 return CYPoolRelease(pool, object);
1032 return CFRetain(object);
1035 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1036 return CYCFType(pool, context, value, true);
1039 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1040 return CYCFType(pool, context, value, false);
1043 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1045 size_t size(JSPropertyNameArrayGetCount(names));
1046 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1047 for (size_t index(0); index != size; ++index)
1048 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1052 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1053 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1056 void CYThrow(JSContextRef context, JSValueRef value) {
1059 @throw CYCastNSObject(NULL, context, value);
1062 JSValueRef CYJSNull(JSContextRef context) {
1063 return JSValueMakeNull(context);
1066 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1067 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1070 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1071 return CYCastJSValue(context, CYJSString(value));
1074 JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = false) {
1075 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
1078 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1079 JSValueRef exception(NULL);
1080 JSObjectRef object(JSValueToObject(context, value, &exception));
1081 CYThrow(context, exception);
1085 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1086 JSValueRef exception(NULL);
1087 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1088 CYThrow(context, exception);
1092 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1093 JSValueRef exception(NULL);
1094 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1095 CYThrow(context, exception);
1099 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1100 JSValueRef exception(NULL);
1101 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1102 CYThrow(context, exception);
1105 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1106 if (exception == NULL)
1108 *exception = CYCastJSValue(context, error);
1111 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1112 JSValueRef exception(NULL);
1113 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1114 CYThrow(context, exception);
1118 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1119 // XXX: this isn't actually correct
1120 return value != NULL && JSValueIsObject(context, value);
1123 @implementation CYJSObject
1125 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1126 if ((self = [super init]) != nil) {
1132 - (NSObject *) cy$toJSON:(NSString *)key {
1133 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1134 if (!CYIsCallable(context_, toJSON))
1135 return [super cy$toJSON:key];
1137 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1138 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1139 // XXX: do I really want an NSNull here?!
1140 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1144 - (NSString *) cy$toCYON {
1145 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1146 if (!CYIsCallable(context_, toCYON))
1147 return [super cy$toCYON];
1149 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1150 return CYCastNSString(NULL, CYJSString(context_, value));
1154 - (NSUInteger) count {
1155 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1156 size_t size(JSPropertyNameArrayGetCount(names));
1157 JSPropertyNameArrayRelease(names);
1161 - (id) objectForKey:(id)key {
1162 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1165 - (NSEnumerator *) keyEnumerator {
1166 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1167 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1168 JSPropertyNameArrayRelease(names);
1172 - (void) setObject:(id)object forKey:(id)key {
1173 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1176 - (void) removeObjectForKey:(id)key {
1177 JSValueRef exception(NULL);
1178 // XXX: this returns a bool... throw exception, or ignore?
1179 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1180 CYThrow(context_, exception);
1185 @implementation CYJSArray
1187 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1188 if ((self = [super init]) != nil) {
1194 - (NSUInteger) count {
1195 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1198 - (id) objectAtIndex:(NSUInteger)index {
1199 JSValueRef exception(NULL);
1200 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1201 CYThrow(context_, exception);
1202 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1207 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1210 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1211 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
1216 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1217 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
1218 const char *string(CYPoolCString(pool, json));
1224 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1228 NSString *self(CYCastNSObject(pool, context, object));
1229 NSString *name(CYCastNSString(pool, property));
1232 if (NSObject *data = [self cy$getProperty:name])
1233 return CYCastJSValue(context, data);
1236 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1237 PropertyAttributes attributes(property);
1238 SEL sel(sel_registerName(attributes.Getter()));
1239 return CYSendMessage(pool, context, self, sel, 0, NULL, exception);
1246 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1250 NSString *self(CYCastNSObject(pool, context, object));
1251 NSString *name(CYCastNSString(pool, property));
1252 NSString *data(CYCastNSObject(pool, context, value));
1255 if ([self cy$setProperty:name to:data])
1259 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1260 PropertyAttributes attributes(property);
1261 if (const char *setter = attributes.Setter()) {
1262 SEL sel(sel_registerName(setter));
1263 JSValueRef arguments[1] = {value};
1264 CYSendMessage(pool, context, self, sel, 1, arguments, exception);
1273 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1276 NSString *self(CYCastNSObject(NULL, context, object));
1277 NSString *name(CYCastNSString(NULL, property));
1278 return [self cy$deleteProperty:name];
1283 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1285 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
1286 return CYMakeInstance(context, [data->GetValue() alloc], true);
1290 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1291 Selector_privateData *data(new Selector_privateData(sel));
1292 return JSObjectMake(context, Selector_, data);
1295 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
1296 Pointer_privateData *data(new Pointer_privateData(pointer));
1297 return JSObjectMake(context, Pointer_, data);
1300 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1301 Functor_privateData *data(new Functor_privateData(type, function));
1302 return JSObjectMake(context, Functor_, data);
1305 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1307 const char *string([CYCastNSString(NULL, value) UTF8String]);
1309 *length = strlen(string);
1312 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1313 char *string(new(pool) char[size]);
1314 JSStringGetUTF8CString(value, string, size);
1315 // XXX: this is ironic
1317 *length = strlen(string);
1322 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1323 if (!JSValueIsNull(context, value))
1324 return CYPoolCString(pool, CYJSString(context, value), length);
1332 // XXX: this macro is unhygenic
1333 #define CYCastCString(context, value) ({ \
1335 if (value == NULL) \
1337 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1338 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1339 utf8 = reinterpret_cast<char *>(alloca(size)); \
1340 JSStringGetUTF8CString(string, utf8, size); \
1341 JSStringRelease(string); \
1347 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1348 switch (JSValueGetType(context, value)) {
1351 /*case kJSTypeString:
1352 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1354 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1355 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1356 return data->value_;
1359 double number(CYCastDouble(context, value));
1360 if (std::isnan(number))
1361 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1362 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1366 template <typename Type_>
1367 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1368 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1371 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1372 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1373 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1374 return reinterpret_cast<SEL>(data->value_);
1376 return CYCastPointer<SEL>(context, value);
1379 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1380 switch (type->primitive) {
1381 case sig::boolean_P:
1382 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1385 #define CYPoolFFI_(primitive, native) \
1386 case sig::primitive ## _P: \
1387 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1390 CYPoolFFI_(uchar, unsigned char)
1391 CYPoolFFI_(char, char)
1392 CYPoolFFI_(ushort, unsigned short)
1393 CYPoolFFI_(short, short)
1394 CYPoolFFI_(ulong, unsigned long)
1395 CYPoolFFI_(long, long)
1396 CYPoolFFI_(uint, unsigned int)
1397 CYPoolFFI_(int, int)
1398 CYPoolFFI_(ulonglong, unsigned long long)
1399 CYPoolFFI_(longlong, long long)
1400 CYPoolFFI_(float, float)
1401 CYPoolFFI_(double, double)
1404 case sig::typename_P:
1405 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1408 case sig::selector_P:
1409 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1412 case sig::pointer_P:
1413 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1417 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1420 case sig::struct_P: {
1421 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1422 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1423 for (size_t index(0); index != type->data.signature.count; ++index) {
1424 sig::Element *element(&type->data.signature.elements[index]);
1425 ffi_type *field(ffi->elements[index]);
1428 if (aggregate == NULL)
1431 rhs = CYGetProperty(context, aggregate, index);
1432 if (JSValueIsUndefined(context, rhs)) {
1433 if (element->name != NULL)
1434 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1437 if (JSValueIsUndefined(context, rhs)) undefined:
1438 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1442 CYPoolFFI(pool, context, element->type, field, base, rhs);
1444 base += field->size;
1452 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1457 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
1460 switch (type->primitive) {
1461 case sig::boolean_P:
1462 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1465 #define CYFromFFI_(primitive, native) \
1466 case sig::primitive ## _P: \
1467 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1470 CYFromFFI_(uchar, unsigned char)
1471 CYFromFFI_(char, char)
1472 CYFromFFI_(ushort, unsigned short)
1473 CYFromFFI_(short, short)
1474 CYFromFFI_(ulong, unsigned long)
1475 CYFromFFI_(long, long)
1476 CYFromFFI_(uint, unsigned int)
1477 CYFromFFI_(int, int)
1478 CYFromFFI_(ulonglong, unsigned long long)
1479 CYFromFFI_(longlong, long long)
1480 CYFromFFI_(float, float)
1481 CYFromFFI_(double, double)
1484 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
1487 case sig::typename_P:
1488 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1491 case sig::selector_P:
1492 if (SEL sel = *reinterpret_cast<SEL *>(data))
1493 value = CYMakeSelector(context, sel);
1497 case sig::pointer_P:
1498 if (void *pointer = *reinterpret_cast<void **>(data))
1499 value = CYMakePointer(context, pointer);
1504 if (char *utf8 = *reinterpret_cast<char **>(data))
1505 value = CYCastJSValue(context, utf8);
1510 value = CYMakeStruct(context, data, type, ffi, owner);
1514 value = CYJSUndefined(context);
1518 value = CYJSNull(context);
1522 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1529 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1530 Type_privateData *typical(internal->type_);
1533 const char *name(CYPoolCString(pool, property, &length));
1534 double number(CYCastDouble(name, length));
1536 size_t count(typical->type_.data.signature.count);
1538 if (std::isnan(number)) {
1539 if (property == NULL)
1542 sig::Element *elements(typical->type_.data.signature.elements);
1544 for (size_t local(0); local != count; ++local) {
1545 sig::Element *element(&elements[local]);
1546 if (element->name != NULL && strcmp(name, element->name) == 0) {
1554 index = static_cast<ssize_t>(number);
1555 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1560 base = reinterpret_cast<uint8_t *>(internal->value_);
1561 for (ssize_t local(0); local != index; ++local)
1562 base += typical->ffi_.elements[local]->size;
1567 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1569 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1570 Type_privateData *typical(internal->type_);
1575 if (!Index_(pool, internal, property, index, base))
1579 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
1583 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1585 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1586 Type_privateData *typical(internal->type_);
1591 if (!Index_(pool, internal, property, index, base))
1595 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1600 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1601 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1602 Type_privateData *typical(internal->type_);
1604 size_t count(typical->type_.data.signature.count);
1605 sig::Element *elements(typical->type_.data.signature.elements);
1609 for (size_t index(0); index != count; ++index) {
1611 name = elements[index].name;
1614 sprintf(number, "%lu", index);
1618 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1622 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)()) {
1624 if (setups + count != signature->count - 1)
1625 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1627 size_t size(setups + count);
1629 memcpy(values, setup, sizeof(void *) * setups);
1631 for (size_t index(setups); index != size; ++index) {
1632 sig::Element *element(&signature->elements[index + 1]);
1633 ffi_type *ffi(cif->arg_types[index]);
1635 values[index] = new(pool) uint8_t[ffi->size];
1636 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1639 uint8_t value[cif->rtype->size];
1640 ffi_call(cif, function, value, values);
1642 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
1646 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1647 ffoData *data(reinterpret_cast<ffoData *>(arg));
1649 JSContextRef context(data->context_);
1651 size_t count(data->cif_.nargs);
1652 JSValueRef values[count];
1654 for (size_t index(0); index != count; ++index)
1655 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1657 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1658 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1661 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1662 // XXX: in case of exceptions this will leak
1663 ffoData *data(new ffoData(type));
1665 ffi_closure *closure;
1666 _syscall(closure = (ffi_closure *) mmap(
1667 NULL, sizeof(ffi_closure),
1668 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1672 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1673 _assert(status == FFI_OK);
1675 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1677 data->value_ = closure;
1679 data->context_ = CYGetJSContext();
1680 data->function_ = function;
1682 return JSObjectMake(context, Functor_, data);
1685 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1688 NSString *name(CYCastNSString(pool, property));
1689 if (Class _class = NSClassFromString(name))
1690 return CYMakeInstance(context, _class, true);
1691 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1692 switch ([[entry objectAtIndex:0] intValue]) {
1694 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1696 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1698 // XXX: this is horrendously inefficient
1699 sig::Signature signature;
1700 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
1702 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1703 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
1709 bool stret(ffi_type *ffi_type) {
1710 return ffi_type->type == FFI_TYPE_STRUCT && (
1711 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1712 struct_forward_array[ffi_type->size] != 0
1717 int *_NSGetArgc(void);
1718 char ***_NSGetArgv(void);
1719 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1722 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1724 NSLog(@"%s", CYCastCString(context, arguments[0]));
1725 return CYJSUndefined(context);
1729 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1733 int argc(CYCastDouble(context, arguments[0]));
1734 char **argv(CYCastPointer<char **>(context, arguments[1]));
1735 NSString *principal(CYCastNSObject(pool, context, arguments[2]));
1736 NSString *delegate(CYCastNSObject(pool, context, arguments[3]));
1738 argc = *_NSGetArgc() - 1;
1739 argv = *_NSGetArgv() + 1;
1740 for (int i(0); i != argc; ++i)
1741 NSLog(@"argv[%i]=%s", i, argv[i]);
1744 return CYCastJSValue(context, UIApplicationMain(argc, argv, principal, delegate));
1748 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1751 Class _class(object_getClass(self));
1752 if (Method method = class_getInstanceMethod(_class, _cmd))
1753 type = method_getTypeEncoding(method);
1756 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1758 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1759 type = CYPoolCString(pool, [method _typeString]);
1767 sig::Signature signature;
1768 sig::Parse(pool, &signature, type, &Structor_);
1771 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1773 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1774 return CYCallFunction(pool, context, 2, setup, count, arguments, exception, &signature, &cif, function);
1777 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1785 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1787 self = CYCastNSObject(pool, context, arguments[0]);
1789 return CYJSNull(context);
1791 _cmd = CYCastSEL(context, arguments[1]);
1794 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, exception);
1797 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1798 JSValueRef setup[count + 2];
1801 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
1802 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1805 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1807 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1808 return CYCallFunction(pool, context, 0, NULL, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1811 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1814 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1815 const char *name(CYCastCString(context, arguments[0]));
1816 return CYMakeSelector(context, sel_registerName(name));
1820 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1823 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1824 const char *type(CYCastCString(context, arguments[1]));
1825 JSValueRef exception(NULL);
1826 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1827 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1828 return CYMakeFunctor(context, function, type);
1829 } else if (exception != NULL) {
1832 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1833 return CYMakeFunctor(context, function, type);
1838 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1839 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
1840 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1843 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1847 static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1849 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1850 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1854 static JSValueRef Pointer_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1855 return Pointer_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1858 static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1860 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1862 sprintf(string, "%p", data->value_);
1863 return CYCastJSValue(context, string);
1867 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1869 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1871 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
1876 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1878 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1880 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
1881 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
1886 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1888 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1890 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
1895 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1897 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1898 return CYCastJSValue(context, sel_getName(data->GetValue()));
1902 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1903 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
1906 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1908 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1909 const char *name(sel_getName(data->GetValue()));
1911 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
1916 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1919 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1921 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1922 Class _class(CYCastNSObject(pool, context, arguments[0]));
1923 bool instance(CYCastBool(context, arguments[1]));
1924 SEL sel(data->GetValue());
1925 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1926 return CYCastJSValue(context, method_getTypeEncoding(method));
1927 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1928 return CYCastJSValue(context, CYJSString(type));
1930 return CYJSNull(context);
1934 static JSStaticValue Pointer_staticValues[2] = {
1935 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1936 {NULL, NULL, NULL, 0}
1939 static JSStaticFunction Pointer_staticFunctions[4] = {
1940 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1941 {"toJSON", &Pointer_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1942 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1946 /*static JSStaticValue Selector_staticValues[2] = {
1947 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1948 {NULL, NULL, NULL, 0}
1951 static JSStaticFunction Instance_staticFunctions[4] = {
1952 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1953 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1954 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1958 static JSStaticFunction Selector_staticFunctions[5] = {
1959 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1960 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1961 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1962 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1966 CYDriver::CYDriver(const std::string &filename) :
1970 filename_(filename),
1976 CYDriver::~CYDriver() {
1980 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1981 CYDriver::Error error;
1982 error.location_ = location;
1983 error.message_ = message;
1984 driver.errors_.push_back(error);
1987 void CYSetArgs(int argc, const char *argv[]) {
1988 JSContextRef context(CYGetJSContext());
1989 JSValueRef args[argc];
1990 for (int i(0); i != argc; ++i)
1991 args[i] = CYCastJSValue(context, argv[i]);
1992 JSValueRef exception(NULL);
1993 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1994 CYThrow(context, exception);
1995 CYSetProperty(context, System_, CYJSString("args"), array);
1998 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1999 return JSContextGetGlobalObject(context);
2002 MSInitialize { _pooled
2005 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2007 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2009 JSClassDefinition definition;
2011 definition = kJSClassDefinitionEmpty;
2012 definition.className = "Pointer";
2013 definition.staticValues = Pointer_staticValues;
2014 definition.staticFunctions = Pointer_staticFunctions;
2015 definition.finalize = &CYData::Finalize;
2016 Pointer_ = JSClassCreate(&definition);
2018 definition = kJSClassDefinitionEmpty;
2019 definition.className = "Functor";
2020 definition.staticValues = Pointer_staticValues;
2021 definition.staticFunctions = Pointer_staticFunctions;
2022 definition.callAsFunction = &Functor_callAsFunction;
2023 definition.finalize = &CYData::Finalize;
2024 Functor_ = JSClassCreate(&definition);
2026 definition = kJSClassDefinitionEmpty;
2027 definition.className = "Struct";
2028 definition.getProperty = &Struct_getProperty;
2029 definition.setProperty = &Struct_setProperty;
2030 definition.getPropertyNames = &Struct_getPropertyNames;
2031 definition.finalize = &CYData::Finalize;
2032 Struct_ = JSClassCreate(&definition);
2034 definition = kJSClassDefinitionEmpty;
2035 definition.className = "Selector";
2036 definition.staticValues = Pointer_staticValues;
2037 //definition.staticValues = Selector_staticValues;
2038 definition.staticFunctions = Selector_staticFunctions;
2039 definition.callAsFunction = &Selector_callAsFunction;
2040 definition.finalize = &CYData::Finalize;
2041 Selector_ = JSClassCreate(&definition);
2043 definition = kJSClassDefinitionEmpty;
2044 definition.className = "Instance";
2045 definition.staticValues = Pointer_staticValues;
2046 definition.staticFunctions = Instance_staticFunctions;
2047 definition.getProperty = &Instance_getProperty;
2048 definition.setProperty = &Instance_setProperty;
2049 definition.deleteProperty = &Instance_deleteProperty;
2050 definition.callAsConstructor = &Instance_callAsConstructor;
2051 definition.finalize = &CYData::Finalize;
2052 Instance_ = JSClassCreate(&definition);
2054 definition = kJSClassDefinitionEmpty;
2055 definition.className = "Runtime";
2056 definition.getProperty = &Runtime_getProperty;
2057 Runtime_ = JSClassCreate(&definition);
2059 definition = kJSClassDefinitionEmpty;
2060 //definition.getProperty = &Global_getProperty;
2061 JSClassRef Global(JSClassCreate(&definition));
2063 JSGlobalContextRef context(JSGlobalContextCreate(Global));
2066 JSObjectRef global(CYGetGlobalObject(context));
2068 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
2069 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
2071 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
2072 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
2074 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
2075 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2077 System_ = JSObjectMake(context, NULL, NULL);
2078 CYSetProperty(context, global, CYJSString("system"), System_);
2079 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
2080 //CYSetProperty(context, System_, CYJSString("global"), global);
2082 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2084 length_ = JSStringCreateWithUTF8CString("length");
2085 message_ = JSStringCreateWithUTF8CString("message");
2086 name_ = JSStringCreateWithUTF8CString("name");
2087 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2088 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
2090 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2091 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));