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_);
176 Transient = (1 << 0),
177 Uninitialized = (1 << 1),
182 Instance(id value, Flags flags) :
183 Pointer_privateData(value),
188 virtual ~Instance() {
189 if ((flags_ & Transient) == 0)
190 [GetValue() release];
193 static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
194 return JSObjectMake(context, Instance_, new Instance(object, flags));
197 id GetValue() const {
198 return reinterpret_cast<id>(value_);
201 bool IsUninitialized() const {
202 return (flags_ & Uninitialized) != 0;
208 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
210 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
211 lhs.name = apr_pstrdup(pool, rhs.name);
212 if (rhs.type == NULL)
215 lhs.type = new(pool) Type;
216 Copy(pool, *lhs.type, *rhs.type);
218 lhs.offset = rhs.offset;
221 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
222 size_t count(rhs.count);
224 lhs.elements = new(pool) Element[count];
225 for (size_t index(0); index != count; ++index)
226 Copy(pool, lhs.elements[index], rhs.elements[index]);
229 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
230 lhs.primitive = rhs.primitive;
231 lhs.name = apr_pstrdup(pool, rhs.name);
232 lhs.flags = rhs.flags;
234 if (sig::IsAggregate(rhs.primitive))
235 Copy(pool, lhs.data.signature, rhs.data.signature);
237 if (rhs.data.data.type != NULL) {
238 lhs.data.data.type = new(pool) Type;
239 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
242 lhs.data.data.size = rhs.data.data.size;
246 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
248 lhs.alignment = rhs.alignment;
250 if (rhs.elements == NULL)
254 while (rhs.elements[count] != NULL)
257 lhs.elements = new(pool) ffi_type *[count + 1];
258 lhs.elements[count] = NULL;
260 for (size_t index(0); index != count; ++index) {
261 // XXX: if these are libffi native then you can just take them
262 ffi_type *ffi(new(pool) ffi_type);
263 lhs.elements[index] = ffi;
264 sig::Copy(pool, *ffi, *rhs.elements[index]);
271 struct CStringMapLess :
272 std::binary_function<const char *, const char *, bool>
274 _finline bool operator ()(const char *lhs, const char *rhs) const {
275 return strcmp(lhs, rhs) < 0;
279 struct Type_privateData {
283 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) {
284 sig::Copy(pool, type_, *type);
285 sig::Copy(pool, ffi_, *ffi);
289 struct Struct_privateData :
293 Type_privateData *type_;
295 Struct_privateData() {
299 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
300 static TypeMap Types_;
302 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
303 Struct_privateData *internal(new Struct_privateData());
304 apr_pool_t *pool(internal->pool_);
305 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
306 internal->type_ = typical;
309 internal->owner_ = owner;
310 internal->value_ = data;
312 internal->owner_ = NULL;
314 size_t size(typical->ffi_.size);
315 void *copy(apr_palloc(internal->pool_, size));
316 memcpy(copy, data, size);
317 internal->value_ = copy;
320 return JSObjectMake(context, Struct_, internal);
323 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *type) {
328 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]]) {
329 switch ([[entry objectAtIndex:0] intValue]) {
332 sig::Parse(Pool_, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
339 struct Functor_privateData :
342 sig::Signature signature_;
345 Functor_privateData(const char *type, void (*value)()) :
346 Pointer_privateData(reinterpret_cast<void *>(value))
348 sig::Parse(pool_, &signature_, type, &Structor_);
349 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
356 JSContextRef context_;
357 JSObjectRef function_;
359 ffoData(const char *type) :
360 Functor_privateData(type, NULL)
365 JSValueRef CYMakeInstance(JSContextRef context, id object, bool transient) {
366 Instance::Flags flags;
369 flags = Instance::Transient;
371 flags = Instance::None;
372 object = [object retain];
375 return Instance::Make(context, object, flags);
378 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
380 return [value UTF8String];
382 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
383 char *string(new(pool) char[size]);
384 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
385 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
390 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
391 return JSValueMakeBoolean(context, value);
394 JSValueRef CYCastJSValue(JSContextRef context, double value) {
395 return JSValueMakeNumber(context, value);
398 #define CYCastJSValue_(Type_) \
399 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
400 return JSValueMakeNumber(context, static_cast<double>(value)); \
404 CYCastJSValue_(unsigned int)
405 CYCastJSValue_(long int)
406 CYCastJSValue_(long unsigned int)
407 CYCastJSValue_(long long int)
408 CYCastJSValue_(long long unsigned int)
410 JSValueRef CYJSUndefined(JSContextRef context) {
411 return JSValueMakeUndefined(context);
414 size_t CYCastIndex(const char *value) {
415 if (value[0] == '0') {
416 if (value[1] == '\0')
420 size_t index(strtoul(value, &end, 10));
421 if (value + strlen(value) == end)
428 size_t CYCastIndex(NSString *value) {
429 return CYCastIndex([value UTF8String]);
432 @interface NSMethodSignature (Cycript)
433 - (NSString *) _typeString;
436 @interface NSObject (Cycript)
438 - (JSType) cy$JSType;
440 - (NSObject *) cy$toJSON:(NSString *)key;
441 - (NSString *) cy$toCYON;
442 - (NSString *) cy$toKey;
444 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
446 - (NSObject *) cy$getProperty:(NSString *)name;
447 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
448 - (bool) cy$deleteProperty:(NSString *)name;
452 @interface NSString (Cycript)
453 - (void *) cy$symbol;
456 @interface NSNumber (Cycript)
457 - (void *) cy$symbol;
460 struct PropertyAttributes {
465 const char *variable;
478 PropertyAttributes(objc_property_t property) :
490 name = property_getName(property);
491 const char *attributes(property_getAttributes(property));
493 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
495 case 'R': readonly = true; break;
496 case 'C': copy = true; break;
497 case '&': retain = true; break;
498 case 'N': nonatomic = true; break;
499 case 'G': getter_ = token + 1; break;
500 case 'S': setter_ = token + 1; break;
501 case 'V': variable = token + 1; break;
505 /*if (variable == NULL) {
506 variable = property_getName(property);
507 size_t size(strlen(variable));
508 char *name(new(pool_) char[size + 2]);
510 memcpy(name + 1, variable, size);
511 name[size + 1] = '\0';
516 const char *Getter() {
518 getter_ = apr_pstrdup(pool_, name);
522 const char *Setter() {
523 if (setter_ == NULL && !readonly) {
524 size_t length(strlen(name));
526 char *temp(new(pool_) char[length + 5]);
532 temp[3] = toupper(name[0]);
533 memcpy(temp + 4, name + 1, length - 1);
536 temp[length + 3] = ':';
537 temp[length + 4] = '\0';
546 @implementation NSObject (Cycript)
548 - (JSType) cy$JSType {
549 return kJSTypeObject;
552 - (NSObject *) cy$toJSON:(NSString *)key {
553 return [self description];
556 - (NSString *) cy$toCYON {
557 return [[self cy$toJSON:@""] cy$toCYON];
560 - (NSString *) cy$toKey {
561 return [self cy$toCYON];
564 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
565 return CYMakeInstance(context, self, false);
568 - (NSObject *) cy$getProperty:(NSString *)name {
569 /*if (![name isEqualToString:@"prototype"])
570 NSLog(@"get:%@", name);*/
574 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
575 //NSLog(@"set:%@", name);
579 - (bool) cy$deleteProperty:(NSString *)name {
580 //NSLog(@"delete:%@", name);
586 @implementation WebUndefined (Cycript)
588 - (JSType) cy$JSType {
589 return kJSTypeUndefined;
592 - (NSObject *) cy$toJSON:(NSString *)key {
596 - (NSString *) cy$toCYON {
600 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
601 return CYJSUndefined(context);
606 @implementation NSNull (Cycript)
608 - (JSType) cy$JSType {
612 - (NSObject *) cy$toJSON:(NSString *)key {
616 - (NSString *) cy$toCYON {
622 @implementation NSArray (Cycript)
624 - (NSString *) cy$toCYON {
625 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
626 [json appendString:@"["];
629 for (id object in self) {
631 [json appendString:@","];
634 if ([object cy$JSType] != kJSTypeUndefined)
635 [json appendString:[object cy$toCYON]];
637 [json appendString:@","];
642 [json appendString:@"]"];
646 - (NSObject *) cy$getProperty:(NSString *)name {
647 if ([name isEqualToString:@"length"])
648 return [NSNumber numberWithUnsignedInteger:[self count]];
650 size_t index(CYCastIndex(name));
651 if (index == _not(size_t) || index >= [self count])
652 return [super cy$getProperty:name];
654 return [self objectAtIndex:index];
659 @implementation NSMutableArray (Cycript)
661 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
662 size_t index(CYCastIndex(name));
663 if (index == _not(size_t) || index >= [self count])
664 return [super cy$setProperty:name to:value];
666 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
671 - (bool) cy$deleteProperty:(NSString *)name {
672 size_t index(CYCastIndex(name));
673 if (index == _not(size_t) || index >= [self count])
674 return [super cy$deleteProperty:name];
676 [self removeObjectAtIndex:index];
683 @implementation NSDictionary (Cycript)
685 - (NSString *) cy$toCYON {
686 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
687 [json appendString:@"{"];
690 for (id key in self) {
692 [json appendString:@","];
695 [json appendString:[key cy$toKey]];
696 [json appendString:@":"];
697 NSObject *object([self objectForKey:key]);
698 [json appendString:[object cy$toCYON]];
701 [json appendString:@"}"];
705 - (NSObject *) cy$getProperty:(NSString *)name {
706 return [self objectForKey:name];
711 @implementation NSMutableDictionary (Cycript)
713 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
714 [self setObject:(value ?: [NSNull null]) forKey:name];
718 - (bool) cy$deleteProperty:(NSString *)name {
719 if ([self objectForKey:name] == nil)
722 [self removeObjectForKey:name];
729 @implementation NSNumber (Cycript)
731 - (JSType) cy$JSType {
732 // XXX: this just seems stupid
733 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
736 - (NSObject *) cy$toJSON:(NSString *)key {
740 - (NSString *) cy$toCYON {
741 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
744 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
745 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
748 - (void *) cy$symbol {
749 return [self pointerValue];
754 @implementation NSString (Cycript)
756 - (JSType) cy$JSType {
757 return kJSTypeString;
760 - (NSObject *) cy$toJSON:(NSString *)key {
764 - (NSString *) cy$toCYON {
765 // XXX: this should use the better code from Output.cpp
766 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
768 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
769 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
770 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
771 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
772 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
774 CFStringInsert(json, 0, CFSTR("\""));
775 CFStringAppend(json, CFSTR("\""));
777 return [reinterpret_cast<const NSString *>(json) autorelease];
780 - (NSString *) cy$toKey {
781 const char *value([self UTF8String]);
782 size_t size(strlen(value));
787 if (DigitRange_[value[0]]) {
788 if (CYCastIndex(self) == _not(size_t))
791 if (!WordStartRange_[value[0]])
793 for (size_t i(1); i != size; ++i)
794 if (!WordEndRange_[value[i]])
801 return [self cy$toCYON];
804 - (void *) cy$symbol {
806 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
811 @interface CYJSObject : NSDictionary {
813 JSContextRef context_;
816 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
818 - (NSString *) cy$toJSON:(NSString *)key;
820 - (NSUInteger) count;
821 - (id) objectForKey:(id)key;
822 - (NSEnumerator *) keyEnumerator;
823 - (void) setObject:(id)object forKey:(id)key;
824 - (void) removeObjectForKey:(id)key;
828 @interface CYJSArray : NSArray {
830 JSContextRef context_;
833 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
835 - (NSUInteger) count;
836 - (id) objectAtIndex:(NSUInteger)index;
840 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
841 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
842 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
844 JSGlobalContextRef CYGetJSContext() {
851 @catch (id error) { \
852 CYThrow(context, error, exception); \
856 void CYThrow(JSContextRef context, JSValueRef value);
858 apr_status_t CYPoolRelease_(void *data) {
859 id object(reinterpret_cast<id>(data));
864 id CYPoolRelease(apr_pool_t *pool, id object) {
867 else if (pool == NULL)
868 return [object autorelease];
870 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
875 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
876 return (CFTypeRef) CYPoolRelease(pool, (id) object);
879 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
880 JSValueRef exception(NULL);
881 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
882 CYThrow(context, exception);
883 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
884 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
887 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
888 if (!JSValueIsObjectOfClass(context, object, Instance_))
889 return CYCastNSObject_(pool, context, object);
891 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
892 return data->GetValue();
896 JSStringRef CYCopyJSString(id value) {
897 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
900 JSStringRef CYCopyJSString(const char *value) {
901 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
904 JSStringRef CYCopyJSString(JSStringRef value) {
905 return value == NULL ? NULL : JSStringRetain(value);
908 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
909 if (JSValueIsNull(context, value))
911 JSValueRef exception(NULL);
912 JSStringRef string(JSValueToStringCopy(context, value, &exception));
913 CYThrow(context, exception);
923 JSStringRelease(string_);
927 CYJSString(const CYJSString &rhs) :
928 string_(CYCopyJSString(rhs.string_))
932 template <typename Arg0_>
933 CYJSString(Arg0_ arg0) :
934 string_(CYCopyJSString(arg0))
938 template <typename Arg0_, typename Arg1_>
939 CYJSString(Arg0_ arg0, Arg1_ arg1) :
940 string_(CYCopyJSString(arg0, arg1))
944 CYJSString &operator =(const CYJSString &rhs) {
946 string_ = CYCopyJSString(rhs.string_);
959 operator JSStringRef() const {
964 CFStringRef CYCopyCFString(JSStringRef value) {
965 return JSStringCopyCFString(kCFAllocatorDefault, value);
968 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
969 return CYCopyCFString(CYJSString(context, value));
972 double CYCastDouble(const char *value, size_t size) {
974 double number(strtod(value, &end));
975 if (end != value + size)
980 double CYCastDouble(const char *value) {
981 return CYCastDouble(value, strlen(value));
984 double CYCastDouble(JSContextRef context, JSValueRef value) {
985 JSValueRef exception(NULL);
986 double number(JSValueToNumber(context, value, &exception));
987 CYThrow(context, exception);
991 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
992 double number(CYCastDouble(context, value));
993 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
996 CFStringRef CYCopyCFString(const char *value) {
997 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1000 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1001 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1004 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1005 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1008 bool CYCastBool(JSContextRef context, JSValueRef value) {
1009 return JSValueToBoolean(context, value);
1012 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1016 switch (JSType type = JSValueGetType(context, value)) {
1017 case kJSTypeUndefined:
1018 object = [WebUndefined undefined];
1026 case kJSTypeBoolean:
1027 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1032 object = CYCopyCFNumber(context, value);
1037 object = CYCopyCFString(context, value);
1042 // XXX: this might could be more efficient
1043 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1048 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1055 return CYPoolRelease(pool, object);
1057 return CFRetain(object);
1060 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1061 return CYCFType(pool, context, value, true);
1064 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1065 return CYCFType(pool, context, value, false);
1068 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1070 size_t size(JSPropertyNameArrayGetCount(names));
1071 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1072 for (size_t index(0); index != size; ++index)
1073 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1077 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1078 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1081 void CYThrow(JSContextRef context, JSValueRef value) {
1084 @throw CYCastNSObject(NULL, context, value);
1087 JSValueRef CYJSNull(JSContextRef context) {
1088 return JSValueMakeNull(context);
1091 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1092 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1095 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1096 return CYCastJSValue(context, CYJSString(value));
1099 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1100 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context];
1103 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1104 JSValueRef exception(NULL);
1105 JSObjectRef object(JSValueToObject(context, value, &exception));
1106 CYThrow(context, exception);
1110 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1111 JSValueRef exception(NULL);
1112 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1113 CYThrow(context, exception);
1117 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1118 JSValueRef exception(NULL);
1119 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1120 CYThrow(context, exception);
1124 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1125 JSValueRef exception(NULL);
1126 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1127 CYThrow(context, exception);
1130 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1131 if (exception == NULL)
1133 *exception = CYCastJSValue(context, error);
1136 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1137 JSValueRef exception(NULL);
1138 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1139 CYThrow(context, exception);
1143 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1144 // XXX: this isn't actually correct
1145 return value != NULL && JSValueIsObject(context, value);
1148 @implementation CYJSObject
1150 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1151 if ((self = [super init]) != nil) {
1157 - (NSObject *) cy$toJSON:(NSString *)key {
1158 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1159 if (!CYIsCallable(context_, toJSON))
1160 return [super cy$toJSON:key];
1162 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1163 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1164 // XXX: do I really want an NSNull here?!
1165 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1169 - (NSString *) cy$toCYON {
1170 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1171 if (!CYIsCallable(context_, toCYON))
1172 return [super cy$toCYON];
1174 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1175 return CYCastNSString(NULL, CYJSString(context_, value));
1179 - (NSUInteger) count {
1180 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1181 size_t size(JSPropertyNameArrayGetCount(names));
1182 JSPropertyNameArrayRelease(names);
1186 - (id) objectForKey:(id)key {
1187 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1190 - (NSEnumerator *) keyEnumerator {
1191 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1192 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1193 JSPropertyNameArrayRelease(names);
1197 - (void) setObject:(id)object forKey:(id)key {
1198 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1201 - (void) removeObjectForKey:(id)key {
1202 JSValueRef exception(NULL);
1203 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1204 CYThrow(context_, exception);
1209 @implementation CYJSArray
1211 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1212 if ((self = [super init]) != nil) {
1218 - (NSUInteger) count {
1219 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1222 - (id) objectAtIndex:(NSUInteger)index {
1223 JSValueRef exception(NULL);
1224 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1225 CYThrow(context_, exception);
1226 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1231 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1234 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1235 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
1240 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1241 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
1242 const char *string(CYPoolCString(pool, json));
1248 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1252 NSString *self(CYCastNSObject(pool, context, object));
1253 NSString *name(CYCastNSString(pool, property));
1256 if (NSObject *data = [self cy$getProperty:name])
1257 return CYCastJSValue(context, data);
1260 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1261 PropertyAttributes attributes(property);
1262 SEL sel(sel_registerName(attributes.Getter()));
1263 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
1270 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1274 NSString *self(CYCastNSObject(pool, context, object));
1275 NSString *name(CYCastNSString(pool, property));
1276 NSString *data(CYCastNSObject(pool, context, value));
1279 if ([self cy$setProperty:name to:data])
1283 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1284 PropertyAttributes attributes(property);
1285 if (const char *setter = attributes.Setter()) {
1286 SEL sel(sel_registerName(setter));
1287 JSValueRef arguments[1] = {value};
1288 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
1297 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1300 NSString *self(CYCastNSObject(NULL, context, object));
1301 NSString *name(CYCastNSString(NULL, property));
1302 return [self cy$deleteProperty:name];
1307 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1309 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1310 JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
1315 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1316 Selector_privateData *data(new Selector_privateData(sel));
1317 return JSObjectMake(context, Selector_, data);
1320 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
1321 Pointer_privateData *data(new Pointer_privateData(pointer));
1322 return JSObjectMake(context, Pointer_, data);
1325 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1326 Functor_privateData *data(new Functor_privateData(type, function));
1327 return JSObjectMake(context, Functor_, data);
1330 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1332 const char *string([CYCastNSString(NULL, value) UTF8String]);
1334 *length = strlen(string);
1337 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1338 char *string(new(pool) char[size]);
1339 JSStringGetUTF8CString(value, string, size);
1340 // XXX: this is ironic
1342 *length = strlen(string);
1347 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1348 if (!JSValueIsNull(context, value))
1349 return CYPoolCString(pool, CYJSString(context, value), length);
1357 // XXX: this macro is unhygenic
1358 #define CYCastCString(context, value) ({ \
1360 if (value == NULL) \
1362 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1363 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1364 utf8 = reinterpret_cast<char *>(alloca(size)); \
1365 JSStringGetUTF8CString(string, utf8, size); \
1366 JSStringRelease(string); \
1372 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1373 switch (JSValueGetType(context, value)) {
1376 /*case kJSTypeString:
1377 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1379 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1380 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1381 return data->value_;
1384 double number(CYCastDouble(context, value));
1385 if (std::isnan(number))
1386 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1387 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1391 template <typename Type_>
1392 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1393 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1396 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1397 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1398 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1399 return reinterpret_cast<SEL>(data->value_);
1401 return CYCastPointer<SEL>(context, value);
1404 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1405 switch (type->primitive) {
1406 case sig::boolean_P:
1407 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1410 #define CYPoolFFI_(primitive, native) \
1411 case sig::primitive ## _P: \
1412 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1415 CYPoolFFI_(uchar, unsigned char)
1416 CYPoolFFI_(char, char)
1417 CYPoolFFI_(ushort, unsigned short)
1418 CYPoolFFI_(short, short)
1419 CYPoolFFI_(ulong, unsigned long)
1420 CYPoolFFI_(long, long)
1421 CYPoolFFI_(uint, unsigned int)
1422 CYPoolFFI_(int, int)
1423 CYPoolFFI_(ulonglong, unsigned long long)
1424 CYPoolFFI_(longlong, long long)
1425 CYPoolFFI_(float, float)
1426 CYPoolFFI_(double, double)
1429 case sig::typename_P:
1430 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1433 case sig::selector_P:
1434 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1437 case sig::pointer_P:
1438 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1442 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1445 case sig::struct_P: {
1446 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1447 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1448 for (size_t index(0); index != type->data.signature.count; ++index) {
1449 sig::Element *element(&type->data.signature.elements[index]);
1450 ffi_type *field(ffi->elements[index]);
1453 if (aggregate == NULL)
1456 rhs = CYGetProperty(context, aggregate, index);
1457 if (JSValueIsUndefined(context, rhs)) {
1458 if (element->name != NULL)
1459 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1462 if (JSValueIsUndefined(context, rhs)) undefined:
1463 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1467 CYPoolFFI(pool, context, element->type, field, base, rhs);
1469 base += field->size;
1477 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1482 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner = NULL) {
1485 switch (type->primitive) {
1486 case sig::boolean_P:
1487 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1490 #define CYFromFFI_(primitive, native) \
1491 case sig::primitive ## _P: \
1492 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1495 CYFromFFI_(uchar, unsigned char)
1496 CYFromFFI_(char, char)
1497 CYFromFFI_(ushort, unsigned short)
1498 CYFromFFI_(short, short)
1499 CYFromFFI_(ulong, unsigned long)
1500 CYFromFFI_(long, long)
1501 CYFromFFI_(uint, unsigned int)
1502 CYFromFFI_(int, int)
1503 CYFromFFI_(ulonglong, unsigned long long)
1504 CYFromFFI_(longlong, long long)
1505 CYFromFFI_(float, float)
1506 CYFromFFI_(double, double)
1508 case sig::object_P: {
1509 if (id object = *reinterpret_cast<id *>(data)) {
1510 value = CYCastJSValue(context, object);
1516 case sig::typename_P:
1517 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1520 case sig::selector_P:
1521 if (SEL sel = *reinterpret_cast<SEL *>(data))
1522 value = CYMakeSelector(context, sel);
1526 case sig::pointer_P:
1527 if (void *pointer = *reinterpret_cast<void **>(data))
1528 value = CYMakePointer(context, pointer);
1533 if (char *utf8 = *reinterpret_cast<char **>(data))
1534 value = CYCastJSValue(context, utf8);
1539 value = CYMakeStruct(context, data, type, ffi, owner);
1543 value = CYJSUndefined(context);
1547 value = CYJSNull(context);
1551 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1558 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1559 Type_privateData *typical(internal->type_);
1562 const char *name(CYPoolCString(pool, property, &length));
1563 double number(CYCastDouble(name, length));
1565 size_t count(typical->type_.data.signature.count);
1567 if (std::isnan(number)) {
1568 if (property == NULL)
1571 sig::Element *elements(typical->type_.data.signature.elements);
1573 for (size_t local(0); local != count; ++local) {
1574 sig::Element *element(&elements[local]);
1575 if (element->name != NULL && strcmp(name, element->name) == 0) {
1583 index = static_cast<ssize_t>(number);
1584 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1589 base = reinterpret_cast<uint8_t *>(internal->value_);
1590 for (ssize_t local(0); local != index; ++local)
1591 base += typical->ffi_.elements[local]->size;
1596 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1598 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1599 Type_privateData *typical(internal->type_);
1604 if (!Index_(pool, internal, property, index, base))
1608 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, false, object);
1612 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1614 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1615 Type_privateData *typical(internal->type_);
1620 if (!Index_(pool, internal, property, index, base))
1624 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1629 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1630 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1631 Type_privateData *typical(internal->type_);
1633 size_t count(typical->type_.data.signature.count);
1634 sig::Element *elements(typical->type_.data.signature.elements);
1638 for (size_t index(0); index != count; ++index) {
1640 name = elements[index].name;
1643 sprintf(number, "%lu", index);
1647 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1651 JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1653 if (setups + count != signature->count - 1)
1654 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1656 size_t size(setups + count);
1658 memcpy(values, setup, sizeof(void *) * setups);
1660 for (size_t index(setups); index != size; ++index) {
1661 sig::Element *element(&signature->elements[index + 1]);
1662 ffi_type *ffi(cif->arg_types[index]);
1664 values[index] = new(pool) uint8_t[ffi->size];
1665 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1668 uint8_t value[cif->rtype->size];
1669 ffi_call(cif, function, value, values);
1671 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
1675 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1676 ffoData *data(reinterpret_cast<ffoData *>(arg));
1678 JSContextRef context(data->context_);
1680 size_t count(data->cif_.nargs);
1681 JSValueRef values[count];
1683 for (size_t index(0); index != count; ++index)
1684 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index], false);
1686 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1687 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1690 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1691 // XXX: in case of exceptions this will leak
1692 ffoData *data(new ffoData(type));
1694 ffi_closure *closure;
1695 _syscall(closure = (ffi_closure *) mmap(
1696 NULL, sizeof(ffi_closure),
1697 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1701 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1702 _assert(status == FFI_OK);
1704 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1706 data->value_ = closure;
1708 data->context_ = CYGetJSContext();
1709 data->function_ = function;
1711 return JSObjectMake(context, Functor_, data);
1714 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1717 NSString *name(CYCastNSString(pool, property));
1718 if (Class _class = NSClassFromString(name))
1719 return CYMakeInstance(context, _class, true);
1720 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1721 switch ([[entry objectAtIndex:0] intValue]) {
1723 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1725 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1727 // XXX: this is horrendously inefficient
1728 sig::Signature signature;
1729 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
1731 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1732 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol], false);
1738 bool stret(ffi_type *ffi_type) {
1739 return ffi_type->type == FFI_TYPE_STRUCT && (
1740 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1741 struct_forward_array[ffi_type->size] != 0
1746 int *_NSGetArgc(void);
1747 char ***_NSGetArgv(void);
1748 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1751 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1753 NSLog(@"%s", CYCastCString(context, arguments[0]));
1754 return CYJSUndefined(context);
1758 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1762 int argc(CYCastDouble(context, arguments[0]));
1763 char **argv(CYCastPointer<char **>(context, arguments[1]));
1764 NSString *principal(CYCastNSObject(pool, context, arguments[2]));
1765 NSString *delegate(CYCastNSObject(pool, context, arguments[3]));
1767 argc = *_NSGetArgc() - 1;
1768 argv = *_NSGetArgv() + 1;
1769 for (int i(0); i != argc; ++i)
1770 NSLog(@"argv[%i]=%s", i, argv[i]);
1773 return CYCastJSValue(context, UIApplicationMain(argc, argv, principal, delegate));
1777 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
1780 Class _class(object_getClass(self));
1781 if (Method method = class_getInstanceMethod(_class, _cmd))
1782 type = method_getTypeEncoding(method);
1785 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1787 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1788 type = CYPoolCString(pool, [method _typeString]);
1796 sig::Signature signature;
1797 sig::Parse(pool, &signature, type, &Structor_);
1800 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1802 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1803 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
1806 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1816 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1818 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
1819 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
1820 self = data->GetValue();
1821 uninitialized = data->IsUninitialized();
1825 self = CYCastNSObject(pool, context, arguments[0]);
1826 uninitialized = false;
1830 return CYJSNull(context);
1832 _cmd = CYCastSEL(context, arguments[1]);
1835 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
1838 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1839 JSValueRef setup[count + 2];
1842 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
1843 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1846 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1848 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1849 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1852 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1855 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1856 const char *name(CYCastCString(context, arguments[0]));
1857 return CYMakeSelector(context, sel_registerName(name));
1861 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1864 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1865 const char *type(CYCastCString(context, arguments[1]));
1866 JSValueRef exception(NULL);
1867 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1868 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1869 return CYMakeFunctor(context, function, type);
1870 } else if (exception != NULL) {
1873 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1874 return CYMakeFunctor(context, function, type);
1879 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1880 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
1881 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1884 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1888 static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1890 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1891 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1895 static JSValueRef Pointer_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1896 return Pointer_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1899 static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1901 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1903 sprintf(string, "%p", data->value_);
1904 return CYCastJSValue(context, string);
1908 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1910 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
1912 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
1917 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1919 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
1921 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
1922 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
1927 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1929 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
1931 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
1936 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1938 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1939 return CYCastJSValue(context, sel_getName(data->GetValue()));
1943 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1944 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
1947 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1949 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1950 const char *name(sel_getName(data->GetValue()));
1952 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
1957 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1960 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1962 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1963 Class _class(CYCastNSObject(pool, context, arguments[0]));
1964 bool instance(CYCastBool(context, arguments[1]));
1965 SEL sel(data->GetValue());
1966 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1967 return CYCastJSValue(context, method_getTypeEncoding(method));
1968 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1969 return CYCastJSValue(context, CYJSString(type));
1971 return CYJSNull(context);
1975 static JSStaticValue Pointer_staticValues[2] = {
1976 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1977 {NULL, NULL, NULL, 0}
1980 static JSStaticFunction Pointer_staticFunctions[4] = {
1981 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1982 {"toJSON", &Pointer_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1983 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1987 /*static JSStaticValue Selector_staticValues[2] = {
1988 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1989 {NULL, NULL, NULL, 0}
1992 static JSStaticFunction Instance_staticFunctions[4] = {
1993 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1994 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1995 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1999 static JSStaticFunction Selector_staticFunctions[5] = {
2000 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2001 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2002 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2003 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2007 CYDriver::CYDriver(const std::string &filename) :
2011 filename_(filename),
2017 CYDriver::~CYDriver() {
2021 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2022 CYDriver::Error error;
2023 error.location_ = location;
2024 error.message_ = message;
2025 driver.errors_.push_back(error);
2028 void CYSetArgs(int argc, const char *argv[]) {
2029 JSContextRef context(CYGetJSContext());
2030 JSValueRef args[argc];
2031 for (int i(0); i != argc; ++i)
2032 args[i] = CYCastJSValue(context, argv[i]);
2033 JSValueRef exception(NULL);
2034 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
2035 CYThrow(context, exception);
2036 CYSetProperty(context, System_, CYJSString("args"), array);
2039 JSObjectRef CYGetGlobalObject(JSContextRef context) {
2040 return JSContextGetGlobalObject(context);
2043 MSInitialize { _pooled
2046 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2048 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2050 JSClassDefinition definition;
2052 definition = kJSClassDefinitionEmpty;
2053 definition.className = "Pointer";
2054 definition.staticValues = Pointer_staticValues;
2055 definition.staticFunctions = Pointer_staticFunctions;
2056 definition.finalize = &CYData::Finalize;
2057 Pointer_ = JSClassCreate(&definition);
2059 definition = kJSClassDefinitionEmpty;
2060 definition.className = "Functor";
2061 definition.staticValues = Pointer_staticValues;
2062 definition.staticFunctions = Pointer_staticFunctions;
2063 definition.callAsFunction = &Functor_callAsFunction;
2064 definition.finalize = &CYData::Finalize;
2065 Functor_ = JSClassCreate(&definition);
2067 definition = kJSClassDefinitionEmpty;
2068 definition.className = "Struct";
2069 definition.getProperty = &Struct_getProperty;
2070 definition.setProperty = &Struct_setProperty;
2071 definition.getPropertyNames = &Struct_getPropertyNames;
2072 definition.finalize = &CYData::Finalize;
2073 Struct_ = JSClassCreate(&definition);
2075 definition = kJSClassDefinitionEmpty;
2076 definition.className = "Selector";
2077 definition.staticValues = Pointer_staticValues;
2078 //definition.staticValues = Selector_staticValues;
2079 definition.staticFunctions = Selector_staticFunctions;
2080 definition.callAsFunction = &Selector_callAsFunction;
2081 definition.finalize = &CYData::Finalize;
2082 Selector_ = JSClassCreate(&definition);
2084 definition = kJSClassDefinitionEmpty;
2085 definition.className = "Instance";
2086 definition.staticValues = Pointer_staticValues;
2087 definition.staticFunctions = Instance_staticFunctions;
2088 definition.getProperty = &Instance_getProperty;
2089 definition.setProperty = &Instance_setProperty;
2090 definition.deleteProperty = &Instance_deleteProperty;
2091 definition.callAsConstructor = &Instance_callAsConstructor;
2092 definition.finalize = &CYData::Finalize;
2093 Instance_ = JSClassCreate(&definition);
2095 definition = kJSClassDefinitionEmpty;
2096 definition.className = "Runtime";
2097 definition.getProperty = &Runtime_getProperty;
2098 Runtime_ = JSClassCreate(&definition);
2100 definition = kJSClassDefinitionEmpty;
2101 //definition.getProperty = &Global_getProperty;
2102 JSClassRef Global(JSClassCreate(&definition));
2104 JSGlobalContextRef context(JSGlobalContextCreate(Global));
2107 JSObjectRef global(CYGetGlobalObject(context));
2109 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
2110 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
2112 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
2113 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
2115 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
2116 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2118 System_ = JSObjectMake(context, NULL, NULL);
2119 CYSetProperty(context, global, CYJSString("system"), System_);
2120 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
2121 //CYSetProperty(context, System_, CYJSString("global"), global);
2123 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2125 length_ = JSStringCreateWithUTF8CString("length");
2126 message_ = JSStringCreateWithUTF8CString("message");
2127 name_ = JSStringCreateWithUTF8CString("name");
2128 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2129 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
2131 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2132 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));