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 JSObjectRef value(JSObjectMake(context, Prototype_, new Prototype(_class)));
231 if (Class super = class_getSuperclass(_class))
232 JSObjectSetPrototype(context, value, Prototype::Make(context, super));
236 Class GetValue() const {
237 return reinterpret_cast<Class>(value_);
246 Internal(id value, JSObjectRef owner) :
252 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
253 return JSObjectMake(context, Internal_, new Internal(object, owner));
256 id GetValue() const {
257 return reinterpret_cast<id>(value_);
263 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
265 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
266 lhs.name = apr_pstrdup(pool, rhs.name);
267 if (rhs.type == NULL)
270 lhs.type = new(pool) Type;
271 Copy(pool, *lhs.type, *rhs.type);
273 lhs.offset = rhs.offset;
276 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
277 size_t count(rhs.count);
279 lhs.elements = new(pool) Element[count];
280 for (size_t index(0); index != count; ++index)
281 Copy(pool, lhs.elements[index], rhs.elements[index]);
284 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
285 lhs.primitive = rhs.primitive;
286 lhs.name = apr_pstrdup(pool, rhs.name);
287 lhs.flags = rhs.flags;
289 if (sig::IsAggregate(rhs.primitive))
290 Copy(pool, lhs.data.signature, rhs.data.signature);
292 if (rhs.data.data.type != NULL) {
293 lhs.data.data.type = new(pool) Type;
294 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
297 lhs.data.data.size = rhs.data.data.size;
301 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
303 lhs.alignment = rhs.alignment;
305 if (rhs.elements == NULL)
309 while (rhs.elements[count] != NULL)
312 lhs.elements = new(pool) ffi_type *[count + 1];
313 lhs.elements[count] = NULL;
315 for (size_t index(0); index != count; ++index) {
316 // XXX: if these are libffi native then you can just take them
317 ffi_type *ffi(new(pool) ffi_type);
318 lhs.elements[index] = ffi;
319 sig::Copy(pool, *ffi, *rhs.elements[index]);
326 struct CStringMapLess :
327 std::binary_function<const char *, const char *, bool>
329 _finline bool operator ()(const char *lhs, const char *rhs) const {
330 return strcmp(lhs, rhs) < 0;
334 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
339 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
340 switch ([[entry objectAtIndex:0] intValue]) {
342 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
346 sig::Signature signature;
347 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
348 type = signature.elements[0].type;
354 struct Type_privateData :
357 static Type_privateData *Object;
358 static Type_privateData *Selector;
363 void Set(sig::Type *type) {
364 type_ = new(pool_) sig::Type;
365 sig::Copy(pool_, *type_, *type);
368 Type_privateData(apr_pool_t *pool, const char *type) :
374 sig::Signature signature;
375 sig::Parse(pool_, &signature, type, &Structor_);
376 type_ = signature.elements[0].type;
379 Type_privateData(sig::Type *type) :
386 Type_privateData(sig::Type *type, ffi_type *ffi) {
387 ffi_ = new(pool_) ffi_type;
388 sig::Copy(pool_, *ffi_, *ffi);
394 ffi_ = new(pool_) ffi_type;
396 sig::Element element;
398 element.type = type_;
401 sig::Signature signature;
402 signature.elements = &element;
406 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
414 Type_privateData *Type_privateData::Object;
415 Type_privateData *Type_privateData::Selector;
417 Type_privateData *Instance::GetType() const {
418 return Type_privateData::Object;
421 Type_privateData *Selector_privateData::GetType() const {
422 return Type_privateData::Selector;
429 Type_privateData *type_;
431 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
434 type_(new(pool_) Type_privateData(type))
439 struct Struct_privateData :
443 Type_privateData *type_;
445 Struct_privateData(JSObjectRef owner) :
451 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
452 static TypeMap Types_;
454 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
455 Struct_privateData *internal(new Struct_privateData(owner));
456 apr_pool_t *pool(internal->pool_);
457 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
458 internal->type_ = typical;
461 internal->value_ = data;
463 size_t size(typical->GetFFI()->size);
464 void *copy(apr_palloc(internal->pool_, size));
465 memcpy(copy, data, size);
466 internal->value_ = copy;
469 return JSObjectMake(context, Struct_, internal);
472 struct Functor_privateData :
475 sig::Signature signature_;
479 Functor_privateData(const char *type, void (*value)()) :
480 CYValue(reinterpret_cast<void *>(value))
482 sig::Parse(pool_, &signature_, type, &Structor_);
483 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
486 void (*GetValue())() const {
487 return reinterpret_cast<void (*)()>(value_);
491 struct Closure_privateData :
494 JSContextRef context_;
495 JSObjectRef function_;
497 Closure_privateData(const char *type) :
498 Functor_privateData(type, NULL)
503 struct Message_privateData :
508 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
509 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
515 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
516 Instance::Flags flags;
519 flags = Instance::Transient;
521 flags = Instance::None;
522 object = [object retain];
525 return Instance::Make(context, object, flags);
528 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
530 return [value UTF8String];
532 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
533 char *string(new(pool) char[size]);
534 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
535 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
540 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
541 return JSValueMakeBoolean(context, value);
544 JSValueRef CYCastJSValue(JSContextRef context, double value) {
545 return JSValueMakeNumber(context, value);
548 #define CYCastJSValue_(Type_) \
549 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
550 return JSValueMakeNumber(context, static_cast<double>(value)); \
554 CYCastJSValue_(unsigned int)
555 CYCastJSValue_(long int)
556 CYCastJSValue_(long unsigned int)
557 CYCastJSValue_(long long int)
558 CYCastJSValue_(long long unsigned int)
560 JSValueRef CYJSUndefined(JSContextRef context) {
561 return JSValueMakeUndefined(context);
564 bool CYGetIndex(const char *value, ssize_t &index) {
565 if (value[0] != '0') {
567 index = strtol(value, &end, 10);
568 if (value + strlen(value) == end)
570 } else if (value[1] == '\0') {
578 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
579 return CYGetIndex(CYPoolCString(pool, value), index);
582 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
584 @interface NSMethodSignature (Cycript)
585 - (NSString *) _typeString;
588 @interface NSObject (Cycript)
590 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
591 - (JSType) cy$JSType;
593 - (NSObject *) cy$toJSON:(NSString *)key;
594 - (NSString *) cy$toCYON;
595 - (NSString *) cy$toKey;
597 - (bool) cy$hasProperty:(NSString *)name;
598 - (NSObject *) cy$getProperty:(NSString *)name;
599 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
600 - (bool) cy$deleteProperty:(NSString *)name;
605 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
608 @interface NSString (Cycript)
609 - (void *) cy$symbol;
612 struct PropertyAttributes {
617 const char *variable;
630 PropertyAttributes(objc_property_t property) :
642 name = property_getName(property);
643 const char *attributes(property_getAttributes(property));
645 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
647 case 'R': readonly = true; break;
648 case 'C': copy = true; break;
649 case '&': retain = true; break;
650 case 'N': nonatomic = true; break;
651 case 'G': getter_ = token + 1; break;
652 case 'S': setter_ = token + 1; break;
653 case 'V': variable = token + 1; break;
657 /*if (variable == NULL) {
658 variable = property_getName(property);
659 size_t size(strlen(variable));
660 char *name(new(pool_) char[size + 2]);
662 memcpy(name + 1, variable, size);
663 name[size + 1] = '\0';
668 const char *Getter() {
670 getter_ = apr_pstrdup(pool_, name);
674 const char *Setter() {
675 if (setter_ == NULL && !readonly) {
676 size_t length(strlen(name));
678 char *temp(new(pool_) char[length + 5]);
684 temp[3] = toupper(name[0]);
685 memcpy(temp + 4, name + 1, length - 1);
688 temp[length + 3] = ':';
689 temp[length + 4] = '\0';
698 @implementation NSProxy (Cycript)
700 - (NSObject *) cy$toJSON:(NSString *)key {
701 return [self description];
704 - (NSString *) cy$toCYON {
705 return [[self cy$toJSON:@""] cy$toCYON];
710 @implementation NSObject (Cycript)
712 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
713 return CYMakeInstance(context, self, false);
716 - (JSType) cy$JSType {
717 return kJSTypeObject;
720 - (NSObject *) cy$toJSON:(NSString *)key {
721 return [self description];
724 - (NSString *) cy$toCYON {
725 return [[self cy$toJSON:@""] cy$toCYON];
728 - (NSString *) cy$toKey {
729 return [self cy$toCYON];
732 - (bool) cy$hasProperty:(NSString *)name {
736 - (NSObject *) cy$getProperty:(NSString *)name {
740 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
744 - (bool) cy$deleteProperty:(NSString *)name {
750 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
751 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
754 @implementation WebUndefined (Cycript)
756 - (JSType) cy$JSType {
757 return kJSTypeUndefined;
760 - (NSObject *) cy$toJSON:(NSString *)key {
764 - (NSString *) cy$toCYON {
768 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
769 return CYJSUndefined(context);
774 @implementation NSNull (Cycript)
776 - (JSType) cy$JSType {
780 - (NSObject *) cy$toJSON:(NSString *)key {
784 - (NSString *) cy$toCYON {
790 @implementation NSArray (Cycript)
792 - (NSString *) cy$toCYON {
793 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
794 [json appendString:@"["];
797 for (id object in self) {
799 [json appendString:@","];
802 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
803 [json appendString:CYPoolNSCYON(NULL, object)];
805 [json appendString:@","];
810 [json appendString:@"]"];
814 - (bool) cy$hasProperty:(NSString *)name {
815 if ([name isEqualToString:@"length"])
819 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
820 return [super cy$hasProperty:name];
825 - (NSObject *) cy$getProperty:(NSString *)name {
826 if ([name isEqualToString:@"length"])
827 return [NSNumber numberWithUnsignedInteger:[self count]];
830 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
831 return [super cy$getProperty:name];
833 return [self objectAtIndex:index];
838 @implementation NSMutableArray (Cycript)
840 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
842 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
843 return [super cy$setProperty:name to:value];
845 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
850 - (bool) cy$deleteProperty:(NSString *)name {
852 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
853 return [super cy$deleteProperty:name];
855 [self removeObjectAtIndex:index];
862 @implementation NSDictionary (Cycript)
864 - (NSString *) cy$toCYON {
865 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
866 [json appendString:@"{"];
869 for (id key in self) {
871 [json appendString:@","];
874 [json appendString:[key cy$toKey]];
875 [json appendString:@":"];
876 NSObject *object([self objectForKey:key]);
877 [json appendString:CYPoolNSCYON(NULL, object)];
880 [json appendString:@"}"];
884 - (bool) cy$hasProperty:(NSString *)name {
885 return [self objectForKey:name] != nil;
888 - (NSObject *) cy$getProperty:(NSString *)name {
889 return [self objectForKey:name];
894 @implementation NSMutableDictionary (Cycript)
896 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
897 [self setObject:(value ?: [NSNull null]) forKey:name];
901 - (bool) cy$deleteProperty:(NSString *)name {
902 if ([self objectForKey:name] == nil)
905 [self removeObjectForKey:name];
912 @implementation NSNumber (Cycript)
914 - (JSType) cy$JSType {
915 // XXX: this just seems stupid
916 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
919 - (NSObject *) cy$toJSON:(NSString *)key {
923 - (NSString *) cy$toCYON {
924 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
927 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
928 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
933 @implementation NSString (Cycript)
935 - (JSType) cy$JSType {
936 return kJSTypeString;
939 - (NSObject *) cy$toJSON:(NSString *)key {
943 - (NSString *) cy$toCYON {
944 // XXX: this should use the better code from Output.cpp
945 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
947 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
948 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
949 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
950 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
951 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
953 CFStringInsert(json, 0, CFSTR("\""));
954 CFStringAppend(json, CFSTR("\""));
956 return [reinterpret_cast<const NSString *>(json) autorelease];
959 - (NSString *) cy$toKey {
960 const char *value([self UTF8String]);
961 size_t size(strlen(value));
966 if (DigitRange_[value[0]]) {
968 if (!CYGetIndex(NULL, self, index) || index < 0)
971 if (!WordStartRange_[value[0]])
973 for (size_t i(1); i != size; ++i)
974 if (!WordEndRange_[value[i]])
981 return [self cy$toCYON];
984 - (void *) cy$symbol {
986 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
991 @interface CYJSObject : NSDictionary {
993 JSContextRef context_;
996 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
998 - (NSString *) cy$toJSON:(NSString *)key;
1000 - (NSUInteger) count;
1001 - (id) objectForKey:(id)key;
1002 - (NSEnumerator *) keyEnumerator;
1003 - (void) setObject:(id)object forKey:(id)key;
1004 - (void) removeObjectForKey:(id)key;
1008 @interface CYJSArray : NSArray {
1009 JSObjectRef object_;
1010 JSContextRef context_;
1013 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1015 - (NSUInteger) count;
1016 - (id) objectAtIndex:(NSUInteger)index;
1020 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1021 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1022 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1027 @catch (id error) { \
1028 CYThrow(context, error, exception); \
1032 void CYThrow(JSContextRef context, JSValueRef value);
1034 apr_status_t CYPoolRelease_(void *data) {
1035 id object(reinterpret_cast<id>(data));
1040 id CYPoolRelease(apr_pool_t *pool, id object) {
1043 else if (pool == NULL)
1044 return [object autorelease];
1046 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1051 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1052 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1055 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1056 JSValueRef exception(NULL);
1057 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1058 CYThrow(context, exception);
1059 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1060 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1063 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1064 if (!JSValueIsObjectOfClass(context, object, Instance_))
1065 return CYCastNSObject_(pool, context, object);
1067 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1068 return internal->GetValue();
1072 JSStringRef CYCopyJSString(id value) {
1073 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
1076 JSStringRef CYCopyJSString(const char *value) {
1077 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
1080 JSStringRef CYCopyJSString(JSStringRef value) {
1081 return value == NULL ? NULL : JSStringRetain(value);
1084 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
1085 if (JSValueIsNull(context, value))
1087 JSValueRef exception(NULL);
1088 JSStringRef string(JSValueToStringCopy(context, value, &exception));
1089 CYThrow(context, exception);
1095 JSStringRef string_;
1098 if (string_ != NULL)
1099 JSStringRelease(string_);
1103 CYJSString(const CYJSString &rhs) :
1104 string_(CYCopyJSString(rhs.string_))
1108 template <typename Arg0_>
1109 CYJSString(Arg0_ arg0) :
1110 string_(CYCopyJSString(arg0))
1114 template <typename Arg0_, typename Arg1_>
1115 CYJSString(Arg0_ arg0, Arg1_ arg1) :
1116 string_(CYCopyJSString(arg0, arg1))
1120 CYJSString &operator =(const CYJSString &rhs) {
1122 string_ = CYCopyJSString(rhs.string_);
1135 operator JSStringRef() const {
1140 CFStringRef CYCopyCFString(JSStringRef value) {
1141 return JSStringCopyCFString(kCFAllocatorDefault, value);
1144 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1145 return CYCopyCFString(CYJSString(context, value));
1148 double CYCastDouble(const char *value, size_t size) {
1150 double number(strtod(value, &end));
1151 if (end != value + size)
1156 double CYCastDouble(const char *value) {
1157 return CYCastDouble(value, strlen(value));
1160 double CYCastDouble(JSContextRef context, JSValueRef value) {
1161 JSValueRef exception(NULL);
1162 double number(JSValueToNumber(context, value, &exception));
1163 CYThrow(context, exception);
1167 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1168 double number(CYCastDouble(context, value));
1169 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1172 CFStringRef CYCopyCFString(const char *value) {
1173 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1176 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1177 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1180 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1181 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1184 bool CYCastBool(JSContextRef context, JSValueRef value) {
1185 return JSValueToBoolean(context, value);
1188 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1192 switch (JSType type = JSValueGetType(context, value)) {
1193 case kJSTypeUndefined:
1194 object = [WebUndefined undefined];
1202 case kJSTypeBoolean:
1203 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1208 object = CYCopyCFNumber(context, value);
1213 object = CYCopyCFString(context, value);
1218 // XXX: this might could be more efficient
1219 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1224 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1231 return CYPoolRelease(pool, object);
1233 return CFRetain(object);
1236 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1237 return CYCFType(pool, context, value, true);
1240 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1241 return CYCFType(pool, context, value, false);
1244 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1246 size_t size(JSPropertyNameArrayGetCount(names));
1247 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1248 for (size_t index(0); index != size; ++index)
1249 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1253 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1254 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1257 void CYThrow(JSContextRef context, JSValueRef value) {
1260 @throw CYCastNSObject(NULL, context, value);
1263 JSValueRef CYJSNull(JSContextRef context) {
1264 return JSValueMakeNull(context);
1267 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1268 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1271 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1272 return CYCastJSValue(context, CYJSString(value));
1275 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1277 return CYJSNull(context);
1278 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1279 return [value cy$JSValueInContext:context];
1281 return CYMakeInstance(context, value, false);
1284 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1285 JSValueRef exception(NULL);
1286 JSObjectRef object(JSValueToObject(context, value, &exception));
1287 CYThrow(context, exception);
1291 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1292 JSValueRef exception(NULL);
1293 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1294 CYThrow(context, exception);
1298 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1299 JSValueRef exception(NULL);
1300 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1301 CYThrow(context, exception);
1305 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1306 JSValueRef exception(NULL);
1307 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1308 CYThrow(context, exception);
1311 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1312 if (exception == NULL)
1314 *exception = CYCastJSValue(context, error);
1317 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1318 JSValueRef exception(NULL);
1319 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1320 CYThrow(context, exception);
1324 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1325 // XXX: this isn't actually correct
1326 return value != NULL && JSValueIsObject(context, value);
1329 @implementation CYJSObject
1331 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1332 if ((self = [super init]) != nil) {
1338 - (NSObject *) cy$toJSON:(NSString *)key {
1339 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1340 if (!CYIsCallable(context_, toJSON))
1341 return [super cy$toJSON:key];
1343 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1344 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1345 // XXX: do I really want an NSNull here?!
1346 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1350 - (NSString *) cy$toCYON {
1351 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1352 if (!CYIsCallable(context_, toCYON))
1353 return [super cy$toCYON];
1355 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1356 return CYCastNSString(NULL, CYJSString(context_, value));
1360 - (NSUInteger) count {
1361 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1362 size_t size(JSPropertyNameArrayGetCount(names));
1363 JSPropertyNameArrayRelease(names);
1367 - (id) objectForKey:(id)key {
1368 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1371 - (NSEnumerator *) keyEnumerator {
1372 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1373 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1374 JSPropertyNameArrayRelease(names);
1378 - (void) setObject:(id)object forKey:(id)key {
1379 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1382 - (void) removeObjectForKey:(id)key {
1383 JSValueRef exception(NULL);
1384 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1385 CYThrow(context_, exception);
1390 @implementation CYJSArray
1392 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1393 if ((self = [super init]) != nil) {
1399 - (NSUInteger) count {
1400 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1403 - (id) objectAtIndex:(NSUInteger)index {
1404 JSValueRef exception(NULL);
1405 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1406 CYThrow(context_, exception);
1407 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1412 NSString *CYCopyNSCYON(id value) {
1418 Class _class(object_getClass(value));
1419 SEL sel(@selector(cy$toCYON));
1421 if (Method toCYON = class_getInstanceMethod(_class, sel))
1422 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1423 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1424 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1425 string = [value cy$toCYON];
1428 if (value == NSZombie_)
1429 string = @"_NSZombie_";
1430 else if (_class == NSZombie_)
1431 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1432 // XXX: frowny /in/ the pants
1433 else if (value == NSMessageBuilder_ || value == Object_)
1436 string = [NSString stringWithFormat:@"%@", value];
1439 // XXX: frowny pants
1441 string = @"undefined";
1444 return [string retain];
1447 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1448 if (JSValueIsNull(context, value))
1449 return [@"null" retain];
1453 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1458 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1459 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1462 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1463 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1464 const char *string(CYPoolCString(pool, json));
1470 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1474 JSObjectRef object_;
1482 // XXX: delete object_? ;(
1485 static CYInternal *Get(id self) {
1486 CYInternal *internal(NULL);
1487 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1488 // XXX: do something epic? ;P
1494 static CYInternal *Set(id self) {
1495 CYInternal *internal(NULL);
1496 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1497 if (internal == NULL) {
1498 internal = new CYInternal();
1499 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1502 // XXX: do something epic? ;P
1508 bool HasProperty(JSContextRef context, JSStringRef name) {
1509 if (object_ == NULL)
1511 return JSObjectHasProperty(context, object_, name);
1514 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1515 if (object_ == NULL)
1517 return CYGetProperty(context, object_, name);
1520 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1521 if (object_ == NULL)
1522 object_ = JSObjectMake(context, NULL, NULL);
1523 CYSetProperty(context, object_, name, value);
1527 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1528 Selector_privateData *internal(new Selector_privateData(sel));
1529 return JSObjectMake(context, Selector_, internal);
1532 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1533 Pointer *internal(new Pointer(pointer, type, owner));
1534 return JSObjectMake(context, Pointer_, internal);
1537 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1538 Functor_privateData *internal(new Functor_privateData(type, function));
1539 return JSObjectMake(context, Functor_, internal);
1542 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1544 const char *string([CYCastNSString(NULL, value) UTF8String]);
1547 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1548 char *string(new(pool) char[size]);
1549 JSStringGetUTF8CString(value, string, size);
1554 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1555 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1558 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1559 return CYGetIndex(CYPoolCString(pool, value), index);
1562 // XXX: this macro is unhygenic
1563 #define CYCastCString(context, value) ({ \
1565 if (value == NULL) \
1567 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1568 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1569 utf8 = reinterpret_cast<char *>(alloca(size)); \
1570 JSStringGetUTF8CString(string, utf8, size); \
1571 JSStringRelease(string); \
1577 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1578 switch (JSValueGetType(context, value)) {
1581 /*case kJSTypeString:
1582 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1584 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1585 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1586 return internal->value_;
1589 double number(CYCastDouble(context, value));
1590 if (std::isnan(number))
1591 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1592 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1596 template <typename Type_>
1597 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1598 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1601 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1602 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1603 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1604 return reinterpret_cast<SEL>(internal->value_);
1606 return CYCastPointer<SEL>(context, value);
1609 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1610 switch (type->primitive) {
1611 case sig::boolean_P:
1612 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1615 #define CYPoolFFI_(primitive, native) \
1616 case sig::primitive ## _P: \
1617 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1620 CYPoolFFI_(uchar, unsigned char)
1621 CYPoolFFI_(char, char)
1622 CYPoolFFI_(ushort, unsigned short)
1623 CYPoolFFI_(short, short)
1624 CYPoolFFI_(ulong, unsigned long)
1625 CYPoolFFI_(long, long)
1626 CYPoolFFI_(uint, unsigned int)
1627 CYPoolFFI_(int, int)
1628 CYPoolFFI_(ulonglong, unsigned long long)
1629 CYPoolFFI_(longlong, long long)
1630 CYPoolFFI_(float, float)
1631 CYPoolFFI_(double, double)
1634 case sig::typename_P:
1635 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1638 case sig::selector_P:
1639 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1642 case sig::pointer_P:
1643 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1647 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1650 case sig::struct_P: {
1651 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1652 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1653 for (size_t index(0); index != type->data.signature.count; ++index) {
1654 sig::Element *element(&type->data.signature.elements[index]);
1655 ffi_type *field(ffi->elements[index]);
1658 if (aggregate == NULL)
1661 rhs = CYGetProperty(context, aggregate, index);
1662 if (JSValueIsUndefined(context, rhs)) {
1663 if (element->name != NULL)
1664 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1667 if (JSValueIsUndefined(context, rhs)) undefined:
1668 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1672 CYPoolFFI(pool, context, element->type, field, base, rhs);
1674 base += field->size;
1682 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1687 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1690 switch (type->primitive) {
1691 case sig::boolean_P:
1692 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1695 #define CYFromFFI_(primitive, native) \
1696 case sig::primitive ## _P: \
1697 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1700 CYFromFFI_(uchar, unsigned char)
1701 CYFromFFI_(char, char)
1702 CYFromFFI_(ushort, unsigned short)
1703 CYFromFFI_(short, short)
1704 CYFromFFI_(ulong, unsigned long)
1705 CYFromFFI_(long, long)
1706 CYFromFFI_(uint, unsigned int)
1707 CYFromFFI_(int, int)
1708 CYFromFFI_(ulonglong, unsigned long long)
1709 CYFromFFI_(longlong, long long)
1710 CYFromFFI_(float, float)
1711 CYFromFFI_(double, double)
1713 case sig::object_P: {
1714 if (id object = *reinterpret_cast<id *>(data)) {
1715 value = CYCastJSValue(context, object);
1721 case sig::typename_P:
1722 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1725 case sig::selector_P:
1726 if (SEL sel = *reinterpret_cast<SEL *>(data))
1727 value = CYMakeSelector(context, sel);
1731 case sig::pointer_P:
1732 if (void *pointer = *reinterpret_cast<void **>(data))
1733 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1738 if (char *utf8 = *reinterpret_cast<char **>(data))
1739 value = CYCastJSValue(context, utf8);
1744 value = CYMakeStruct(context, data, type, ffi, owner);
1748 value = CYJSUndefined(context);
1752 value = CYJSNull(context);
1756 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1763 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1764 if (Method method = class_getInstanceMethod(_class, selector)) {
1768 method_getReturnType(method, type, sizeof(type));
1773 // XXX: possibly use a more "awesome" check?
1777 const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
1779 return method_getTypeEncoding(method);
1780 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1781 return CYPoolCString(pool, type);
1786 void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1787 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1789 JSContextRef context(internal->context_);
1791 size_t count(internal->cif_.nargs);
1792 JSValueRef values[count];
1794 for (size_t index(0); index != count; ++index)
1795 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1797 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
1798 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1801 void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1802 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1804 JSContextRef context(internal->context_);
1806 size_t count(internal->cif_.nargs);
1807 JSValueRef values[count];
1809 for (size_t index(0); index != count; ++index)
1810 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1812 JSObjectRef _this(CYCastJSObject(context, values[0]));
1814 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1815 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1818 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
1819 // XXX: in case of exceptions this will leak
1820 // XXX: in point of fact, this may /need/ to leak :(
1821 Closure_privateData *internal(new Closure_privateData(type));
1823 ffi_closure *closure((ffi_closure *) _syscall(mmap(
1824 NULL, sizeof(ffi_closure),
1825 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1829 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
1830 _assert(status == FFI_OK);
1832 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1834 internal->value_ = closure;
1836 internal->context_ = CYGetJSContext();
1837 internal->function_ = function;
1842 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1843 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
1844 return JSObjectMake(context, Functor_, internal);
1847 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
1848 JSValueRef exception(NULL);
1849 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
1850 CYThrow(context, exception);
1853 JSObjectRef function(CYCastJSObject(context, value));
1854 return CYMakeFunctor(context, function, type);
1856 void (*function)()(CYCastPointer<void (*)()>(context, value));
1857 return CYMakeFunctor(context, function, type);
1861 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1862 Message_privateData *internal(new Message_privateData(sel, type, imp));
1863 return JSObjectMake(context, Message_, internal);
1866 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1867 JSObjectRef function(CYCastJSObject(context, value));
1868 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1869 return reinterpret_cast<IMP>(internal->GetValue());
1872 static bool Prototype_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1873 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1874 Class _class(internal->GetValue());
1877 const char *name(CYPoolCString(pool, property));
1879 if (SEL sel = sel_getUid(name))
1880 if (class_getInstanceMethod(_class, sel) != NULL)
1886 static JSValueRef Prototype_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1887 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1888 Class _class(internal->GetValue());
1891 const char *name(CYPoolCString(pool, property));
1893 if (SEL sel = sel_getUid(name))
1894 if (Method method = class_getInstanceMethod(_class, sel))
1895 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1900 static bool Prototype_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1901 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1902 Class _class(internal->GetValue());
1905 const char *name(CYPoolCString(pool, property));
1907 SEL sel(sel_registerName(name));
1909 Method method(class_getInstanceMethod(_class, sel));
1914 if (JSValueIsObjectOfClass(context, value, Message_)) {
1915 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1916 type = sig::Unparse(pool, &message->signature_);
1917 imp = reinterpret_cast<IMP>(message->GetValue());
1919 type = CYPoolTypeEncoding(pool, _class, sel, method);
1920 imp = CYMakeMessage(context, value, type);
1924 method_setImplementation(method, imp);
1926 class_replaceMethod(_class, sel, imp, type);
1932 static bool Prototype_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1933 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1934 Class _class(internal->GetValue());
1937 const char *name(CYPoolCString(pool, property));
1939 if (SEL sel = sel_getUid(name))
1940 if (Method method = class_getInstanceMethod(_class, sel)) {
1941 objc_method_list list = {NULL, 1, {method}};
1942 class_removeMethods(_class, &list);
1950 static void Prototype_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1951 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1952 Class _class(internal->GetValue());
1955 Method *data(class_copyMethodList(_class, &size));
1956 for (size_t i(0); i != size; ++i)
1957 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1961 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1962 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1963 id self(internal->GetValue());
1965 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1969 NSString *name(CYCastNSString(pool, property));
1971 if (CYInternal *internal = CYInternal::Get(self))
1972 if (internal->HasProperty(context, property))
1976 if ([self cy$hasProperty:name])
1978 } CYPoolCatch(false)
1980 const char *string(CYPoolCString(pool, name));
1981 Class _class(object_getClass(self));
1983 if (class_getProperty(_class, string) != NULL)
1986 if (SEL sel = sel_getUid(string))
1987 if (CYImplements(self, _class, sel, true))
1993 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1994 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1995 id self(internal->GetValue());
1997 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1998 return Internal::Make(context, self, object);
2002 NSString *name(CYCastNSString(pool, property));
2004 if (CYInternal *internal = CYInternal::Get(self))
2005 if (JSValueRef value = internal->GetProperty(context, property))
2009 if (NSObject *data = [self cy$getProperty:name])
2010 return CYCastJSValue(context, data);
2013 const char *string(CYPoolCString(pool, name));
2014 Class _class(object_getClass(self));
2016 if (objc_property_t property = class_getProperty(_class, string)) {
2017 PropertyAttributes attributes(property);
2018 SEL sel(sel_registerName(attributes.Getter()));
2019 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2022 if (SEL sel = sel_getUid(string))
2023 if (CYImplements(self, _class, sel, true))
2024 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2030 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2031 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2032 id self(internal->GetValue());
2037 NSString *name(CYCastNSString(pool, property));
2038 NSString *data(CYCastNSObject(pool, context, value));
2041 if ([self cy$setProperty:name to:data])
2045 const char *string(CYPoolCString(pool, name));
2046 Class _class(object_getClass(self));
2048 if (objc_property_t property = class_getProperty(_class, string)) {
2049 PropertyAttributes attributes(property);
2050 if (const char *setter = attributes.Setter()) {
2051 SEL sel(sel_registerName(setter));
2052 JSValueRef arguments[1] = {value};
2053 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2058 size_t length(strlen(string));
2060 char set[length + 5];
2066 if (string[0] != '\0') {
2067 set[3] = toupper(string[0]);
2068 memcpy(set + 4, string + 1, length - 1);
2071 set[length + 3] = ':';
2072 set[length + 4] = '\0';
2074 if (SEL sel = sel_getUid(set))
2075 if (CYImplements(self, _class, sel, false)) {
2076 JSValueRef arguments[1] = {value};
2077 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2080 if (CYInternal *internal = CYInternal::Set(self)) {
2081 internal->SetProperty(context, property, value);
2089 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2090 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2091 id self(internal->GetValue());
2095 NSString *name(CYCastNSString(NULL, property));
2096 return [self cy$deleteProperty:name];
2101 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2102 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2103 id self(internal->GetValue());
2106 Class _class(object_getClass(self));
2110 objc_property_t *data(class_copyPropertyList(_class, &size));
2111 for (size_t i(0); i != size; ++i)
2112 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2117 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2119 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2120 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2125 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2126 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2129 id self(internal->GetValue());
2130 const char *name(CYPoolCString(pool, property));
2132 if (object_getInstanceVariable(self, name, NULL) != NULL)
2138 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2139 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2143 id self(internal->GetValue());
2144 const char *name(CYPoolCString(pool, property));
2146 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2147 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2148 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2155 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2156 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2160 id self(internal->GetValue());
2161 const char *name(CYPoolCString(pool, property));
2163 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2164 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2165 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2173 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2174 if (Class super = class_getSuperclass(_class))
2175 Internal_getPropertyNames_(super, names);
2178 Ivar *data(class_copyIvarList(_class, &size));
2179 for (size_t i(0); i != size; ++i)
2180 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2184 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2185 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2188 id self(internal->GetValue());
2189 Class _class(object_getClass(self));
2191 Internal_getPropertyNames_(_class, names);
2194 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2195 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2196 return internal->owner_;
2199 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2200 Type_privateData *typical(internal->type_);
2201 sig::Type *type(typical->type_);
2205 const char *name(CYPoolCString(pool, property));
2206 size_t length(strlen(name));
2207 double number(CYCastDouble(name, length));
2209 size_t count(type->data.signature.count);
2211 if (std::isnan(number)) {
2212 if (property == NULL)
2215 sig::Element *elements(type->data.signature.elements);
2217 for (size_t local(0); local != count; ++local) {
2218 sig::Element *element(&elements[local]);
2219 if (element->name != NULL && strcmp(name, element->name) == 0) {
2227 index = static_cast<ssize_t>(number);
2228 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2233 ffi_type **elements(typical->GetFFI()->elements);
2235 base = reinterpret_cast<uint8_t *>(internal->value_);
2236 for (ssize_t local(0); local != index; ++local)
2237 base += elements[local]->size;
2242 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2243 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2244 Type_privateData *typical(internal->type_);
2246 ffi_type *ffi(typical->GetFFI());
2248 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2249 base += ffi->size * index;
2251 JSObjectRef owner(internal->owner_ ?: object);
2254 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2258 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2260 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2261 Type_privateData *typical(internal->type_);
2263 if (typical->type_ == NULL)
2267 if (!CYGetIndex(pool, property, index))
2270 return Pointer_getIndex(context, object, index, exception);
2273 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2274 return Pointer_getIndex(context, object, 0, exception);
2277 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2278 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2279 Type_privateData *typical(internal->type_);
2281 ffi_type *ffi(typical->GetFFI());
2283 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2284 base += ffi->size * index;
2287 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2292 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2294 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2295 Type_privateData *typical(internal->type_);
2297 if (typical->type_ == NULL)
2301 if (!CYGetIndex(pool, property, index))
2304 return Pointer_setIndex(context, object, 0, value, exception);
2307 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2308 return Pointer_setIndex(context, object, 0, value, exception);
2311 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2312 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2313 Type_privateData *typical(internal->type_);
2314 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2317 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2319 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2320 Type_privateData *typical(internal->type_);
2325 if (!Index_(pool, internal, property, index, base))
2328 JSObjectRef owner(internal->owner_ ?: object);
2331 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2335 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2337 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2338 Type_privateData *typical(internal->type_);
2343 if (!Index_(pool, internal, property, index, base))
2347 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2352 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2353 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2354 Type_privateData *typical(internal->type_);
2355 sig::Type *type(typical->type_);
2360 size_t count(type->data.signature.count);
2361 sig::Element *elements(type->data.signature.elements);
2365 for (size_t index(0); index != count; ++index) {
2367 name = elements[index].name;
2370 sprintf(number, "%lu", index);
2374 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2378 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)()) {
2380 if (setups + count != signature->count - 1)
2381 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2383 size_t size(setups + count);
2385 memcpy(values, setup, sizeof(void *) * setups);
2387 for (size_t index(setups); index != size; ++index) {
2388 sig::Element *element(&signature->elements[index + 1]);
2389 ffi_type *ffi(cif->arg_types[index]);
2391 values[index] = new(pool) uint8_t[ffi->size];
2392 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2395 uint8_t value[cif->rtype->size];
2396 ffi_call(cif, function, value, values);
2398 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2402 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2405 NSString *name(CYCastNSString(pool, property));
2406 if (Class _class = NSClassFromString(name))
2407 return CYMakeInstance(context, _class, true);
2412 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2413 size_t size(objc_getClassList(NULL, 0));
2414 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2417 size_t writ(objc_getClassList(data, size));
2420 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2426 for (size_t i(0); i != writ; ++i)
2427 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2433 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2434 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2438 const char *name(CYPoolCString(pool, property));
2440 const char **data(objc_copyClassNamesForImage(internal, &size));
2442 for (size_t i(0); i != size; ++i)
2443 if (strcmp(name, data[i]) == 0) {
2444 if (Class _class = objc_getClass(name)) {
2445 value = CYMakeInstance(context, _class, true);
2457 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2458 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2460 const char **data(objc_copyClassNamesForImage(internal, &size));
2461 for (size_t i(0); i != size; ++i)
2462 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2466 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2469 const char *name(CYPoolCString(pool, property));
2471 const char **data(objc_copyImageNames(&size));
2472 for (size_t i(0); i != size; ++i)
2473 if (strcmp(name, data[i]) == 0) {
2482 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2483 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2488 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2490 const char **data(objc_copyImageNames(&size));
2491 for (size_t i(0); i != size; ++i)
2492 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2496 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2499 NSString *name(CYCastNSString(pool, property));
2500 if (Protocol *protocol = NSProtocolFromString(name))
2501 return CYMakeInstance(context, protocol, true);
2506 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2508 Protocol **data(objc_copyProtocolList(&size));
2509 for (size_t i(0); i != size; ++i)
2510 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2514 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2515 if (JSStringIsEqualToUTF8CString(property, "nil"))
2516 return Instance::Make(context, nil);
2520 NSString *name(CYCastNSString(pool, property));
2521 if (Class _class = NSClassFromString(name))
2522 return CYMakeInstance(context, _class, true);
2523 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2524 switch ([[entry objectAtIndex:0] intValue]) {
2526 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2528 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2530 // XXX: this is horrendously inefficient
2531 sig::Signature signature;
2532 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2534 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2535 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2541 bool stret(ffi_type *ffi_type) {
2542 return ffi_type->type == FFI_TYPE_STRUCT && (
2543 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2544 struct_forward_array[ffi_type->size] != 0
2549 int *_NSGetArgc(void);
2550 char ***_NSGetArgv(void);
2551 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2554 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2556 NSLog(@"%s", CYCastCString(context, arguments[0]));
2557 return CYJSUndefined(context);
2561 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2564 Class _class(object_getClass(self));
2565 if (Method method = class_getInstanceMethod(_class, _cmd))
2566 type = method_getTypeEncoding(method);
2570 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2572 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2573 type = CYPoolCString(pool, [method _typeString]);
2582 sig::Signature signature;
2583 sig::Parse(pool, &signature, type, &Structor_);
2586 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2588 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2589 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2592 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2602 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2604 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2605 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2606 self = internal->GetValue();
2607 uninitialized = internal->IsUninitialized();
2609 internal->value_ = nil;
2611 self = CYCastNSObject(pool, context, arguments[0]);
2612 uninitialized = false;
2616 return CYJSNull(context);
2618 _cmd = CYCastSEL(context, arguments[1]);
2621 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2624 MSHook(void, CYDealloc, id self, SEL sel) {
2625 CYInternal *internal;
2626 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2627 if (internal != NULL)
2629 _CYDealloc(self, sel);
2632 MSHook(void, objc_registerClassPair, Class _class) {
2633 Class super(class_getSuperclass(_class));
2634 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2635 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2636 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2639 _objc_registerClassPair(_class);
2642 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2645 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2647 Class _class(CYCastNSObject(pool, context, arguments[0]));
2648 $objc_registerClassPair(_class);
2649 return CYJSUndefined(context);
2653 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2654 JSValueRef setup[count + 2];
2657 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2658 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2661 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2663 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2665 // XXX: handle Instance::Uninitialized?
2666 id self(CYCastNSObject(pool, context, _this));
2670 setup[1] = &internal->sel_;
2672 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2675 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2677 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2678 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2681 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2684 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2685 const char *name(CYCastCString(context, arguments[0]));
2686 return CYMakeSelector(context, sel_registerName(name));
2690 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2693 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2695 void *value(CYCastPointer<void *>(context, arguments[0]));
2696 const char *type(CYCastCString(context, arguments[1]));
2700 sig::Signature signature;
2701 sig::Parse(pool, &signature, type, &Structor_);
2703 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2707 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2708 Type_privateData *internal(new Type_privateData(NULL, type));
2709 return JSObjectMake(context, Type_, internal);
2712 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2715 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2716 const char *type(CYCastCString(context, arguments[0]));
2717 return CYMakeType(context, object, type);
2721 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2724 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2725 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2726 sig::Type *type(internal->type_);
2727 ffi_type *ffi(internal->GetFFI());
2729 uint8_t value[ffi->size];
2731 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2732 return CYFromFFI(context, type, ffi, value);
2736 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2739 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2740 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2741 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2743 void *value(malloc(internal->GetFFI()->size * size));
2744 return CYMakePointer(context, value, internal->type_, internal->ffi_, NULL);
2748 JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2751 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
2752 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2753 return Instance::Make(context, self);
2757 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2760 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2761 const char *type(CYCastCString(context, arguments[1]));
2762 return CYMakeFunctor(context, arguments[0], type);
2766 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2767 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2768 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2771 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2772 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2773 Type_privateData *typical(internal->GetType());
2778 if (typical == NULL) {
2782 type = typical->type_;
2783 ffi = typical->ffi_;
2786 return CYMakePointer(context, &internal->value_, type, ffi, object);
2789 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2790 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2793 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2797 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2798 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2801 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2802 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2804 sprintf(string, "%p", internal->value_);
2807 return CYCastJSValue(context, string);
2811 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2812 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2813 return Instance::Make(context, object_getClass(internal->GetValue()));
2816 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2817 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2818 id self(internal->GetValue());
2819 // XXX: this is a lame object_isClass
2820 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
2821 return CYJSUndefined(context);
2822 return Prototype::Make(context, self);
2825 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2826 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2830 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
2835 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2836 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2840 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2841 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
2846 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2847 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2851 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
2856 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2857 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2860 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2864 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2865 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2868 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2869 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2870 const char *name(sel_getName(internal->GetValue()));
2874 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2879 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2882 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2884 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2885 Class _class(CYCastNSObject(pool, context, arguments[0]));
2886 SEL sel(internal->GetValue());
2887 Method method(class_getInstanceMethod(_class, sel));
2888 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
2889 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
2893 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2895 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2897 const char *type(sig::Unparse(pool, internal->type_));
2899 return CYCastJSValue(context, CYJSString(type));
2904 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2906 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2908 const char *type(sig::Unparse(pool, internal->type_));
2910 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
2915 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2916 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
2919 static JSStaticValue CYValue_staticValues[2] = {
2920 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2921 {NULL, NULL, NULL, 0}
2924 static JSStaticValue Pointer_staticValues[2] = {
2925 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2926 {NULL, NULL, NULL, 0}
2929 static JSStaticFunction Pointer_staticFunctions[4] = {
2930 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2931 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2932 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2936 static JSStaticFunction Struct_staticFunctions[2] = {
2937 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2941 static JSStaticFunction Functor_staticFunctions[4] = {
2942 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2943 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2944 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2948 static JSStaticValue Instance_staticValues[4] = {
2949 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2950 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2951 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2952 {NULL, NULL, NULL, 0}
2955 static JSStaticFunction Instance_staticFunctions[5] = {
2956 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2957 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2958 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2959 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2963 static JSStaticFunction Internal_staticFunctions[2] = {
2964 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2968 static JSStaticFunction Selector_staticFunctions[5] = {
2969 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2970 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2971 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2972 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2976 static JSStaticFunction Type_staticFunctions[4] = {
2977 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2978 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2979 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2983 CYDriver::CYDriver(const std::string &filename) :
2988 filename_(filename),
2994 CYDriver::~CYDriver() {
2998 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2999 CYDriver::Error error;
3000 error.location_ = location;
3001 error.message_ = message;
3002 driver.errors_.push_back(error);
3005 void CYSetArgs(int argc, const char *argv[]) {
3006 JSContextRef context(CYGetJSContext());
3007 JSValueRef args[argc];
3008 for (int i(0); i != argc; ++i)
3009 args[i] = CYCastJSValue(context, argv[i]);
3010 JSValueRef exception(NULL);
3011 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3012 CYThrow(context, exception);
3013 CYSetProperty(context, System_, CYJSString("args"), array);
3016 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3017 return JSContextGetGlobalObject(context);
3020 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3021 JSContextRef context(CYGetJSContext());
3022 JSValueRef exception(NULL), result;
3025 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3026 } catch (const char *error) {
3030 if (exception != NULL) { error:
3035 if (JSValueIsUndefined(context, result))
3038 const char *json(CYPoolCCYON(pool, context, result, &exception));
3039 if (exception != NULL)
3042 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3046 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
3047 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
3055 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
3056 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
3068 const char * volatile data_;
3071 // XXX: this is "tre lame"
3072 @interface CYClient_ : NSObject {
3075 - (void) execute:(NSValue *)value;
3079 @implementation CYClient_
3081 - (void) execute:(NSValue *)value {
3082 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3083 const char *data(execute->data_);
3084 execute->data_ = NULL;
3085 execute->data_ = CYExecute(execute->pool_, data);
3094 apr_thread_t *thread_;
3096 CYClient(int socket) :
3102 _syscall(close(socket_));
3105 void Handle() { _pooled
3106 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3110 if (!CYRecvAll(socket_, &size, sizeof(size)))
3114 char *data(new(pool) char[size + 1]);
3115 if (!CYRecvAll(socket_, data, size))
3119 CYDriver driver("");
3120 cy::parser parser(driver);
3122 driver.data_ = data;
3123 driver.size_ = size;
3126 if (parser.parse() != 0 || !driver.errors_.empty()) {
3128 size = _not(size_t);
3130 std::ostringstream str;
3131 driver.source_->Show(str);
3132 std::string code(str.str());
3133 CYExecute_ execute = {pool, code.c_str()};
3134 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3135 json = execute.data_;
3136 size = json == NULL ? _not(size_t) : strlen(json);
3139 if (!CYSendAll(socket_, &size, sizeof(size)))
3142 if (!CYSendAll(socket_, json, size))
3148 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3149 CYClient *client(reinterpret_cast<CYClient *>(data));
3155 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3156 CYClient *client(new(pool) CYClient(socket));
3157 apr_threadattr_t *attr;
3158 _aprcall(apr_threadattr_create(&attr, client->pool_));
3159 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3162 MSInitialize { _pooled
3163 _aprcall(apr_initialize());
3164 _aprcall(apr_pool_create(&Pool_, NULL));
3166 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3167 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3169 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3171 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3172 NSCFType_ = objc_getClass("NSCFType");
3173 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3174 NSZombie_ = objc_getClass("_NSZombie_");
3175 Object_ = objc_getClass("Object");
3178 JSGlobalContextRef CYGetJSContext() {
3179 if (Context_ == NULL) {
3180 JSClassDefinition definition;
3182 definition = kJSClassDefinitionEmpty;
3183 definition.className = "Functor";
3184 definition.staticFunctions = Functor_staticFunctions;
3185 definition.callAsFunction = &Functor_callAsFunction;
3186 definition.finalize = &Finalize;
3187 Functor_ = JSClassCreate(&definition);
3189 definition = kJSClassDefinitionEmpty;
3190 definition.className = "Instance";
3191 definition.staticValues = Instance_staticValues;
3192 definition.staticFunctions = Instance_staticFunctions;
3193 definition.hasProperty = &Instance_hasProperty;
3194 definition.getProperty = &Instance_getProperty;
3195 definition.setProperty = &Instance_setProperty;
3196 definition.deleteProperty = &Instance_deleteProperty;
3197 definition.getPropertyNames = &Instance_getPropertyNames;
3198 definition.callAsConstructor = &Instance_callAsConstructor;
3199 definition.finalize = &Finalize;
3200 Instance_ = JSClassCreate(&definition);
3202 definition = kJSClassDefinitionEmpty;
3203 definition.className = "Internal";
3204 definition.staticFunctions = Internal_staticFunctions;
3205 definition.hasProperty = &Internal_hasProperty;
3206 definition.getProperty = &Internal_getProperty;
3207 definition.setProperty = &Internal_setProperty;
3208 definition.getPropertyNames = &Internal_getPropertyNames;
3209 definition.finalize = &Finalize;
3210 Internal_ = JSClassCreate(&definition);
3212 definition = kJSClassDefinitionEmpty;
3213 definition.className = "Message";
3214 definition.staticFunctions = Functor_staticFunctions;
3215 definition.callAsFunction = &Message_callAsFunction;
3216 definition.finalize = &Finalize;
3217 Message_ = JSClassCreate(&definition);
3219 definition = kJSClassDefinitionEmpty;
3220 definition.className = "Pointer";
3221 definition.staticValues = Pointer_staticValues;
3222 definition.staticFunctions = Pointer_staticFunctions;
3223 definition.getProperty = &Pointer_getProperty;
3224 definition.setProperty = &Pointer_setProperty;
3225 definition.finalize = &Finalize;
3226 Pointer_ = JSClassCreate(&definition);
3228 definition = kJSClassDefinitionEmpty;
3229 definition.className = "Prototype";
3230 definition.hasProperty = &Prototype_hasProperty;
3231 definition.getProperty = &Prototype_getProperty;
3232 definition.setProperty = &Prototype_setProperty;
3234 definition.deleteProperty = &Prototype_deleteProperty;
3236 definition.getPropertyNames = &Prototype_getPropertyNames;
3237 definition.finalize = &Finalize;
3238 Prototype_ = JSClassCreate(&definition);
3240 definition = kJSClassDefinitionEmpty;
3241 definition.className = "Selector";
3242 definition.staticValues = CYValue_staticValues;
3243 definition.staticFunctions = Selector_staticFunctions;
3244 definition.callAsFunction = &Selector_callAsFunction;
3245 definition.finalize = &Finalize;
3246 Selector_ = JSClassCreate(&definition);
3248 definition = kJSClassDefinitionEmpty;
3249 definition.className = "Struct";
3250 definition.staticFunctions = Struct_staticFunctions;
3251 definition.getProperty = &Struct_getProperty;
3252 definition.setProperty = &Struct_setProperty;
3253 definition.getPropertyNames = &Struct_getPropertyNames;
3254 definition.finalize = &Finalize;
3255 Struct_ = JSClassCreate(&definition);
3257 definition = kJSClassDefinitionEmpty;
3258 definition.className = "Type";
3259 definition.staticFunctions = Type_staticFunctions;
3260 //definition.getProperty = &Type_getProperty;
3261 definition.callAsFunction = &Type_callAsFunction;
3262 definition.callAsConstructor = &Type_callAsConstructor;
3263 definition.finalize = &Finalize;
3264 Type_ = JSClassCreate(&definition);
3266 definition = kJSClassDefinitionEmpty;
3267 definition.className = "Runtime";
3268 definition.getProperty = &Runtime_getProperty;
3269 Runtime_ = JSClassCreate(&definition);
3271 definition = kJSClassDefinitionEmpty;
3272 definition.className = "ObjectiveC::Classes";
3273 definition.getProperty = &ObjectiveC_Classes_getProperty;
3274 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3275 ObjectiveC_Classes_ = JSClassCreate(&definition);
3277 definition = kJSClassDefinitionEmpty;
3278 definition.className = "ObjectiveC::Images";
3279 definition.getProperty = &ObjectiveC_Images_getProperty;
3280 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3281 ObjectiveC_Images_ = JSClassCreate(&definition);
3283 definition = kJSClassDefinitionEmpty;
3284 definition.className = "ObjectiveC::Image::Classes";
3285 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3286 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3287 definition.finalize = &Finalize;
3288 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3290 definition = kJSClassDefinitionEmpty;
3291 definition.className = "ObjectiveC::Protocols";
3292 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3293 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3294 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3296 definition = kJSClassDefinitionEmpty;
3297 //definition.getProperty = &Global_getProperty;
3298 JSClassRef Global(JSClassCreate(&definition));
3300 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3303 JSObjectRef global(CYGetGlobalObject(context));
3305 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3306 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3307 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3309 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3310 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3311 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3313 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3314 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3316 length_ = JSStringCreateWithUTF8CString("length");
3317 message_ = JSStringCreateWithUTF8CString("message");
3318 name_ = JSStringCreateWithUTF8CString("name");
3319 prototype_ = JSStringCreateWithUTF8CString("prototype");
3320 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3321 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3323 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3324 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3325 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3327 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3328 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3329 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3330 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3332 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3333 CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, &Instance_new));
3334 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3335 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3336 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3338 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3340 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3342 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3343 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3345 System_ = JSObjectMake(context, NULL, NULL);
3346 CYSetProperty(context, global, CYJSString("system"), System_);
3347 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3348 //CYSetProperty(context, System_, CYJSString("global"), global);
3350 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3352 Result_ = JSStringCreateWithUTF8CString("_");