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"
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <CoreFoundation/CFLogUtilities.h>
54 #include <WebKit/WebScriptObject.h>
59 #include <ext/stdio_filebuf.h>
67 #include "Cycript.tab.hh"
69 #include <apr-1/apr_thread_proc.h>
74 #define _assert(test) do { \
76 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
79 #define _trace() do { \
80 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
85 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
87 #define CYPoolCatch(value) \
88 @catch (NSException *error) { \
89 _saved = [error retain]; \
95 [_saved autorelease]; \
99 static JSGlobalContextRef Context_;
100 static JSObjectRef System_;
101 static JSObjectRef ObjectiveC_;
103 static JSClassRef Functor_;
104 static JSClassRef Instance_;
105 static JSClassRef Internal_;
106 static JSClassRef Message_;
107 static JSClassRef Pointer_;
108 static JSClassRef Prototype_;
109 static JSClassRef Runtime_;
110 static JSClassRef Selector_;
111 static JSClassRef Struct_;
112 static JSClassRef Type_;
114 static JSClassRef ObjectiveC_Classes_;
115 static JSClassRef ObjectiveC_Image_Classes_;
116 static JSClassRef ObjectiveC_Images_;
117 static JSClassRef ObjectiveC_Protocols_;
119 static JSObjectRef Array_;
120 static JSObjectRef Function_;
122 static JSStringRef Result_;
124 static JSStringRef length_;
125 static JSStringRef message_;
126 static JSStringRef name_;
127 static JSStringRef prototype_;
128 static JSStringRef toCYON_;
129 static JSStringRef toJSON_;
131 static Class NSCFBoolean_;
132 static Class NSCFType_;
133 static Class NSMessageBuilder_;
134 static Class NSZombie_;
135 static Class Object_;
137 static NSArray *Bridge_;
139 static void Finalize(JSObjectRef object) {
140 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
143 class Type_privateData;
153 CYValue(void *value) :
158 CYValue(const CYValue &rhs) :
163 virtual Type_privateData *GetType() const {
168 struct Selector_privateData :
171 Selector_privateData(SEL value) :
176 SEL GetValue() const {
177 return reinterpret_cast<SEL>(value_);
180 virtual Type_privateData *GetType() const;
188 Transient = (1 << 0),
189 Uninitialized = (1 << 1),
194 Instance(id value, Flags flags) :
200 virtual ~Instance() {
201 if ((flags_ & Transient) == 0)
202 // XXX: does this handle background threads correctly?
203 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
206 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
207 return JSObjectMake(context, Instance_, new Instance(object, flags));
210 id GetValue() const {
211 return reinterpret_cast<id>(value_);
214 bool IsUninitialized() const {
215 return (flags_ & Uninitialized) != 0;
218 virtual Type_privateData *GetType() const;
224 Prototype(Class value) :
229 static JSObjectRef Make(JSContextRef context, Class _class) {
230 return JSObjectMake(context, Prototype_, new Prototype(_class));
233 Class GetValue() const {
234 return reinterpret_cast<Class>(value_);
243 Internal(id value, JSObjectRef owner) :
249 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
250 return JSObjectMake(context, Internal_, new Internal(object, owner));
253 id GetValue() const {
254 return reinterpret_cast<id>(value_);
260 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
262 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
263 lhs.name = apr_pstrdup(pool, rhs.name);
264 if (rhs.type == NULL)
267 lhs.type = new(pool) Type;
268 Copy(pool, *lhs.type, *rhs.type);
270 lhs.offset = rhs.offset;
273 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
274 size_t count(rhs.count);
276 lhs.elements = new(pool) Element[count];
277 for (size_t index(0); index != count; ++index)
278 Copy(pool, lhs.elements[index], rhs.elements[index]);
281 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
282 lhs.primitive = rhs.primitive;
283 lhs.name = apr_pstrdup(pool, rhs.name);
284 lhs.flags = rhs.flags;
286 if (sig::IsAggregate(rhs.primitive))
287 Copy(pool, lhs.data.signature, rhs.data.signature);
289 if (rhs.data.data.type != NULL) {
290 lhs.data.data.type = new(pool) Type;
291 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
294 lhs.data.data.size = rhs.data.data.size;
298 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
300 lhs.alignment = rhs.alignment;
302 if (rhs.elements == NULL)
306 while (rhs.elements[count] != NULL)
309 lhs.elements = new(pool) ffi_type *[count + 1];
310 lhs.elements[count] = NULL;
312 for (size_t index(0); index != count; ++index) {
313 // XXX: if these are libffi native then you can just take them
314 ffi_type *ffi(new(pool) ffi_type);
315 lhs.elements[index] = ffi;
316 sig::Copy(pool, *ffi, *rhs.elements[index]);
323 struct CStringMapLess :
324 std::binary_function<const char *, const char *, bool>
326 _finline bool operator ()(const char *lhs, const char *rhs) const {
327 return strcmp(lhs, rhs) < 0;
331 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
336 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
337 switch ([[entry objectAtIndex:0] intValue]) {
339 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
343 sig::Signature signature;
344 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
345 type = signature.elements[0].type;
351 struct Type_privateData :
354 static Type_privateData *Object;
355 static Type_privateData *Selector;
360 void Set(sig::Type *type) {
361 type_ = new(pool_) sig::Type;
362 sig::Copy(pool_, *type_, *type);
365 Type_privateData(apr_pool_t *pool, const char *type) :
371 sig::Signature signature;
372 sig::Parse(pool_, &signature, type, &Structor_);
373 type_ = signature.elements[0].type;
376 Type_privateData(sig::Type *type) :
383 Type_privateData(sig::Type *type, ffi_type *ffi) {
384 ffi_ = new(pool_) ffi_type;
385 sig::Copy(pool_, *ffi_, *ffi);
391 ffi_ = new(pool_) ffi_type;
393 sig::Element element;
395 element.type = type_;
398 sig::Signature signature;
399 signature.elements = &element;
403 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
411 Type_privateData *Type_privateData::Object;
412 Type_privateData *Type_privateData::Selector;
414 Type_privateData *Instance::GetType() const {
415 return Type_privateData::Object;
418 Type_privateData *Selector_privateData::GetType() const {
419 return Type_privateData::Selector;
426 Type_privateData *type_;
428 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
431 type_(new(pool_) Type_privateData(type))
436 struct Struct_privateData :
440 Type_privateData *type_;
442 Struct_privateData(JSObjectRef owner) :
448 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
449 static TypeMap Types_;
451 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
452 Struct_privateData *internal(new Struct_privateData(owner));
453 apr_pool_t *pool(internal->pool_);
454 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
455 internal->type_ = typical;
458 internal->value_ = data;
460 size_t size(typical->GetFFI()->size);
461 void *copy(apr_palloc(internal->pool_, size));
462 memcpy(copy, data, size);
463 internal->value_ = copy;
466 return JSObjectMake(context, Struct_, internal);
469 struct Functor_privateData :
472 sig::Signature signature_;
476 Functor_privateData(const char *type, void (*value)()) :
477 CYValue(reinterpret_cast<void *>(value))
479 sig::Parse(pool_, &signature_, type, &Structor_);
480 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
483 void (*GetValue())() const {
484 return reinterpret_cast<void (*)()>(value_);
488 struct Closure_privateData :
491 JSContextRef context_;
492 JSObjectRef function_;
494 Closure_privateData(const char *type) :
495 Functor_privateData(type, NULL)
500 struct Message_privateData :
505 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
506 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
512 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
513 Instance::Flags flags;
516 flags = Instance::Transient;
518 flags = Instance::None;
519 object = [object retain];
522 return Instance::Make(context, object, flags);
525 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
527 return [value UTF8String];
529 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
530 char *string(new(pool) char[size]);
531 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
532 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
537 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
538 return JSValueMakeBoolean(context, value);
541 JSValueRef CYCastJSValue(JSContextRef context, double value) {
542 return JSValueMakeNumber(context, value);
545 #define CYCastJSValue_(Type_) \
546 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
547 return JSValueMakeNumber(context, static_cast<double>(value)); \
551 CYCastJSValue_(unsigned int)
552 CYCastJSValue_(long int)
553 CYCastJSValue_(long unsigned int)
554 CYCastJSValue_(long long int)
555 CYCastJSValue_(long long unsigned int)
557 JSValueRef CYJSUndefined(JSContextRef context) {
558 return JSValueMakeUndefined(context);
561 bool CYGetIndex(const char *value, ssize_t &index) {
562 if (value[0] != '0') {
564 index = strtol(value, &end, 10);
565 if (value + strlen(value) == end)
567 } else if (value[1] == '\0') {
575 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
576 return CYGetIndex(CYPoolCString(pool, value), index);
579 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
581 @interface NSMethodSignature (Cycript)
582 - (NSString *) _typeString;
585 @interface NSObject (Cycript)
587 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
588 - (JSType) cy$JSType;
590 - (NSObject *) cy$toJSON:(NSString *)key;
591 - (NSString *) cy$toCYON;
592 - (NSString *) cy$toKey;
594 - (bool) cy$hasProperty:(NSString *)name;
595 - (NSObject *) cy$getProperty:(NSString *)name;
596 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
597 - (bool) cy$deleteProperty:(NSString *)name;
602 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
605 @interface NSString (Cycript)
606 - (void *) cy$symbol;
609 struct PropertyAttributes {
614 const char *variable;
627 PropertyAttributes(objc_property_t property) :
639 name = property_getName(property);
640 const char *attributes(property_getAttributes(property));
642 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
644 case 'R': readonly = true; break;
645 case 'C': copy = true; break;
646 case '&': retain = true; break;
647 case 'N': nonatomic = true; break;
648 case 'G': getter_ = token + 1; break;
649 case 'S': setter_ = token + 1; break;
650 case 'V': variable = token + 1; break;
654 /*if (variable == NULL) {
655 variable = property_getName(property);
656 size_t size(strlen(variable));
657 char *name(new(pool_) char[size + 2]);
659 memcpy(name + 1, variable, size);
660 name[size + 1] = '\0';
665 const char *Getter() {
667 getter_ = apr_pstrdup(pool_, name);
671 const char *Setter() {
672 if (setter_ == NULL && !readonly) {
673 size_t length(strlen(name));
675 char *temp(new(pool_) char[length + 5]);
681 temp[3] = toupper(name[0]);
682 memcpy(temp + 4, name + 1, length - 1);
685 temp[length + 3] = ':';
686 temp[length + 4] = '\0';
695 @implementation NSProxy (Cycript)
697 - (NSObject *) cy$toJSON:(NSString *)key {
698 return [self description];
701 - (NSString *) cy$toCYON {
702 return [[self cy$toJSON:@""] cy$toCYON];
707 @implementation NSObject (Cycript)
709 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
710 return CYMakeInstance(context, self, false);
713 - (JSType) cy$JSType {
714 return kJSTypeObject;
717 - (NSObject *) cy$toJSON:(NSString *)key {
718 return [self description];
721 - (NSString *) cy$toCYON {
722 return [[self cy$toJSON:@""] cy$toCYON];
725 - (NSString *) cy$toKey {
726 return [self cy$toCYON];
729 - (bool) cy$hasProperty:(NSString *)name {
733 - (NSObject *) cy$getProperty:(NSString *)name {
737 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
741 - (bool) cy$deleteProperty:(NSString *)name {
747 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
748 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
751 @implementation WebUndefined (Cycript)
753 - (JSType) cy$JSType {
754 return kJSTypeUndefined;
757 - (NSObject *) cy$toJSON:(NSString *)key {
761 - (NSString *) cy$toCYON {
765 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
766 return CYJSUndefined(context);
771 @implementation NSNull (Cycript)
773 - (JSType) cy$JSType {
777 - (NSObject *) cy$toJSON:(NSString *)key {
781 - (NSString *) cy$toCYON {
787 @implementation NSArray (Cycript)
789 - (NSString *) cy$toCYON {
790 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
791 [json appendString:@"["];
794 for (id object in self) {
796 [json appendString:@","];
799 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
800 [json appendString:CYPoolNSCYON(NULL, object)];
802 [json appendString:@","];
807 [json appendString:@"]"];
811 - (bool) cy$hasProperty:(NSString *)name {
812 if ([name isEqualToString:@"length"])
816 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
817 return [super cy$hasProperty:name];
822 - (NSObject *) cy$getProperty:(NSString *)name {
823 if ([name isEqualToString:@"length"])
824 return [NSNumber numberWithUnsignedInteger:[self count]];
827 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
828 return [super cy$getProperty:name];
830 return [self objectAtIndex:index];
835 @implementation NSMutableArray (Cycript)
837 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
839 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
840 return [super cy$setProperty:name to:value];
842 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
847 - (bool) cy$deleteProperty:(NSString *)name {
849 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
850 return [super cy$deleteProperty:name];
852 [self removeObjectAtIndex:index];
859 @implementation NSDictionary (Cycript)
861 - (NSString *) cy$toCYON {
862 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
863 [json appendString:@"{"];
866 for (id key in self) {
868 [json appendString:@","];
871 [json appendString:[key cy$toKey]];
872 [json appendString:@":"];
873 NSObject *object([self objectForKey:key]);
874 [json appendString:CYPoolNSCYON(NULL, object)];
877 [json appendString:@"}"];
881 - (bool) cy$hasProperty:(NSString *)name {
882 return [self objectForKey:name] != nil;
885 - (NSObject *) cy$getProperty:(NSString *)name {
886 return [self objectForKey:name];
891 @implementation NSMutableDictionary (Cycript)
893 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
894 [self setObject:(value ?: [NSNull null]) forKey:name];
898 - (bool) cy$deleteProperty:(NSString *)name {
899 if ([self objectForKey:name] == nil)
902 [self removeObjectForKey:name];
909 @implementation NSNumber (Cycript)
911 - (JSType) cy$JSType {
912 // XXX: this just seems stupid
913 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
916 - (NSObject *) cy$toJSON:(NSString *)key {
920 - (NSString *) cy$toCYON {
921 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
924 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
925 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
930 @implementation NSString (Cycript)
932 - (JSType) cy$JSType {
933 return kJSTypeString;
936 - (NSObject *) cy$toJSON:(NSString *)key {
940 - (NSString *) cy$toCYON {
941 // XXX: this should use the better code from Output.cpp
942 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
944 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
945 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
946 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
947 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
948 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
950 CFStringInsert(json, 0, CFSTR("\""));
951 CFStringAppend(json, CFSTR("\""));
953 return [reinterpret_cast<const NSString *>(json) autorelease];
956 - (NSString *) cy$toKey {
957 const char *value([self UTF8String]);
958 size_t size(strlen(value));
963 if (DigitRange_[value[0]]) {
965 if (!CYGetIndex(NULL, self, index) || index < 0)
968 if (!WordStartRange_[value[0]])
970 for (size_t i(1); i != size; ++i)
971 if (!WordEndRange_[value[i]])
978 return [self cy$toCYON];
981 - (void *) cy$symbol {
983 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
988 @interface CYJSObject : NSDictionary {
990 JSContextRef context_;
993 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
995 - (NSString *) cy$toJSON:(NSString *)key;
997 - (NSUInteger) count;
998 - (id) objectForKey:(id)key;
999 - (NSEnumerator *) keyEnumerator;
1000 - (void) setObject:(id)object forKey:(id)key;
1001 - (void) removeObjectForKey:(id)key;
1005 @interface CYJSArray : NSArray {
1006 JSObjectRef object_;
1007 JSContextRef context_;
1010 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1012 - (NSUInteger) count;
1013 - (id) objectAtIndex:(NSUInteger)index;
1017 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1018 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1019 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1024 @catch (id error) { \
1025 CYThrow(context, error, exception); \
1029 void CYThrow(JSContextRef context, JSValueRef value);
1031 apr_status_t CYPoolRelease_(void *data) {
1032 id object(reinterpret_cast<id>(data));
1037 id CYPoolRelease(apr_pool_t *pool, id object) {
1040 else if (pool == NULL)
1041 return [object autorelease];
1043 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1048 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1049 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1052 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1053 JSValueRef exception(NULL);
1054 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1055 CYThrow(context, exception);
1056 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1057 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1060 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1061 if (!JSValueIsObjectOfClass(context, object, Instance_))
1062 return CYCastNSObject_(pool, context, object);
1064 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1065 return data->GetValue();
1069 JSStringRef CYCopyJSString(id value) {
1070 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
1073 JSStringRef CYCopyJSString(const char *value) {
1074 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
1077 JSStringRef CYCopyJSString(JSStringRef value) {
1078 return value == NULL ? NULL : JSStringRetain(value);
1081 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
1082 if (JSValueIsNull(context, value))
1084 JSValueRef exception(NULL);
1085 JSStringRef string(JSValueToStringCopy(context, value, &exception));
1086 CYThrow(context, exception);
1092 JSStringRef string_;
1095 if (string_ != NULL)
1096 JSStringRelease(string_);
1100 CYJSString(const CYJSString &rhs) :
1101 string_(CYCopyJSString(rhs.string_))
1105 template <typename Arg0_>
1106 CYJSString(Arg0_ arg0) :
1107 string_(CYCopyJSString(arg0))
1111 template <typename Arg0_, typename Arg1_>
1112 CYJSString(Arg0_ arg0, Arg1_ arg1) :
1113 string_(CYCopyJSString(arg0, arg1))
1117 CYJSString &operator =(const CYJSString &rhs) {
1119 string_ = CYCopyJSString(rhs.string_);
1132 operator JSStringRef() const {
1137 CFStringRef CYCopyCFString(JSStringRef value) {
1138 return JSStringCopyCFString(kCFAllocatorDefault, value);
1141 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1142 return CYCopyCFString(CYJSString(context, value));
1145 double CYCastDouble(const char *value, size_t size) {
1147 double number(strtod(value, &end));
1148 if (end != value + size)
1153 double CYCastDouble(const char *value) {
1154 return CYCastDouble(value, strlen(value));
1157 double CYCastDouble(JSContextRef context, JSValueRef value) {
1158 JSValueRef exception(NULL);
1159 double number(JSValueToNumber(context, value, &exception));
1160 CYThrow(context, exception);
1164 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1165 double number(CYCastDouble(context, value));
1166 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1169 CFStringRef CYCopyCFString(const char *value) {
1170 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1173 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1174 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1177 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1178 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1181 bool CYCastBool(JSContextRef context, JSValueRef value) {
1182 return JSValueToBoolean(context, value);
1185 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1189 switch (JSType type = JSValueGetType(context, value)) {
1190 case kJSTypeUndefined:
1191 object = [WebUndefined undefined];
1199 case kJSTypeBoolean:
1200 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1205 object = CYCopyCFNumber(context, value);
1210 object = CYCopyCFString(context, value);
1215 // XXX: this might could be more efficient
1216 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1221 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1228 return CYPoolRelease(pool, object);
1230 return CFRetain(object);
1233 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1234 return CYCFType(pool, context, value, true);
1237 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1238 return CYCFType(pool, context, value, false);
1241 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1243 size_t size(JSPropertyNameArrayGetCount(names));
1244 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1245 for (size_t index(0); index != size; ++index)
1246 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1250 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1251 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1254 void CYThrow(JSContextRef context, JSValueRef value) {
1257 @throw CYCastNSObject(NULL, context, value);
1260 JSValueRef CYJSNull(JSContextRef context) {
1261 return JSValueMakeNull(context);
1264 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1265 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1268 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1269 return CYCastJSValue(context, CYJSString(value));
1272 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1274 return CYJSNull(context);
1275 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1276 return [value cy$JSValueInContext:context];
1278 return CYMakeInstance(context, value, false);
1281 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1282 JSValueRef exception(NULL);
1283 JSObjectRef object(JSValueToObject(context, value, &exception));
1284 CYThrow(context, exception);
1288 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1289 JSValueRef exception(NULL);
1290 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1291 CYThrow(context, exception);
1295 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1296 JSValueRef exception(NULL);
1297 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1298 CYThrow(context, exception);
1302 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1303 JSValueRef exception(NULL);
1304 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1305 CYThrow(context, exception);
1308 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1309 if (exception == NULL)
1311 *exception = CYCastJSValue(context, error);
1314 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1315 JSValueRef exception(NULL);
1316 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1317 CYThrow(context, exception);
1321 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1322 // XXX: this isn't actually correct
1323 return value != NULL && JSValueIsObject(context, value);
1326 @implementation CYJSObject
1328 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1329 if ((self = [super init]) != nil) {
1335 - (NSObject *) cy$toJSON:(NSString *)key {
1336 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1337 if (!CYIsCallable(context_, toJSON))
1338 return [super cy$toJSON:key];
1340 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1341 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1342 // XXX: do I really want an NSNull here?!
1343 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1347 - (NSString *) cy$toCYON {
1348 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1349 if (!CYIsCallable(context_, toCYON))
1350 return [super cy$toCYON];
1352 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1353 return CYCastNSString(NULL, CYJSString(context_, value));
1357 - (NSUInteger) count {
1358 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1359 size_t size(JSPropertyNameArrayGetCount(names));
1360 JSPropertyNameArrayRelease(names);
1364 - (id) objectForKey:(id)key {
1365 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1368 - (NSEnumerator *) keyEnumerator {
1369 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1370 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1371 JSPropertyNameArrayRelease(names);
1375 - (void) setObject:(id)object forKey:(id)key {
1376 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1379 - (void) removeObjectForKey:(id)key {
1380 JSValueRef exception(NULL);
1381 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1382 CYThrow(context_, exception);
1387 @implementation CYJSArray
1389 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1390 if ((self = [super init]) != nil) {
1396 - (NSUInteger) count {
1397 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1400 - (id) objectAtIndex:(NSUInteger)index {
1401 JSValueRef exception(NULL);
1402 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1403 CYThrow(context_, exception);
1404 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1409 NSString *CYCopyNSCYON(id value) {
1415 Class _class(object_getClass(value));
1416 SEL sel(@selector(cy$toCYON));
1418 if (Method toCYON = class_getInstanceMethod(_class, sel))
1419 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1420 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1421 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1422 string = [value cy$toCYON];
1425 if (value == NSZombie_)
1426 string = @"_NSZombie_";
1427 else if (_class == NSZombie_)
1428 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1429 // XXX: frowny /in/ the pants
1430 else if (value == NSMessageBuilder_ || value == Object_)
1433 string = [NSString stringWithFormat:@"%@", value];
1436 // XXX: frowny pants
1438 string = @"undefined";
1441 return [string retain];
1444 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1445 if (JSValueIsNull(context, value))
1446 return [@"null" retain];
1450 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1455 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1456 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1459 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1460 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1461 const char *string(CYPoolCString(pool, json));
1467 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1471 JSObjectRef object_;
1479 // XXX: delete object_? ;(
1482 static CYInternal *Get(id self) {
1483 CYInternal *internal(NULL);
1484 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1485 // XXX: do something epic? ;P
1491 static CYInternal *Set(id self) {
1492 CYInternal *internal(NULL);
1493 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1494 if (internal == NULL) {
1495 internal = new CYInternal();
1496 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1499 // XXX: do something epic? ;P
1505 bool HasProperty(JSContextRef context, JSStringRef name) {
1506 if (object_ == NULL)
1508 return JSObjectHasProperty(context, object_, name);
1511 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1512 if (object_ == NULL)
1514 return CYGetProperty(context, object_, name);
1517 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1518 if (object_ == NULL)
1519 object_ = JSObjectMake(context, NULL, NULL);
1520 CYSetProperty(context, object_, name, value);
1524 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1525 Selector_privateData *data(new Selector_privateData(sel));
1526 return JSObjectMake(context, Selector_, data);
1529 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1530 Pointer *data(new Pointer(pointer, type, owner));
1531 return JSObjectMake(context, Pointer_, data);
1534 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1535 Functor_privateData *data(new Functor_privateData(type, function));
1536 return JSObjectMake(context, Functor_, data);
1539 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1541 const char *string([CYCastNSString(NULL, value) UTF8String]);
1544 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1545 char *string(new(pool) char[size]);
1546 JSStringGetUTF8CString(value, string, size);
1551 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1552 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1555 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1556 return CYGetIndex(CYPoolCString(pool, value), index);
1559 // XXX: this macro is unhygenic
1560 #define CYCastCString(context, value) ({ \
1562 if (value == NULL) \
1564 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1565 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1566 utf8 = reinterpret_cast<char *>(alloca(size)); \
1567 JSStringGetUTF8CString(string, utf8, size); \
1568 JSStringRelease(string); \
1574 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1575 switch (JSValueGetType(context, value)) {
1578 /*case kJSTypeString:
1579 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1581 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1582 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1583 return data->value_;
1586 double number(CYCastDouble(context, value));
1587 if (std::isnan(number))
1588 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1589 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1593 template <typename Type_>
1594 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1595 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1598 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1599 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1600 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1601 return reinterpret_cast<SEL>(data->value_);
1603 return CYCastPointer<SEL>(context, value);
1606 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1607 switch (type->primitive) {
1608 case sig::boolean_P:
1609 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1612 #define CYPoolFFI_(primitive, native) \
1613 case sig::primitive ## _P: \
1614 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1617 CYPoolFFI_(uchar, unsigned char)
1618 CYPoolFFI_(char, char)
1619 CYPoolFFI_(ushort, unsigned short)
1620 CYPoolFFI_(short, short)
1621 CYPoolFFI_(ulong, unsigned long)
1622 CYPoolFFI_(long, long)
1623 CYPoolFFI_(uint, unsigned int)
1624 CYPoolFFI_(int, int)
1625 CYPoolFFI_(ulonglong, unsigned long long)
1626 CYPoolFFI_(longlong, long long)
1627 CYPoolFFI_(float, float)
1628 CYPoolFFI_(double, double)
1631 case sig::typename_P:
1632 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1635 case sig::selector_P:
1636 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1639 case sig::pointer_P:
1640 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1644 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1647 case sig::struct_P: {
1648 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1649 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1650 for (size_t index(0); index != type->data.signature.count; ++index) {
1651 sig::Element *element(&type->data.signature.elements[index]);
1652 ffi_type *field(ffi->elements[index]);
1655 if (aggregate == NULL)
1658 rhs = CYGetProperty(context, aggregate, index);
1659 if (JSValueIsUndefined(context, rhs)) {
1660 if (element->name != NULL)
1661 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1664 if (JSValueIsUndefined(context, rhs)) undefined:
1665 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1669 CYPoolFFI(pool, context, element->type, field, base, rhs);
1671 base += field->size;
1679 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1684 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1687 switch (type->primitive) {
1688 case sig::boolean_P:
1689 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1692 #define CYFromFFI_(primitive, native) \
1693 case sig::primitive ## _P: \
1694 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1697 CYFromFFI_(uchar, unsigned char)
1698 CYFromFFI_(char, char)
1699 CYFromFFI_(ushort, unsigned short)
1700 CYFromFFI_(short, short)
1701 CYFromFFI_(ulong, unsigned long)
1702 CYFromFFI_(long, long)
1703 CYFromFFI_(uint, unsigned int)
1704 CYFromFFI_(int, int)
1705 CYFromFFI_(ulonglong, unsigned long long)
1706 CYFromFFI_(longlong, long long)
1707 CYFromFFI_(float, float)
1708 CYFromFFI_(double, double)
1710 case sig::object_P: {
1711 if (id object = *reinterpret_cast<id *>(data)) {
1712 value = CYCastJSValue(context, object);
1718 case sig::typename_P:
1719 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1722 case sig::selector_P:
1723 if (SEL sel = *reinterpret_cast<SEL *>(data))
1724 value = CYMakeSelector(context, sel);
1728 case sig::pointer_P:
1729 if (void *pointer = *reinterpret_cast<void **>(data))
1730 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1735 if (char *utf8 = *reinterpret_cast<char **>(data))
1736 value = CYCastJSValue(context, utf8);
1741 value = CYMakeStruct(context, data, type, ffi, owner);
1745 value = CYJSUndefined(context);
1749 value = CYJSNull(context);
1753 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1760 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1761 if (Method method = class_getInstanceMethod(_class, selector)) {
1765 method_getReturnType(method, type, sizeof(type));
1770 // XXX: possibly use a more "awesome" check?
1774 const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
1776 return method_getTypeEncoding(method);
1777 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1778 return CYPoolCString(pool, type);
1783 void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1784 Closure_privateData *data(reinterpret_cast<Closure_privateData *>(arg));
1786 JSContextRef context(data->context_);
1788 size_t count(data->cif_.nargs);
1789 JSValueRef values[count];
1791 for (size_t index(0); index != count; ++index)
1792 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1794 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1795 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1798 void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1799 Closure_privateData *data(reinterpret_cast<Closure_privateData *>(arg));
1801 JSContextRef context(data->context_);
1803 size_t count(data->cif_.nargs);
1804 JSValueRef values[count];
1806 for (size_t index(0); index != count; ++index)
1807 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1809 JSObjectRef _this(CYCastJSObject(context, values[0]));
1811 JSValueRef value(CYCallAsFunction(context, data->function_, _this, count - 2, values + 2));
1812 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1815 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
1816 // XXX: in case of exceptions this will leak
1817 // XXX: in point of fact, this may /need/ to leak :(
1818 Closure_privateData *internal(new Closure_privateData(type));
1820 ffi_closure *closure((ffi_closure *) _syscall(mmap(
1821 NULL, sizeof(ffi_closure),
1822 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1826 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
1827 _assert(status == FFI_OK);
1829 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1831 internal->value_ = closure;
1833 internal->context_ = CYGetJSContext();
1834 internal->function_ = function;
1839 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1840 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
1841 return JSObjectMake(context, Functor_, internal);
1844 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
1845 JSValueRef exception(NULL);
1846 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
1847 CYThrow(context, exception);
1850 JSObjectRef function(CYCastJSObject(context, value));
1851 return CYMakeFunctor(context, function, type);
1853 void (*function)()(CYCastPointer<void (*)()>(context, value));
1854 return CYMakeFunctor(context, function, type);
1858 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1859 Message_privateData *internal(new Message_privateData(sel, type, imp));
1860 return JSObjectMake(context, Message_, internal);
1863 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1864 JSObjectRef function(CYCastJSObject(context, value));
1865 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1866 return reinterpret_cast<IMP>(internal->GetValue());
1869 static bool Prototype_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1870 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1871 Class _class(internal->GetValue());
1874 const char *name(CYPoolCString(pool, property));
1876 if (SEL sel = sel_getUid(name))
1877 if (class_getInstanceMethod(_class, sel) != NULL)
1883 static JSValueRef Prototype_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1884 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1885 Class _class(internal->GetValue());
1888 const char *name(CYPoolCString(pool, property));
1890 if (SEL sel = sel_getUid(name))
1891 if (Method method = class_getInstanceMethod(_class, sel))
1892 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1897 static bool Prototype_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1898 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1899 Class _class(internal->GetValue());
1902 const char *name(CYPoolCString(pool, property));
1904 SEL sel(sel_registerName(name));
1906 Method method(class_getInstanceMethod(_class, sel));
1911 if (JSValueIsObjectOfClass(context, value, Message_)) {
1912 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1913 type = sig::Unparse(pool, &message->signature_);
1914 imp = reinterpret_cast<IMP>(message->GetValue());
1916 type = CYPoolTypeEncoding(pool, _class, sel, method);
1917 imp = CYMakeMessage(context, value, type);
1921 method_setImplementation(method, imp);
1923 class_replaceMethod(_class, sel, imp, type);
1929 static bool Prototype_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1930 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1931 Class _class(internal->GetValue());
1934 const char *name(CYPoolCString(pool, property));
1936 if (SEL sel = sel_getUid(name))
1937 if (Method method = class_getInstanceMethod(_class, sel)) {
1938 objc_method_list list = {NULL, 1, {method}};
1939 class_removeMethods(_class, &list);
1947 static void Prototype_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1948 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1949 Class _class(internal->GetValue());
1952 Method *data(class_copyMethodList(_class, &size));
1953 for (size_t i(0); i != size; ++i)
1954 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1958 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1959 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1960 id self(internal->GetValue());
1962 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1966 NSString *name(CYCastNSString(pool, property));
1968 if (CYInternal *internal = CYInternal::Get(self))
1969 if (internal->HasProperty(context, property))
1973 if ([self cy$hasProperty:name])
1975 } CYPoolCatch(false)
1977 const char *string(CYPoolCString(pool, name));
1978 Class _class(object_getClass(self));
1980 if (class_getProperty(_class, string) != NULL)
1983 if (SEL sel = sel_getUid(string))
1984 if (CYImplements(self, _class, sel, true))
1990 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1991 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1992 id self(internal->GetValue());
1994 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1995 return Internal::Make(context, self, object);
1999 NSString *name(CYCastNSString(pool, property));
2001 if (CYInternal *internal = CYInternal::Get(self))
2002 if (JSValueRef value = internal->GetProperty(context, property))
2006 if (NSObject *data = [self cy$getProperty:name])
2007 return CYCastJSValue(context, data);
2010 const char *string(CYPoolCString(pool, name));
2011 Class _class(object_getClass(self));
2013 if (objc_property_t property = class_getProperty(_class, string)) {
2014 PropertyAttributes attributes(property);
2015 SEL sel(sel_registerName(attributes.Getter()));
2016 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2019 if (SEL sel = sel_getUid(string))
2020 if (CYImplements(self, _class, sel, true))
2021 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2027 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2028 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2029 id self(internal->GetValue());
2034 NSString *name(CYCastNSString(pool, property));
2035 NSString *data(CYCastNSObject(pool, context, value));
2038 if ([self cy$setProperty:name to:data])
2042 const char *string(CYPoolCString(pool, name));
2043 Class _class(object_getClass(self));
2045 if (objc_property_t property = class_getProperty(_class, string)) {
2046 PropertyAttributes attributes(property);
2047 if (const char *setter = attributes.Setter()) {
2048 SEL sel(sel_registerName(setter));
2049 JSValueRef arguments[1] = {value};
2050 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2055 size_t length(strlen(string));
2057 char set[length + 5];
2063 if (string[0] != '\0') {
2064 set[3] = toupper(string[0]);
2065 memcpy(set + 4, string + 1, length - 1);
2068 set[length + 3] = ':';
2069 set[length + 4] = '\0';
2071 if (SEL sel = sel_getUid(set))
2072 if (CYImplements(self, _class, sel, false)) {
2073 JSValueRef arguments[1] = {value};
2074 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2077 if (CYInternal *internal = CYInternal::Set(self)) {
2078 internal->SetProperty(context, property, value);
2086 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2087 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2088 id self(internal->GetValue());
2092 NSString *name(CYCastNSString(NULL, property));
2093 return [self cy$deleteProperty:name];
2098 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2099 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2100 id self(internal->GetValue());
2103 Class _class(object_getClass(self));
2107 objc_property_t *data(class_copyPropertyList(_class, &size));
2108 for (size_t i(0); i != size; ++i)
2109 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2114 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2116 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2117 JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
2122 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2123 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2126 id self(internal->GetValue());
2127 const char *name(CYPoolCString(pool, property));
2129 if (object_getInstanceVariable(self, name, NULL) != NULL)
2135 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2136 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2140 id self(internal->GetValue());
2141 const char *name(CYPoolCString(pool, property));
2143 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2144 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2145 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2152 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2153 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2157 id self(internal->GetValue());
2158 const char *name(CYPoolCString(pool, property));
2160 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2161 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2162 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2170 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2171 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2174 id self(internal->GetValue());
2175 Class _class(object_getClass(self));
2177 for (Class super(_class); super != NULL; super = class_getSuperclass(super)) {
2179 Ivar *data(class_copyIvarList(super, &size));
2180 for (size_t i(0); i != size; ++i)
2181 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2186 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2187 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2188 return internal->owner_;
2191 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2192 Type_privateData *typical(internal->type_);
2193 sig::Type *type(typical->type_);
2197 const char *name(CYPoolCString(pool, property));
2198 size_t length(strlen(name));
2199 double number(CYCastDouble(name, length));
2201 size_t count(type->data.signature.count);
2203 if (std::isnan(number)) {
2204 if (property == NULL)
2207 sig::Element *elements(type->data.signature.elements);
2209 for (size_t local(0); local != count; ++local) {
2210 sig::Element *element(&elements[local]);
2211 if (element->name != NULL && strcmp(name, element->name) == 0) {
2219 index = static_cast<ssize_t>(number);
2220 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2225 ffi_type **elements(typical->GetFFI()->elements);
2227 base = reinterpret_cast<uint8_t *>(internal->value_);
2228 for (ssize_t local(0); local != index; ++local)
2229 base += elements[local]->size;
2234 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2235 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2236 Type_privateData *typical(internal->type_);
2238 ffi_type *ffi(typical->GetFFI());
2240 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2241 base += ffi->size * index;
2243 JSObjectRef owner(internal->owner_ ?: object);
2246 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2250 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2252 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2253 Type_privateData *typical(internal->type_);
2255 if (typical->type_ == NULL)
2259 if (!CYGetIndex(pool, property, index))
2262 return Pointer_getIndex(context, object, index, exception);
2265 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2266 return Pointer_getIndex(context, object, 0, exception);
2269 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2270 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2271 Type_privateData *typical(internal->type_);
2273 ffi_type *ffi(typical->GetFFI());
2275 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2276 base += ffi->size * index;
2279 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2284 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2286 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2287 Type_privateData *typical(internal->type_);
2289 if (typical->type_ == NULL)
2293 if (!CYGetIndex(pool, property, index))
2296 return Pointer_setIndex(context, object, 0, value, exception);
2299 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2300 return Pointer_setIndex(context, object, 0, value, exception);
2303 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2304 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2305 Type_privateData *typical(internal->type_);
2306 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2309 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2311 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2312 Type_privateData *typical(internal->type_);
2317 if (!Index_(pool, internal, property, index, base))
2320 JSObjectRef owner(internal->owner_ ?: object);
2323 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2327 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2329 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2330 Type_privateData *typical(internal->type_);
2335 if (!Index_(pool, internal, property, index, base))
2339 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2344 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2345 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2346 Type_privateData *typical(internal->type_);
2347 sig::Type *type(typical->type_);
2352 size_t count(type->data.signature.count);
2353 sig::Element *elements(type->data.signature.elements);
2357 for (size_t index(0); index != count; ++index) {
2359 name = elements[index].name;
2362 sprintf(number, "%lu", index);
2366 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2370 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)()) {
2372 if (setups + count != signature->count - 1)
2373 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2375 size_t size(setups + count);
2377 memcpy(values, setup, sizeof(void *) * setups);
2379 for (size_t index(setups); index != size; ++index) {
2380 sig::Element *element(&signature->elements[index + 1]);
2381 ffi_type *ffi(cif->arg_types[index]);
2383 values[index] = new(pool) uint8_t[ffi->size];
2384 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2387 uint8_t value[cif->rtype->size];
2388 ffi_call(cif, function, value, values);
2390 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2394 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2397 NSString *name(CYCastNSString(pool, property));
2398 if (Class _class = NSClassFromString(name))
2399 return CYMakeInstance(context, _class, true);
2404 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2405 size_t size(objc_getClassList(NULL, 0));
2406 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2409 size_t writ(objc_getClassList(data, size));
2412 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2418 for (size_t i(0); i != writ; ++i)
2419 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2425 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2426 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2430 const char *name(CYPoolCString(pool, property));
2432 const char **data(objc_copyClassNamesForImage(internal, &size));
2434 for (size_t i(0); i != size; ++i)
2435 if (strcmp(name, data[i]) == 0) {
2436 if (Class _class = objc_getClass(name)) {
2437 value = CYMakeInstance(context, _class, true);
2449 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2450 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2452 const char **data(objc_copyClassNamesForImage(internal, &size));
2453 for (size_t i(0); i != size; ++i)
2454 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2458 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2461 const char *name(CYPoolCString(pool, property));
2463 const char **data(objc_copyImageNames(&size));
2464 for (size_t i(0); i != size; ++i)
2465 if (strcmp(name, data[i]) == 0) {
2474 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2475 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2480 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2482 const char **data(objc_copyImageNames(&size));
2483 for (size_t i(0); i != size; ++i)
2484 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2488 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2491 NSString *name(CYCastNSString(pool, property));
2492 if (Protocol *protocol = NSProtocolFromString(name))
2493 return CYMakeInstance(context, protocol, true);
2498 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2500 Protocol **data(objc_copyProtocolList(&size));
2501 for (size_t i(0); i != size; ++i)
2502 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2506 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2507 if (JSStringIsEqualToUTF8CString(property, "nil"))
2508 return Instance::Make(context, nil);
2512 NSString *name(CYCastNSString(pool, property));
2513 if (Class _class = NSClassFromString(name))
2514 return CYMakeInstance(context, _class, true);
2515 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2516 switch ([[entry objectAtIndex:0] intValue]) {
2518 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2520 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2522 // XXX: this is horrendously inefficient
2523 sig::Signature signature;
2524 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2526 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2527 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2533 bool stret(ffi_type *ffi_type) {
2534 return ffi_type->type == FFI_TYPE_STRUCT && (
2535 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2536 struct_forward_array[ffi_type->size] != 0
2541 int *_NSGetArgc(void);
2542 char ***_NSGetArgv(void);
2543 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2546 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2548 NSLog(@"%s", CYCastCString(context, arguments[0]));
2549 return CYJSUndefined(context);
2553 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2556 Class _class(object_getClass(self));
2557 if (Method method = class_getInstanceMethod(_class, _cmd))
2558 type = method_getTypeEncoding(method);
2562 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2564 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2565 type = CYPoolCString(pool, [method _typeString]);
2574 sig::Signature signature;
2575 sig::Parse(pool, &signature, type, &Structor_);
2578 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2580 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2581 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2584 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2594 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2596 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2597 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2598 self = data->GetValue();
2599 uninitialized = data->IsUninitialized();
2603 self = CYCastNSObject(pool, context, arguments[0]);
2604 uninitialized = false;
2608 return CYJSNull(context);
2610 _cmd = CYCastSEL(context, arguments[1]);
2613 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2616 MSHook(void, CYDealloc, id self, SEL sel) {
2617 CYInternal *internal;
2618 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2619 if (internal != NULL)
2621 _CYDealloc(self, sel);
2624 MSHook(void, objc_registerClassPair, Class _class) {
2625 Class super(class_getSuperclass(_class));
2626 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2627 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2628 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2631 _objc_registerClassPair(_class);
2634 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2637 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2639 Class _class(CYCastNSObject(pool, context, arguments[0]));
2640 $objc_registerClassPair(_class);
2641 return CYJSUndefined(context);
2645 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2646 JSValueRef setup[count + 2];
2649 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2650 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2653 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2655 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2657 // XXX: handle Instance::Uninitialized?
2658 id self(CYCastNSObject(pool, context, _this));
2662 setup[1] = &internal->sel_;
2664 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2667 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2669 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2670 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2673 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2676 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2677 const char *name(CYCastCString(context, arguments[0]));
2678 return CYMakeSelector(context, sel_registerName(name));
2682 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2685 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2687 void *value(CYCastPointer<void *>(context, arguments[0]));
2688 const char *type(CYCastCString(context, arguments[1]));
2692 sig::Signature signature;
2693 sig::Parse(pool, &signature, type, &Structor_);
2695 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2699 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2700 Type_privateData *internal(new Type_privateData(NULL, type));
2701 return JSObjectMake(context, Type_, internal);
2704 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2707 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2708 const char *type(CYCastCString(context, arguments[0]));
2709 return CYMakeType(context, object, type);
2713 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2716 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2717 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2718 sig::Type *type(internal->type_);
2719 ffi_type *ffi(internal->GetFFI());
2721 uint8_t value[ffi->size];
2723 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2724 return CYFromFFI(context, type, ffi, value);
2728 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2731 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2732 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2733 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2735 void *value(malloc(internal->GetFFI()->size * size));
2736 return CYMakePointer(context, value, internal->type_, internal->ffi_, NULL);
2740 JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2743 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
2744 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2745 return Instance::Make(context, self);
2749 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2752 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2753 const char *type(CYCastCString(context, arguments[1]));
2754 return CYMakeFunctor(context, arguments[0], type);
2758 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2759 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2760 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2763 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2764 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2765 Type_privateData *typical(internal->GetType());
2770 if (typical == NULL) {
2774 type = typical->type_;
2775 ffi = typical->ffi_;
2778 return CYMakePointer(context, &internal->value_, type, ffi, object);
2781 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2782 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2785 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2789 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2790 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2793 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2794 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2796 sprintf(string, "%p", internal->value_);
2799 return CYCastJSValue(context, string);
2803 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2804 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2805 return Instance::Make(context, object_getClass(internal->GetValue()));
2808 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2809 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2810 id self(internal->GetValue());
2811 // XXX: this is a lame object_isClass
2812 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
2813 return CYJSUndefined(context);
2814 return Prototype::Make(context, self);
2817 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2818 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2822 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
2827 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2828 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2832 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2833 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
2838 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2839 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2843 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
2848 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2849 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2852 return CYCastJSValue(context, sel_getName(data->GetValue()));
2856 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2857 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2860 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2861 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2862 const char *name(sel_getName(internal->GetValue()));
2866 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2871 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2874 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2876 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2877 Class _class(CYCastNSObject(pool, context, arguments[0]));
2878 SEL sel(internal->GetValue());
2879 Method method(class_getInstanceMethod(_class, sel));
2880 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
2881 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
2885 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2887 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2889 const char *type(sig::Unparse(pool, internal->type_));
2891 return CYCastJSValue(context, CYJSString(type));
2896 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2898 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2900 const char *type(sig::Unparse(pool, internal->type_));
2902 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
2907 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2908 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
2911 static JSStaticValue CYValue_staticValues[2] = {
2912 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2913 {NULL, NULL, NULL, 0}
2916 static JSStaticValue Pointer_staticValues[2] = {
2917 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2918 {NULL, NULL, NULL, 0}
2921 static JSStaticFunction Pointer_staticFunctions[4] = {
2922 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2923 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2924 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2928 static JSStaticFunction Struct_staticFunctions[2] = {
2929 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2933 static JSStaticFunction Functor_staticFunctions[4] = {
2934 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2935 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2936 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2940 static JSStaticValue Instance_staticValues[4] = {
2941 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2942 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2943 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2944 {NULL, NULL, NULL, 0}
2947 static JSStaticFunction Instance_staticFunctions[5] = {
2948 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2949 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2950 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2951 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2955 static JSStaticFunction Internal_staticFunctions[2] = {
2956 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2960 static JSStaticFunction Selector_staticFunctions[5] = {
2961 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2962 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2963 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2964 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2968 static JSStaticFunction Type_staticFunctions[4] = {
2969 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2970 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2971 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2975 CYDriver::CYDriver(const std::string &filename) :
2980 filename_(filename),
2986 CYDriver::~CYDriver() {
2990 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2991 CYDriver::Error error;
2992 error.location_ = location;
2993 error.message_ = message;
2994 driver.errors_.push_back(error);
2997 void CYSetArgs(int argc, const char *argv[]) {
2998 JSContextRef context(CYGetJSContext());
2999 JSValueRef args[argc];
3000 for (int i(0); i != argc; ++i)
3001 args[i] = CYCastJSValue(context, argv[i]);
3002 JSValueRef exception(NULL);
3003 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3004 CYThrow(context, exception);
3005 CYSetProperty(context, System_, CYJSString("args"), array);
3008 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3009 return JSContextGetGlobalObject(context);
3012 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3013 JSContextRef context(CYGetJSContext());
3014 JSValueRef exception(NULL), result;
3017 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3018 } catch (const char *error) {
3022 if (exception != NULL) { error:
3027 if (JSValueIsUndefined(context, result))
3030 const char *json(CYPoolCCYON(pool, context, result, &exception));
3031 if (exception != NULL)
3034 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3038 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
3039 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
3047 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
3048 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
3060 const char * volatile data_;
3063 // XXX: this is "tre lame"
3064 @interface CYClient_ : NSObject {
3067 - (void) execute:(NSValue *)value;
3071 @implementation CYClient_
3073 - (void) execute:(NSValue *)value {
3074 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3075 const char *data(execute->data_);
3076 execute->data_ = NULL;
3077 execute->data_ = CYExecute(execute->pool_, data);
3086 apr_thread_t *thread_;
3088 CYClient(int socket) :
3094 _syscall(close(socket_));
3097 void Handle() { _pooled
3098 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3102 if (!CYRecvAll(socket_, &size, sizeof(size)))
3106 char *data(new(pool) char[size + 1]);
3107 if (!CYRecvAll(socket_, data, size))
3111 CYDriver driver("");
3112 cy::parser parser(driver);
3114 driver.data_ = data;
3115 driver.size_ = size;
3118 if (parser.parse() != 0 || !driver.errors_.empty()) {
3120 size = _not(size_t);
3122 std::ostringstream str;
3123 driver.source_->Show(str);
3124 std::string code(str.str());
3125 CYExecute_ execute = {pool, code.c_str()};
3126 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3127 json = execute.data_;
3128 size = json == NULL ? _not(size_t) : strlen(json);
3131 if (!CYSendAll(socket_, &size, sizeof(size)))
3134 if (!CYSendAll(socket_, json, size))
3140 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3141 CYClient *client(reinterpret_cast<CYClient *>(data));
3147 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3148 CYClient *client(new(pool) CYClient(socket));
3149 apr_threadattr_t *attr;
3150 _aprcall(apr_threadattr_create(&attr, client->pool_));
3151 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3154 MSInitialize { _pooled
3155 _aprcall(apr_initialize());
3156 _aprcall(apr_pool_create(&Pool_, NULL));
3158 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3159 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3161 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3163 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3164 NSCFType_ = objc_getClass("NSCFType");
3165 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3166 NSZombie_ = objc_getClass("_NSZombie_");
3167 Object_ = objc_getClass("Object");
3170 JSGlobalContextRef CYGetJSContext() {
3171 if (Context_ == NULL) {
3172 JSClassDefinition definition;
3174 definition = kJSClassDefinitionEmpty;
3175 definition.className = "Functor";
3176 definition.staticFunctions = Functor_staticFunctions;
3177 definition.callAsFunction = &Functor_callAsFunction;
3178 definition.finalize = &Finalize;
3179 Functor_ = JSClassCreate(&definition);
3181 definition = kJSClassDefinitionEmpty;
3182 definition.className = "Instance";
3183 definition.staticValues = Instance_staticValues;
3184 definition.staticFunctions = Instance_staticFunctions;
3185 definition.hasProperty = &Instance_hasProperty;
3186 definition.getProperty = &Instance_getProperty;
3187 definition.setProperty = &Instance_setProperty;
3188 definition.deleteProperty = &Instance_deleteProperty;
3189 definition.getPropertyNames = &Instance_getPropertyNames;
3190 definition.callAsConstructor = &Instance_callAsConstructor;
3191 definition.finalize = &Finalize;
3192 Instance_ = JSClassCreate(&definition);
3194 definition = kJSClassDefinitionEmpty;
3195 definition.className = "Internal";
3196 definition.staticFunctions = Internal_staticFunctions;
3197 definition.hasProperty = &Internal_hasProperty;
3198 definition.getProperty = &Internal_getProperty;
3199 definition.setProperty = &Internal_setProperty;
3200 definition.getPropertyNames = &Internal_getPropertyNames;
3201 definition.finalize = &Finalize;
3202 Internal_ = JSClassCreate(&definition);
3204 definition = kJSClassDefinitionEmpty;
3205 definition.className = "Message";
3206 definition.staticFunctions = Functor_staticFunctions;
3207 definition.callAsFunction = &Message_callAsFunction;
3208 definition.finalize = &Finalize;
3209 Message_ = JSClassCreate(&definition);
3211 definition = kJSClassDefinitionEmpty;
3212 definition.className = "Pointer";
3213 definition.staticValues = Pointer_staticValues;
3214 definition.staticFunctions = Pointer_staticFunctions;
3215 definition.getProperty = &Pointer_getProperty;
3216 definition.setProperty = &Pointer_setProperty;
3217 definition.finalize = &Finalize;
3218 Pointer_ = JSClassCreate(&definition);
3220 definition = kJSClassDefinitionEmpty;
3221 definition.className = "Prototype";
3222 definition.hasProperty = &Prototype_hasProperty;
3223 definition.getProperty = &Prototype_getProperty;
3224 definition.setProperty = &Prototype_setProperty;
3226 definition.deleteProperty = &Prototype_deleteProperty;
3228 definition.getPropertyNames = &Prototype_getPropertyNames;
3229 definition.finalize = &Finalize;
3230 Prototype_ = JSClassCreate(&definition);
3232 definition = kJSClassDefinitionEmpty;
3233 definition.className = "Selector";
3234 definition.staticValues = CYValue_staticValues;
3235 definition.staticFunctions = Selector_staticFunctions;
3236 definition.callAsFunction = &Selector_callAsFunction;
3237 definition.finalize = &Finalize;
3238 Selector_ = JSClassCreate(&definition);
3240 definition = kJSClassDefinitionEmpty;
3241 definition.className = "Struct";
3242 definition.staticFunctions = Struct_staticFunctions;
3243 definition.getProperty = &Struct_getProperty;
3244 definition.setProperty = &Struct_setProperty;
3245 definition.getPropertyNames = &Struct_getPropertyNames;
3246 definition.finalize = &Finalize;
3247 Struct_ = JSClassCreate(&definition);
3249 definition = kJSClassDefinitionEmpty;
3250 definition.className = "Type";
3251 definition.staticFunctions = Type_staticFunctions;
3252 //definition.getProperty = &Type_getProperty;
3253 definition.callAsFunction = &Type_callAsFunction;
3254 definition.callAsConstructor = &Type_callAsConstructor;
3255 definition.finalize = &Finalize;
3256 Type_ = JSClassCreate(&definition);
3258 definition = kJSClassDefinitionEmpty;
3259 definition.className = "Runtime";
3260 definition.getProperty = &Runtime_getProperty;
3261 Runtime_ = JSClassCreate(&definition);
3263 definition = kJSClassDefinitionEmpty;
3264 definition.className = "ObjectiveC::Classes";
3265 definition.getProperty = &ObjectiveC_Classes_getProperty;
3266 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3267 ObjectiveC_Classes_ = JSClassCreate(&definition);
3269 definition = kJSClassDefinitionEmpty;
3270 definition.className = "ObjectiveC::Images";
3271 definition.getProperty = &ObjectiveC_Images_getProperty;
3272 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3273 ObjectiveC_Images_ = JSClassCreate(&definition);
3275 definition = kJSClassDefinitionEmpty;
3276 definition.className = "ObjectiveC::Image::Classes";
3277 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3278 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3279 definition.finalize = &Finalize;
3280 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3282 definition = kJSClassDefinitionEmpty;
3283 definition.className = "ObjectiveC::Protocols";
3284 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3285 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3286 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3288 definition = kJSClassDefinitionEmpty;
3289 //definition.getProperty = &Global_getProperty;
3290 JSClassRef Global(JSClassCreate(&definition));
3292 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3295 JSObjectRef global(CYGetGlobalObject(context));
3297 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3298 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3299 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3301 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3302 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3303 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3305 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3306 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3308 length_ = JSStringCreateWithUTF8CString("length");
3309 message_ = JSStringCreateWithUTF8CString("message");
3310 name_ = JSStringCreateWithUTF8CString("name");
3311 prototype_ = JSStringCreateWithUTF8CString("prototype");
3312 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3313 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3315 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3316 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3318 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3319 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3320 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3322 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3323 CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, &Instance_new));
3324 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3325 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
3326 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3328 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3330 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3332 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3333 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3335 System_ = JSObjectMake(context, NULL, NULL);
3336 CYSetProperty(context, global, CYJSString("system"), System_);
3337 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3338 //CYSetProperty(context, System_, CYJSString("global"), global);
3340 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3342 Result_ = JSStringCreateWithUTF8CString("_");