1 /* Cyrker - 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 <CFNetwork/CFNetwork.h>
58 #include <WebKit/WebScriptObject.h>
60 #include <sys/types.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
66 #include <ext/stdio_filebuf.h>
73 #include "Cycript.tab.hh"
78 #define _assert(test) do { \
80 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
83 #define _trace() do { \
84 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
89 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
91 #define CYPoolCatch(value) \
92 @catch (NSException *error) { \
93 _saved = [error retain]; \
99 [_saved autorelease]; \
103 static JSGlobalContextRef Context_;
104 static JSObjectRef System_;
106 static JSClassRef Functor_;
107 static JSClassRef Instance_;
108 static JSClassRef Pointer_;
109 static JSClassRef Runtime_;
110 static JSClassRef Selector_;
111 static JSClassRef Struct_;
113 static JSObjectRef Array_;
114 static JSObjectRef Function_;
116 static JSStringRef name_;
117 static JSStringRef message_;
118 static JSStringRef length_;
120 static Class NSCFBoolean_;
122 static NSArray *Bridge_;
125 CFHTTPMessageRef message_;
135 void *operator new(size_t size) {
137 apr_pool_create(&pool, NULL);
138 void *data(apr_palloc(pool, size));
139 reinterpret_cast<CYData *>(data)->pool_ = pool;
143 static void Finalize(JSObjectRef object) {
144 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
146 apr_pool_destroy(data->pool_);
150 struct Pointer_privateData :
156 Pointer_privateData() {
159 Pointer_privateData(void *value) :
165 struct Functor_privateData :
168 sig::Signature signature_;
171 Functor_privateData(const char *type, void (*value)()) :
172 Pointer_privateData(reinterpret_cast<void *>(value))
174 sig::Parse(pool_, &signature_, type);
175 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
182 JSContextRef context_;
183 JSObjectRef function_;
185 ffoData(const char *type) :
186 Functor_privateData(type, NULL)
191 struct Selector_privateData : Pointer_privateData {
192 Selector_privateData(SEL value) :
193 Pointer_privateData(value)
197 SEL GetValue() const {
198 return reinterpret_cast<SEL>(value_);
202 struct Instance_privateData :
207 Instance_privateData(id value, bool transient) :
208 Pointer_privateData(value)
212 virtual ~Instance_privateData() {
214 [GetValue() release];
217 id GetValue() const {
218 return reinterpret_cast<id>(value_);
224 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
226 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
227 lhs.name = apr_pstrdup(pool, rhs.name);
228 if (rhs.type == NULL)
231 lhs.type = new(pool) Type;
232 Copy(pool, *lhs.type, *rhs.type);
234 lhs.offset = rhs.offset;
237 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
238 size_t count(rhs.count);
240 lhs.elements = new(pool) Element[count];
241 for (size_t index(0); index != count; ++index)
242 Copy(pool, lhs.elements[index], rhs.elements[index]);
245 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
246 lhs.primitive = rhs.primitive;
247 lhs.name = apr_pstrdup(pool, rhs.name);
248 lhs.flags = rhs.flags;
250 if (sig::IsAggregate(rhs.primitive))
251 Copy(pool, lhs.data.signature, rhs.data.signature);
253 if (rhs.data.data.type != NULL) {
254 lhs.data.data.type = new(pool) Type;
255 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
258 lhs.data.data.size = rhs.data.data.size;
262 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
264 lhs.alignment = rhs.alignment;
266 if (rhs.elements == NULL)
270 while (rhs.elements[count] != NULL)
273 lhs.elements = new(pool) ffi_type *[count + 1];
274 lhs.elements[count] = NULL;
276 for (size_t index(0); index != count; ++index) {
277 // XXX: if these are libffi native then you can just take them
278 ffi_type *ffi(new(pool) ffi_type);
279 lhs.elements[index] = ffi;
280 sig::Copy(pool, *ffi, *rhs.elements[index]);
287 struct Type_privateData {
292 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) {
293 sig::Copy(pool, type_, *type);
294 sig::Copy(pool, ffi_, *ffi);
296 /*sig::Element element;
301 sig::Signature signature;
302 signature.elements = &element;
306 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
309 /*if (type_->type != FFI_TYPE_STRUCT)
313 while (type_->elements[count] != NULL)
320 struct Struct_privateData :
324 Type_privateData *type_;
326 Struct_privateData() {
330 struct CStringMapLess :
331 std::binary_function<const char *, const char *, bool>
333 _finline bool operator ()(const char *lhs, const char *rhs) const {
334 return strcmp(lhs, rhs) < 0;
338 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
339 static TypeMap Types_;
341 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
342 Struct_privateData *internal(new Struct_privateData());
343 apr_pool_t *pool(internal->pool_);
344 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
345 internal->type_ = typical;
348 internal->owner_ = owner;
349 internal->value_ = data;
351 internal->owner_ = NULL;
353 size_t size(typical->ffi_.size);
354 void *copy(apr_palloc(internal->pool_, size));
355 memcpy(copy, data, size);
356 internal->value_ = copy;
359 return JSObjectMake(context, Struct_, internal);
362 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
364 object = [object retain];
365 Instance_privateData *data(new Instance_privateData(object, transient));
366 return JSObjectMake(context, Instance_, data);
369 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
371 return [value UTF8String];
373 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
374 char *string(new(pool) char[size]);
375 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
376 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
381 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
382 return JSValueMakeBoolean(context, value);
385 JSValueRef CYCastJSValue(JSContextRef context, double value) {
386 return JSValueMakeNumber(context, value);
389 #define CYCastJSValue_(Type_) \
390 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
391 return JSValueMakeNumber(context, static_cast<double>(value)); \
395 CYCastJSValue_(unsigned int)
396 CYCastJSValue_(long int)
397 CYCastJSValue_(long unsigned int)
398 CYCastJSValue_(long long int)
399 CYCastJSValue_(long long unsigned int)
401 JSValueRef CYJSUndefined(JSContextRef context) {
402 return JSValueMakeUndefined(context);
405 @interface NSMethodSignature (Cycript)
406 - (NSString *) _typeString;
409 @interface NSObject (Cycript)
410 - (bool) cy$isUndefined;
411 - (NSString *) cy$toJSON;
412 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
413 - (NSObject *) cy$getProperty:(NSString *)name;
414 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
415 - (bool) cy$deleteProperty:(NSString *)name;
418 @interface NSString (Cycript)
419 - (void *) cy$symbol;
422 @interface NSNumber (Cycript)
423 - (void *) cy$symbol;
426 @implementation NSObject (Cycript)
428 - (bool) cy$isUndefined {
432 - (NSString *) cy$toJSON {
433 return [self description];
436 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
437 return CYMakeInstance(context, self, transient);
440 - (NSObject *) cy$getProperty:(NSString *)name {
441 if (![name isEqualToString:@"prototype"])
442 NSLog(@"get:%@", name);
446 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
447 NSLog(@"set:%@", name);
451 - (bool) cy$deleteProperty:(NSString *)name {
452 NSLog(@"delete:%@", name);
458 @implementation WebUndefined (Cycript)
460 - (bool) cy$isUndefined {
464 - (NSString *) cy$toJSON {
468 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
469 return CYJSUndefined(context);
474 @implementation NSNull (Cycript)
476 - (NSString *) cy$toJSON {
482 @implementation NSArray (Cycript)
484 - (NSString *) cy$toJSON {
485 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
486 [json appendString:@"["];
489 for (id object in self) {
491 [json appendString:@","];
494 if (![object cy$isUndefined])
495 [json appendString:[object cy$toJSON]];
497 [json appendString:@","];
502 [json appendString:@"]"];
506 - (NSObject *) cy$getProperty:(NSString *)name {
507 int index([name intValue]);
508 if (index < 0 || index >= static_cast<int>([self count]))
509 return [super cy$getProperty:name];
511 return [self objectAtIndex:index];
516 @implementation NSMutableArray (Cycript)
518 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
519 int index([name intValue]);
520 if (index < 0 || index >= static_cast<int>([self count]))
521 return [super cy$setProperty:name to:value];
523 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
528 - (bool) cy$deleteProperty:(NSString *)name {
529 int index([name intValue]);
530 if (index < 0 || index >= static_cast<int>([self count]))
531 return [super cy$deleteProperty:name];
533 [self removeObjectAtIndex:index];
540 @implementation NSDictionary (Cycript)
542 - (NSString *) cy$toJSON {
543 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
544 [json appendString:@"({"];
547 for (id key in self) {
549 [json appendString:@","];
552 [json appendString:[key cy$toJSON]];
553 [json appendString:@":"];
554 NSObject *object([self objectForKey:key]);
555 [json appendString:[object cy$toJSON]];
558 [json appendString:@"})"];
562 - (NSObject *) cy$getProperty:(NSString *)name {
563 return [self objectForKey:name];
568 @implementation NSMutableDictionary (Cycript)
570 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
571 [self setObject:(value ?: [NSNull null]) forKey:name];
575 - (bool) cy$deleteProperty:(NSString *)name {
576 if ([self objectForKey:name] == nil)
579 [self removeObjectForKey:name];
586 @implementation NSNumber (Cycript)
588 - (NSString *) cy$toJSON {
589 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
592 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
593 return [self class] != NSCFBoolean_ ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
596 - (void *) cy$symbol {
597 return [self pointerValue];
602 @implementation NSString (Cycript)
604 - (NSString *) cy$toJSON {
605 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
607 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
608 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
609 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
610 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
611 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
613 CFStringInsert(json, 0, CFSTR("\""));
614 CFStringAppend(json, CFSTR("\""));
616 return [reinterpret_cast<const NSString *>(json) autorelease];
619 - (void *) cy$symbol {
621 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
626 @interface CYJSObject : NSDictionary {
628 JSContextRef context_;
631 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
633 - (NSUInteger) count;
634 - (id) objectForKey:(id)key;
635 - (NSEnumerator *) keyEnumerator;
636 - (void) setObject:(id)object forKey:(id)key;
637 - (void) removeObjectForKey:(id)key;
641 @interface CYJSArray : NSArray {
643 JSContextRef context_;
646 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
648 - (NSUInteger) count;
649 - (id) objectAtIndex:(NSUInteger)index;
653 CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
654 CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
656 JSGlobalContextRef CYGetJSContext() {
663 @catch (id error) { \
664 CYThrow(context, error, exception); \
668 void CYThrow(JSContextRef context, JSValueRef value);
670 apr_status_t CYPoolRelease_(void *data) {
671 id object(reinterpret_cast<id>(data));
676 id CYPoolRelease(apr_pool_t *pool, id object) {
678 return [object autorelease];
680 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
685 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
686 return (CFTypeRef) CYPoolRelease(pool, (id) object);
689 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
690 if (JSValueIsObjectOfClass(context, object, Instance_)) {
691 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
692 return data->GetValue();
695 JSValueRef exception(NULL);
696 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
697 CYThrow(context, exception);
698 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
699 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
702 JSStringRef CYCopyJSString(id value) {
703 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
706 JSStringRef CYCopyJSString(const char *value) {
707 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
710 JSStringRef CYCopyJSString(JSStringRef value) {
711 return value == NULL ? NULL : JSStringRetain(value);
714 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
715 if (JSValueIsNull(context, value))
717 JSValueRef exception(NULL);
718 JSStringRef string(JSValueToStringCopy(context, value, &exception));
719 CYThrow(context, exception);
728 JSStringRelease(string_);
732 CYJSString(const CYJSString &rhs) :
733 string_(CYCopyJSString(rhs.string_))
737 template <typename Arg0_>
738 CYJSString(Arg0_ arg0) :
739 string_(CYCopyJSString(arg0))
743 template <typename Arg0_, typename Arg1_>
744 CYJSString(Arg0_ arg0, Arg1_ arg1) :
745 string_(CYCopyJSString(arg0, arg1))
749 CYJSString &operator =(const CYJSString &rhs) {
751 string_ = CYCopyJSString(rhs.string_);
764 operator JSStringRef() const {
769 CFStringRef CYCopyCFString(JSStringRef value) {
770 return JSStringCopyCFString(kCFAllocatorDefault, value);
773 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
774 return CYCopyCFString(CYJSString(context, value));
777 double CYCastDouble(const char *value, size_t size) {
779 double number(strtod(value, &end));
780 if (end != value + size)
785 double CYCastDouble(const char *value) {
786 return CYCastDouble(value, strlen(value));
789 double CYCastDouble(JSContextRef context, JSValueRef value) {
790 JSValueRef exception(NULL);
791 double number(JSValueToNumber(context, value, &exception));
792 CYThrow(context, exception);
796 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
797 double number(CYCastDouble(context, value));
798 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
801 CFStringRef CYCopyCFString(const char *value) {
802 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
805 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
806 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
809 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
810 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
813 bool CYCastBool(JSContextRef context, JSValueRef value) {
814 return JSValueToBoolean(context, value);
817 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
821 switch (JSType type = JSValueGetType(context, value)) {
822 case kJSTypeUndefined:
823 object = [WebUndefined undefined];
832 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
837 object = CYCopyCFNumber(context, value);
842 object = CYCopyCFString(context, value);
847 // XXX: this might could be more efficient
848 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
853 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
860 return CYPoolRelease(pool, object);
862 return CFRetain(object);
865 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
866 return CYCFType(pool, context, value, true);
869 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
870 return CYCFType(pool, context, value, false);
873 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
875 size_t size(JSPropertyNameArrayGetCount(names));
876 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
877 for (size_t index(0); index != size; ++index)
878 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
882 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
883 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
886 void CYThrow(JSContextRef context, JSValueRef value) {
889 @throw CYCastNSObject(NULL, context, value);
892 JSValueRef CYJSNull(JSContextRef context) {
893 return JSValueMakeNull(context);
896 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
897 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
900 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
901 return CYCastJSValue(context, CYJSString(value));
904 JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
905 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
908 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
909 JSValueRef exception(NULL);
910 JSObjectRef object(JSValueToObject(context, value, &exception));
911 CYThrow(context, exception);
915 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
916 JSValueRef exception(NULL);
917 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
918 CYThrow(context, exception);
922 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
923 JSValueRef exception(NULL);
924 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
925 CYThrow(context, exception);
929 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
930 JSValueRef exception(NULL);
931 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
932 CYThrow(context, exception);
935 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
936 if (exception == NULL)
938 *exception = CYCastJSValue(context, error);
941 @implementation CYJSObject
943 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
944 if ((self = [super init]) != nil) {
950 - (NSUInteger) count {
951 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
952 size_t size(JSPropertyNameArrayGetCount(names));
953 JSPropertyNameArrayRelease(names);
957 - (id) objectForKey:(id)key {
958 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
961 - (NSEnumerator *) keyEnumerator {
962 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
963 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
964 JSPropertyNameArrayRelease(names);
968 - (void) setObject:(id)object forKey:(id)key {
969 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
972 - (void) removeObjectForKey:(id)key {
973 JSValueRef exception(NULL);
974 // XXX: this returns a bool... throw exception, or ignore?
975 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
976 CYThrow(context_, exception);
981 @implementation CYJSArray
983 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
984 if ((self = [super init]) != nil) {
990 - (NSUInteger) count {
991 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
994 - (id) objectAtIndex:(NSUInteger)index {
995 JSValueRef exception(NULL);
996 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
997 CYThrow(context_, exception);
998 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1003 CFStringRef CYCopyJSONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1006 id object(CYCastNSObject(NULL, context, value));
1007 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
1012 const char *CYPoolJSONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1013 if (NSString *json = (NSString *) CYCopyJSONString(context, value, exception)) {
1014 const char *string(CYPoolCString(pool, json));
1020 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
1022 case kCFSocketDataCallBack:
1023 CFDataRef data(reinterpret_cast<CFDataRef>(value));
1024 Client *client(reinterpret_cast<Client *>(info));
1026 if (client->message_ == NULL)
1027 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
1029 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
1030 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
1031 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
1032 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
1034 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
1035 CFRelease(client->message_);
1037 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
1040 JSStringRef script(JSStringCreateWithCFString(code));
1043 JSValueRef result(JSEvaluateScript(CYGetJSContext(), script, NULL, NULL, 0, NULL));
1044 JSStringRelease(script);
1046 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
1047 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
1049 CFStringRef json(CYCopyJSONString(CYGetJSContext(), result, NULL));
1050 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
1053 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
1054 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
1057 CFHTTPMessageSetBody(response, body);
1060 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
1061 CFRelease(response);
1063 CFSocketSendData(socket, NULL, serialized, 0);
1064 CFRelease(serialized);
1072 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
1074 case kCFSocketAcceptCallBack:
1075 Client *client(new Client());
1077 client->message_ = NULL;
1079 CFSocketContext context;
1080 context.version = 0;
1081 context.info = client;
1082 context.retain = NULL;
1083 context.release = NULL;
1084 context.copyDescription = NULL;
1086 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
1088 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
1093 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1096 NSString *self(CYCastNSObject(pool, context, object));
1097 NSString *name(CYCastNSString(pool, property));
1098 NSObject *data([self cy$getProperty:name]);
1099 return data == nil ? NULL : CYCastJSValue(context, data);
1103 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1106 NSString *self(CYCastNSObject(pool, context, object));
1107 NSString *name(CYCastNSString(pool, property));
1108 NSString *data(CYCastNSObject(pool, context, value));
1109 return [self cy$setProperty:name to:data];
1113 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1116 NSString *self(CYCastNSObject(pool, context, object));
1117 NSString *name(CYCastNSString(pool, property));
1118 return [self cy$deleteProperty:name];
1122 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1124 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
1125 return CYMakeInstance(context, [data->GetValue() alloc], true);
1129 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1130 Selector_privateData *data(new Selector_privateData(sel));
1131 return JSObjectMake(context, Selector_, data);
1134 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
1135 Pointer_privateData *data(new Pointer_privateData(pointer));
1136 return JSObjectMake(context, Pointer_, data);
1139 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1140 Functor_privateData *data(new Functor_privateData(type, function));
1141 return JSObjectMake(context, Functor_, data);
1144 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1146 const char *string([CYCastNSString(NULL, value) UTF8String]);
1148 *length = strlen(string);
1151 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1152 char *string(new(pool) char[size]);
1153 JSStringGetUTF8CString(value, string, size);
1154 // XXX: this is ironic
1156 *length = strlen(string);
1161 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1162 if (!JSValueIsNull(context, value))
1163 return CYPoolCString(pool, CYJSString(context, value), length);
1171 // XXX: this macro is unhygenic
1172 #define CYCastCString(context, value) ({ \
1174 if (value == NULL) \
1176 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1177 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1178 utf8 = reinterpret_cast<char *>(alloca(size)); \
1179 JSStringGetUTF8CString(string, utf8, size); \
1180 JSStringRelease(string); \
1186 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1187 if (JSValueIsNull(context, value))
1189 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
1190 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1191 return reinterpret_cast<SEL>(data->value_);
1193 return sel_registerName(CYCastCString(context, value));
1196 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1197 switch (JSValueGetType(context, value)) {
1200 /*case kJSTypeString:
1201 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1203 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1204 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1205 return data->value_;
1208 double number(CYCastDouble(context, value));
1209 if (std::isnan(number))
1210 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1211 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1215 template <typename Type_>
1216 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1217 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1220 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1221 switch (type->primitive) {
1222 case sig::boolean_P:
1223 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1226 #define CYPoolFFI_(primitive, native) \
1227 case sig::primitive ## _P: \
1228 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1231 CYPoolFFI_(uchar, unsigned char)
1232 CYPoolFFI_(char, char)
1233 CYPoolFFI_(ushort, unsigned short)
1234 CYPoolFFI_(short, short)
1235 CYPoolFFI_(ulong, unsigned long)
1236 CYPoolFFI_(long, long)
1237 CYPoolFFI_(uint, unsigned int)
1238 CYPoolFFI_(int, int)
1239 CYPoolFFI_(ulonglong, unsigned long long)
1240 CYPoolFFI_(longlong, long long)
1241 CYPoolFFI_(float, float)
1242 CYPoolFFI_(double, double)
1245 case sig::typename_P:
1246 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1249 case sig::selector_P:
1250 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1253 case sig::pointer_P:
1254 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1258 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1261 case sig::struct_P: {
1262 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1263 bool aggregate(JSValueIsObject(context, value));
1264 for (size_t index(0); index != type->data.signature.count; ++index) {
1265 ffi_type *element(ffi->elements[index]);
1266 JSValueRef rhs(aggregate ? CYGetProperty(context, (JSObjectRef) value, index) : value);
1267 CYPoolFFI(pool, context, type->data.signature.elements[index].type, element, base, rhs);
1269 base += element->size;
1277 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1282 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
1285 switch (type->primitive) {
1286 case sig::boolean_P:
1287 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1290 #define CYFromFFI_(primitive, native) \
1291 case sig::primitive ## _P: \
1292 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1295 CYFromFFI_(uchar, unsigned char)
1296 CYFromFFI_(char, char)
1297 CYFromFFI_(ushort, unsigned short)
1298 CYFromFFI_(short, short)
1299 CYFromFFI_(ulong, unsigned long)
1300 CYFromFFI_(long, long)
1301 CYFromFFI_(uint, unsigned int)
1302 CYFromFFI_(int, int)
1303 CYFromFFI_(ulonglong, unsigned long long)
1304 CYFromFFI_(longlong, long long)
1305 CYFromFFI_(float, float)
1306 CYFromFFI_(double, double)
1309 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
1312 case sig::typename_P:
1313 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1316 case sig::selector_P:
1317 if (SEL sel = *reinterpret_cast<SEL *>(data))
1318 value = CYMakeSelector(context, sel);
1322 case sig::pointer_P:
1323 if (void *pointer = *reinterpret_cast<void **>(data))
1324 value = CYMakePointer(context, pointer);
1329 if (char *utf8 = *reinterpret_cast<char **>(data))
1330 value = CYCastJSValue(context, utf8);
1335 value = CYMakeStruct(context, data, type, ffi, owner);
1339 value = CYJSUndefined(context);
1343 value = CYJSNull(context);
1347 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1354 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1355 Type_privateData *typical(internal->type_);
1358 const char *name(CYPoolCString(pool, property, &length));
1359 double number(CYCastDouble(name, length));
1361 if (std::isnan(number))
1365 index = static_cast<ssize_t>(number);
1366 if (index != number || index < 0 || static_cast<size_t>(index) >= typical->type_.data.signature.count)
1369 base = reinterpret_cast<uint8_t *>(internal->value_);
1370 for (ssize_t local(0); local != index; ++local)
1371 base += typical->ffi_.elements[local]->size;
1376 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1379 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1380 Type_privateData *typical(internal->type_);
1385 if (!Index_(pool, internal, property, index, base))
1388 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
1392 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1395 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1396 Type_privateData *typical(internal->type_);
1401 if (!Index_(pool, internal, property, index, base))
1404 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1409 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1411 if (count != signature->count - 1)
1412 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1415 void *values[count];
1417 for (unsigned index(0); index != count; ++index) {
1418 sig::Element *element(&signature->elements[index + 1]);
1419 ffi_type *ffi(cif->arg_types[index]);
1421 values[index] = new(pool) uint8_t[ffi->size];
1422 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index]);
1425 uint8_t value[cif->rtype->size];
1426 ffi_call(cif, function, value, values);
1428 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
1432 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1433 ffoData *data(reinterpret_cast<ffoData *>(arg));
1435 JSContextRef context(data->context_);
1437 size_t count(data->cif_.nargs);
1438 JSValueRef values[count];
1440 for (size_t index(0); index != count; ++index)
1441 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1443 JSValueRef exception(NULL);
1444 JSValueRef value(JSObjectCallAsFunction(context, data->function_, NULL, count, values, &exception));
1445 CYThrow(context, exception);
1447 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1450 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1451 // XXX: in case of exceptions this will leak
1452 ffoData *data(new ffoData(type));
1454 ffi_closure *closure;
1455 _syscall(closure = (ffi_closure *) mmap(
1456 NULL, sizeof(ffi_closure),
1457 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1461 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1462 _assert(status == FFI_OK);
1464 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1466 data->value_ = closure;
1468 data->context_ = CYGetJSContext();
1469 data->function_ = function;
1471 return JSObjectMake(context, Functor_, data);
1474 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1477 NSString *name(CYCastNSString(pool, property));
1478 if (Class _class = NSClassFromString(name))
1479 return CYMakeInstance(context, _class, true);
1480 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1481 switch ([[entry objectAtIndex:0] intValue]) {
1483 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1485 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1487 // XXX: this is horrendously inefficient
1488 sig::Signature signature;
1489 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]));
1491 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1492 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
1498 bool stret(ffi_type *ffi_type) {
1499 return ffi_type->type == FFI_TYPE_STRUCT && (
1500 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1501 struct_forward_array[ffi_type->size] != 0
1506 int *_NSGetArgc(void);
1507 char ***_NSGetArgv(void);
1508 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1511 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1513 NSLog(@"%s", CYCastCString(context, arguments[0]));
1514 return CYJSUndefined(context);
1518 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1521 NSString *name(CYCastNSObject(pool, context, arguments[0]));
1522 int argc(*_NSGetArgc());
1523 char **argv(*_NSGetArgv());
1524 for (int i(0); i != argc; ++i)
1525 NSLog(@"argv[%i]=%s", i, argv[i]);
1527 return CYCastJSValue(context, UIApplicationMain(argc, argv, name, name));
1531 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1538 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1540 id self(CYCastNSObject(pool, context, arguments[0]));
1542 return CYJSNull(context);
1544 SEL _cmd(CYCastSEL(context, arguments[1]));
1546 Class _class(object_getClass(self));
1547 if (Method method = class_getInstanceMethod(_class, _cmd))
1548 type = method_getTypeEncoding(method);
1551 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1553 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1554 type = CYPoolCString(pool, [method _typeString]);
1559 sig::Signature signature;
1560 sig::Parse(pool, &signature, type);
1563 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1565 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1566 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
1569 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1570 JSValueRef setup[count + 2];
1573 memmove(setup + 2, arguments, sizeof(JSValueRef) * count);
1574 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1577 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1578 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1579 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1582 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1585 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1586 const char *name(CYCastCString(context, arguments[0]));
1587 return CYMakeSelector(context, sel_registerName(name));
1591 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1594 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1595 const char *type(CYCastCString(context, arguments[1]));
1596 JSValueRef exception(NULL);
1597 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1598 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1599 return CYMakeFunctor(context, function, type);
1600 } else if (exception != NULL) {
1603 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1604 return CYMakeFunctor(context, function, type);
1609 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1610 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
1611 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1614 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1618 static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1620 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1621 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1625 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1627 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1629 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
1634 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1636 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1637 return CYCastJSValue(context, sel_getName(data->GetValue()));
1641 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1644 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1646 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1647 Class _class(CYCastNSObject(pool, context, arguments[0]));
1648 bool instance(CYCastBool(context, arguments[1]));
1649 SEL sel(data->GetValue());
1650 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1651 return CYCastJSValue(context, method_getTypeEncoding(method));
1652 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1653 return CYCastJSValue(context, CYJSString(type));
1655 return CYJSNull(context);
1659 static JSStaticValue Pointer_staticValues[2] = {
1660 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1661 {NULL, NULL, NULL, 0}
1664 static JSStaticFunction Pointer_staticFunctions[2] = {
1665 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1669 /*static JSStaticValue Selector_staticValues[2] = {
1670 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1671 {NULL, NULL, NULL, 0}
1674 static JSStaticFunction Instance_staticFunctions[2] = {
1675 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1679 static JSStaticFunction Selector_staticFunctions[3] = {
1680 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1681 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1685 CYDriver::CYDriver(const std::string &filename) :
1689 filename_(filename),
1695 CYDriver::~CYDriver() {
1699 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1700 CYDriver::Error error;
1701 error.location_ = location;
1702 error.message_ = message;
1703 driver.errors_.push_back(error);
1706 void CYSetArgs(int argc, const char *argv[]) {
1707 JSContextRef context(CYGetJSContext());
1708 JSValueRef args[argc];
1709 for (int i(0); i != argc; ++i)
1710 args[i] = CYCastJSValue(context, argv[i]);
1711 JSValueRef exception(NULL);
1712 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1713 CYThrow(context, exception);
1714 CYSetProperty(context, System_, CYJSString("args"), array);
1717 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1718 return JSContextGetGlobalObject(context);
1721 MSInitialize { _pooled
1724 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1726 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1728 pid_t pid(getpid());
1730 struct sockaddr_in address;
1731 address.sin_len = sizeof(address);
1732 address.sin_family = AF_INET;
1733 address.sin_addr.s_addr = INADDR_ANY;
1734 address.sin_port = htons(10000 + pid);
1736 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
1738 CFSocketSignature signature;
1739 signature.protocolFamily = AF_INET;
1740 signature.socketType = SOCK_STREAM;
1741 signature.protocol = IPPROTO_TCP;
1742 signature.address = data;
1744 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1745 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1747 JSClassDefinition definition;
1749 definition = kJSClassDefinitionEmpty;
1750 definition.className = "Pointer";
1751 definition.staticValues = Pointer_staticValues;
1752 definition.staticFunctions = Pointer_staticFunctions;
1753 definition.finalize = &CYData::Finalize;
1754 Pointer_ = JSClassCreate(&definition);
1756 definition = kJSClassDefinitionEmpty;
1757 definition.className = "Functor";
1758 definition.staticValues = Pointer_staticValues;
1759 definition.staticFunctions = Pointer_staticFunctions;
1760 definition.callAsFunction = &Functor_callAsFunction;
1761 definition.finalize = &CYData::Finalize;
1762 Functor_ = JSClassCreate(&definition);
1764 definition = kJSClassDefinitionEmpty;
1765 definition.className = "Struct";
1766 definition.getProperty = &Struct_getProperty;
1767 definition.setProperty = &Struct_setProperty;
1768 definition.finalize = &CYData::Finalize;
1769 Struct_ = JSClassCreate(&definition);
1771 definition = kJSClassDefinitionEmpty;
1772 definition.className = "Selector";
1773 definition.staticValues = Pointer_staticValues;
1774 //definition.staticValues = Selector_staticValues;
1775 definition.staticFunctions = Selector_staticFunctions;
1776 definition.callAsFunction = &Selector_callAsFunction;
1777 definition.finalize = &CYData::Finalize;
1778 Selector_ = JSClassCreate(&definition);
1780 definition = kJSClassDefinitionEmpty;
1781 definition.className = "Instance";
1782 definition.staticValues = Pointer_staticValues;
1783 definition.staticFunctions = Instance_staticFunctions;
1784 definition.getProperty = &Instance_getProperty;
1785 definition.setProperty = &Instance_setProperty;
1786 definition.deleteProperty = &Instance_deleteProperty;
1787 definition.callAsConstructor = &Instance_callAsConstructor;
1788 definition.finalize = &CYData::Finalize;
1789 Instance_ = JSClassCreate(&definition);
1791 definition = kJSClassDefinitionEmpty;
1792 definition.className = "Runtime";
1793 definition.getProperty = &Runtime_getProperty;
1794 Runtime_ = JSClassCreate(&definition);
1796 definition = kJSClassDefinitionEmpty;
1797 //definition.getProperty = &Global_getProperty;
1798 JSClassRef Global(JSClassCreate(&definition));
1800 JSGlobalContextRef context(JSGlobalContextCreate(Global));
1803 JSObjectRef global(CYGetGlobalObject(context));
1805 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
1806 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
1808 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
1809 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
1811 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
1812 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1814 System_ = JSObjectMake(context, NULL, NULL);
1815 CYSetProperty(context, global, CYJSString("system"), System_);
1816 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
1817 //CYSetProperty(context, System_, CYJSString("global"), global);
1819 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
1821 name_ = JSStringCreateWithUTF8CString("name");
1822 message_ = JSStringCreateWithUTF8CString("message");
1823 length_ = JSStringCreateWithUTF8CString("length");
1825 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1826 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));