]> git.saurik.com Git - cycript.git/blame - ObjectiveC/Library.mm
Removed all global cache objects, placing them in a object in the context.
[cycript.git] / ObjectiveC / Library.mm
CommitLineData
7c6c5b0a 1#if defined(__APPLE__) && defined(__arm__)
37954781 2#include <substrate.h>
7c6c5b0a
JF
3#else
4#include <objc/objc-api.h>
b5dd57dc 5#endif
3c1c3635 6
37954781 7#include "ObjectiveC/Internal.hpp"
aabea98c
JF
8
9#ifdef __APPLE__
37954781 10#include "Struct.hpp"
aabea98c 11#endif
3c1c3635 12
37954781 13#include <Foundation/Foundation.h>
3c1c3635 14
aabea98c
JF
15#include <objc/Protocol.h>
16
37954781 17#include "cycript.hpp"
3c1c3635 18
37954781 19#include "ObjectiveC/Internal.hpp"
3c1c3635 20
37954781
JF
21#ifdef __APPLE__
22#include <CoreFoundation/CoreFoundation.h>
37954781
JF
23#include <JavaScriptCore/JSStringRefCF.h>
24#include <WebKit/WebScriptObject.h>
25#endif
3c1c3635 26
37954781
JF
27#include "Error.hpp"
28#include "JavaScript.hpp"
29#include "String.hpp"
3c1c3635 30
aabea98c 31#include <cmath>
37954781 32#include <map>
3c1c3635 33
37954781
JF
34#define CYObjectiveTry_(context) { \
35 JSContextRef context_(context); \
36 try
37#define CYObjectiveTry { \
38 try
39#define CYObjectiveCatch \
40 catch (const CYException &error) { \
41 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
42 } \
3c1c3635
JF
43}
44
37954781
JF
45#define CYPoolTry { \
46 id _saved(nil); \
47 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
48 @try
49#define CYPoolCatch(value) \
50 @catch (NSException *error) { \
51 _saved = [error retain]; \
52 throw CYJSError(context, CYCastJSValue(context, error)); \
53 return value; \
54 } @finally { \
55 [_pool release]; \
56 if (_saved != nil) \
57 [_saved autorelease]; \
58 } \
3c1c3635
JF
59}
60
37954781
JF
61#ifndef __APPLE__
62#define class_getSuperclass GSObjCSuper
aabea98c
JF
63#define class_getInstanceVariable GSCGetInstanceVariableDefinition
64#define class_getName GSNameFromClass
65
66#define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
67
68#define ivar_getName(ivar) ((ivar)->ivar_name)
69#define ivar_getOffset(ivar) ((ivar)->ivar_offset)
70#define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
71
72#define method_getName(method) ((method)->method_name)
73#define method_getImplementation(method) ((method)->method_imp)
74#define method_getTypeEncoding(method) ((method)->method_types)
75#define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
76
ba4fa42f
JF
77#undef objc_getClass
78#define objc_getClass GSClassFromName
79
aabea98c
JF
80#define objc_getProtocol GSProtocolFromName
81
37954781 82#define object_getClass GSObjCClass
aabea98c
JF
83
84#define object_getInstanceVariable(object, name, value) ({ \
85 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
ba4fa42f
JF
86 if (ivar != NULL) \
87 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
aabea98c
JF
88 ivar; \
89})
90
91#define object_setIvar(object, ivar, value) ({ \
92 void *data = (value); \
93 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
94})
95
96#define protocol_getName(protocol) [(protocol) name]
37954781 97#endif
3c1c3635 98
37954781 99JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
3c1c3635 100
37954781 101extern sqlite3 *Bridge_;
3c1c3635
JF
102
103/* Objective-C Pool Release {{{ */
104apr_status_t CYPoolRelease_(void *data) {
105 id object(reinterpret_cast<id>(data));
106 [object release];
107 return APR_SUCCESS;
108}
109
110id CYPoolRelease_(apr_pool_t *pool, id object) {
111 if (object == nil)
112 return nil;
113 else if (pool == NULL)
114 return [object autorelease];
115 else {
116 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
117 return object;
118 }
119}
120
121template <typename Type_>
122Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
123 return (Type_) CYPoolRelease_(pool, (id) object);
124}
125/* }}} */
126/* Objective-C Strings {{{ */
127const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
128 if (pool == NULL)
129 return [value UTF8String];
130 else {
131 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
132 char *string(new(pool) char[size]);
133 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
37954781 134 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
3c1c3635
JF
135 return string;
136 }
137}
138
aabea98c 139JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
3c1c3635
JF
140#ifdef __APPLE__
141 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
142#else
143 CYPool pool;
aabea98c 144 return CYCopyJSString(CYPoolCString(pool, context, value));
3c1c3635
JF
145#endif
146}
147
8665da0c 148JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
3c1c3635
JF
149 if (value == nil)
150 return NULL;
151 // XXX: this definition scares me; is anyone using this?!
152 NSString *string([value description]);
8665da0c 153 return CYCopyJSString(context, string);
3c1c3635
JF
154}
155
156NSString *CYCopyNSString(const CYUTF8String &value) {
157#ifdef __APPLE__
158 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
159#else
160 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
161#endif
162}
163
aabea98c 164NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
3c1c3635
JF
165#ifdef __APPLE__
166 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
167#else
aabea98c
JF
168 CYPool pool;
169 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
3c1c3635
JF
170#endif
171}
172
173NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
aabea98c 174 return CYCopyNSString(context, CYJSString(context, value));
3c1c3635
JF
175}
176
177NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
178 return CYPoolRelease(pool, CYCopyNSString(value));
179}
180
181NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
182 const char *name(sel_getName(sel));
183 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
184}
185
aabea98c
JF
186NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
187 return CYPoolRelease(pool, CYCopyNSString(context, value));
3c1c3635 188}
c239b9f8 189
3c1c3635
JF
190CYUTF8String CYCastUTF8String(NSString *value) {
191 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
192 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
193}
194/* }}} */
ff783f8c 195
ba4fa42f
JF
196JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
197
3c1c3635
JF
198void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
199 if (exception == NULL)
200 throw error;
201 *exception = CYCastJSValue(context, error);
202}
bce8339b 203
3c1c3635
JF
204size_t CYGetIndex(NSString *value) {
205 return CYGetIndex(CYCastUTF8String(value));
206}
ff783f8c 207
3c1c3635
JF
208bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
209 return CYGetOffset(CYPoolCString(pool, context, value), index);
210}
ff783f8c 211
3c1c3635
JF
212static JSClassRef Instance_;
213static JSClassRef Internal_;
214static JSClassRef Message_;
215static JSClassRef Messages_;
216static JSClassRef Selector_;
217static JSClassRef Super_;
ff783f8c 218
3c1c3635 219static JSClassRef ObjectiveC_Classes_;
aabea98c
JF
220static JSClassRef ObjectiveC_Protocols_;
221
222#ifdef __APPLE__
3c1c3635
JF
223static JSClassRef ObjectiveC_Image_Classes_;
224static JSClassRef ObjectiveC_Images_;
aabea98c 225#endif
ff783f8c 226
3c1c3635
JF
227#ifdef __APPLE__
228static Class NSCFBoolean_;
229static Class NSCFType_;
b5dd57dc
JF
230static Class NSMessageBuilder_;
231static Class NSZombie_;
c074e774
JF
232#else
233static Class NSBoolNumber_;
3c1c3635 234#endif
ff783f8c 235
3c1c3635
JF
236static Class NSArray_;
237static Class NSDictionary_;
3c1c3635 238static Class Object_;
b24eb750 239
3c1c3635
JF
240static Type_privateData *Object_type;
241static Type_privateData *Selector_type;
7b184c00
JF
242
243Type_privateData *Instance::GetType() const {
3c1c3635 244 return Object_type;
7b184c00
JF
245}
246
247Type_privateData *Selector_privateData::GetType() const {
3c1c3635 248 return Selector_type;
7b184c00 249}
ff783f8c 250
3c1c3635
JF
251// XXX: trick this out with associated objects!
252JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
253 if (self == nil)
498c3570 254 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
bd17e6f3 255
3c1c3635
JF
256 // XXX: I need to think through multi-context
257 typedef std::map<id, JSValueRef> CacheMap;
258 static CacheMap cache_;
bd17e6f3 259
3c1c3635
JF
260 JSValueRef &value(cache_[self]);
261 if (value != NULL)
262 return value;
bd17e6f3 263
3c1c3635
JF
264 JSClassRef _class(NULL);
265 JSValueRef prototype;
bd17e6f3 266
3c1c3635 267 if (self == NSArray_)
498c3570 268 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
3c1c3635 269 else if (self == NSDictionary_)
498c3570 270 prototype = CYGetCachedObject(context, CYJSString("Object_prototype"));
3c1c3635
JF
271 else
272 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
bd17e6f3 273
3c1c3635
JF
274 JSObjectRef object(JSObjectMake(context, _class, NULL));
275 JSObjectSetPrototype(context, object, prototype);
bd17e6f3 276
3c1c3635
JF
277 JSValueProtect(context, object);
278 value = object;
279 return object;
bd17e6f3
JF
280}
281
3c1c3635
JF
282JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
283 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
284 if (_class == NSArray_)
285 array = true;
286 if (Class super = class_getSuperclass(_class))
287 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
288 /*else if (array)
289 JSObjectSetPrototype(context, value, Array_prototype_);*/
290 return value;
291}
dc68b74c 292
3c1c3635
JF
293JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
294 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
295}
f33b048a 296
3c1c3635
JF
297namespace cy {
298JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
299 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
300 return value;
301} }
f33b048a 302
3c1c3635
JF
303JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
304 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
305 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
306 return value;
307}
4e39dc0b 308
3c1c3635
JF
309Instance::~Instance() {
310 if ((flags_ & Transient) == 0)
311 // XXX: does this handle background threads correctly?
312 // XXX: this simply does not work on the console because I'm stupid
313 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
314}
f33b048a 315
dc68b74c 316struct Message_privateData :
37954781 317 cy::Functor
dc68b74c
JF
318{
319 SEL sel_;
320
321 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
37954781 322 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
dc68b74c
JF
323 sel_(sel)
324 {
325 }
326};
327
f7c38a29 328JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
2b52f27e
JF
329 Instance::Flags flags;
330
331 if (transient)
332 flags = Instance::Transient;
333 else {
334 flags = Instance::None;
478d4ed0 335 object = [object retain];
2b52f27e
JF
336 }
337
338 return Instance::Make(context, object, flags);
478d4ed0 339}
0c862573 340
107e3ed0 341@interface NSMethodSignature (Cycript)
7ba62cfd
JF
342- (NSString *) _typeString;
343@end
344
107e3ed0 345@interface NSObject (Cycript)
b4aa79af 346
61933e16 347- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
b4aa79af
JF
348- (JSType) cy$JSType;
349
350- (NSObject *) cy$toJSON:(NSString *)key;
351- (NSString *) cy$toCYON;
f33b048a 352- (NSString *) cy$toKey;
b4aa79af 353
7b184c00 354- (bool) cy$hasProperty:(NSString *)name;
cc103044
JF
355- (NSObject *) cy$getProperty:(NSString *)name;
356- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
357- (bool) cy$deleteProperty:(NSString *)name;
8665da0c 358- (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
b4aa79af 359
c1582939
JF
360@end
361
f7c38a29
JF
362@protocol Cycript
363- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
364@end
88c977fa 365
520c130f
JF
366NSString *CYCastNSCYON(id value) {
367 NSString *string;
368
369 if (value == nil)
370 string = @"nil";
371 else {
372 Class _class(object_getClass(value));
373 SEL sel(@selector(cy$toCYON));
374
375 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
376 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
377 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
378 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
379 string = [value cy$toCYON];
380 else goto fail;
381 } else fail: {
b5dd57dc
JF
382 if (false);
383#ifdef __APPLE__
384 else if (value == NSZombie_)
520c130f
JF
385 string = @"_NSZombie_";
386 else if (_class == NSZombie_)
387 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
388 // XXX: frowny /in/ the pants
389 else if (value == NSMessageBuilder_ || value == Object_)
390 string = nil;
b5dd57dc 391#endif
520c130f
JF
392 else
393 string = [NSString stringWithFormat:@"%@", value];
394 }
395
396 // XXX: frowny pants
397 if (string == nil)
398 string = @"undefined";
399 }
400
401 return string;
402}
520c130f 403
cbaa5f0f 404#ifdef __APPLE__
4afefdd9
JF
405struct PropertyAttributes {
406 CYPool pool_;
407
408 const char *name;
409
410 const char *variable;
411
412 const char *getter_;
413 const char *setter_;
414
415 bool readonly;
416 bool copy;
417 bool retain;
418 bool nonatomic;
419 bool dynamic;
420 bool weak;
421 bool garbage;
422
423 PropertyAttributes(objc_property_t property) :
424 variable(NULL),
425 getter_(NULL),
426 setter_(NULL),
427 readonly(false),
428 copy(false),
429 retain(false),
430 nonatomic(false),
431 dynamic(false),
432 weak(false),
433 garbage(false)
434 {
435 name = property_getName(property);
436 const char *attributes(property_getAttributes(property));
437
438 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
439 switch (*token) {
440 case 'R': readonly = true; break;
441 case 'C': copy = true; break;
442 case '&': retain = true; break;
443 case 'N': nonatomic = true; break;
444 case 'G': getter_ = token + 1; break;
445 case 'S': setter_ = token + 1; break;
446 case 'V': variable = token + 1; break;
447 }
448 }
449
450 /*if (variable == NULL) {
451 variable = property_getName(property);
452 size_t size(strlen(variable));
453 char *name(new(pool_) char[size + 2]);
454 name[0] = '_';
455 memcpy(name + 1, variable, size);
456 name[size + 1] = '\0';
457 variable = name;
458 }*/
459 }
460
461 const char *Getter() {
462 if (getter_ == NULL)
463 getter_ = apr_pstrdup(pool_, name);
464 return getter_;
465 }
466
467 const char *Setter() {
468 if (setter_ == NULL && !readonly) {
469 size_t length(strlen(name));
470
471 char *temp(new(pool_) char[length + 5]);
472 temp[0] = 's';
473 temp[1] = 'e';
474 temp[2] = 't';
475
3c1c3635
JF
476 if (length != 0) {
477 temp[3] = toupper(name[0]);
478 memcpy(temp + 4, name + 1, length - 1);
479 }
480
481 temp[length + 3] = ':';
482 temp[length + 4] = '\0';
483 setter_ = temp;
484 }
485
486 return setter_;
487 }
488
489};
490#endif
491
492#ifdef __APPLE__
493NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
494 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
495}
496#endif
497
498#ifndef __APPLE__
499@interface CYWebUndefined : NSObject {
500}
501
502+ (CYWebUndefined *) undefined;
503
504@end
505
506@implementation CYWebUndefined
507
508+ (CYWebUndefined *) undefined {
509 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
510 return instance_;
511}
512
513@end
514
515#define WebUndefined CYWebUndefined
516#endif
517
518/* Bridge: CYJSObject {{{ */
519@interface CYJSObject : NSMutableDictionary {
520 JSObjectRef object_;
521 JSContextRef context_;
522}
523
524- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
525
526- (NSObject *) cy$toJSON:(NSString *)key;
527
528- (NSUInteger) count;
529- (id) objectForKey:(id)key;
530- (NSEnumerator *) keyEnumerator;
531- (void) setObject:(id)object forKey:(id)key;
532- (void) removeObjectForKey:(id)key;
533
534@end
535/* }}} */
536/* Bridge: CYJSArray {{{ */
537@interface CYJSArray : NSMutableArray {
538 JSObjectRef object_;
539 JSContextRef context_;
540}
541
542- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
543
544- (NSUInteger) count;
545- (id) objectAtIndex:(NSUInteger)index;
546
547- (void) addObject:(id)anObject;
548- (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
549- (void) removeLastObject;
550- (void) removeObjectAtIndex:(NSUInteger)index;
551- (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
552
553@end
554/* }}} */
4afefdd9 555
3c1c3635 556NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
498c3570 557 JSObjectRef Array(CYGetCachedObject(context, Array_s));
3c1c3635 558 JSValueRef exception(NULL);
498c3570 559 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
3c1c3635
JF
560 CYThrow(context, exception);
561 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
562 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
563}
4afefdd9 564
3c1c3635
JF
565NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
566 if (!JSValueIsObjectOfClass(context, object, Instance_))
567 return CYCastNSObject_(pool, context, object);
568 else {
569 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
570 return internal->GetValue();
4afefdd9 571 }
3c1c3635 572}
4afefdd9 573
3c1c3635
JF
574NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
575 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
576}
4afefdd9 577
c074e774
JF
578#ifndef __APPLE__
579@interface NSBoolNumber : NSNumber {
580}
581@end
582#endif
583
3c1c3635
JF
584id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
585 id object;
586 bool copy;
587
588 switch (JSType type = JSValueGetType(context, value)) {
589 case kJSTypeUndefined:
590 object = [WebUndefined undefined];
591 copy = false;
592 break;
593
594 case kJSTypeNull:
595 return NULL;
596 break;
597
598 case kJSTypeBoolean:
cbaa5f0f 599#ifdef __APPLE__
3c1c3635
JF
600 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
601 copy = false;
602#else
c074e774 603 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
3c1c3635 604 copy = true;
b24eb750 605#endif
3c1c3635 606 break;
c239b9f8 607
3c1c3635
JF
608 case kJSTypeNumber:
609 object = CYCopyNSNumber(context, value);
610 copy = true;
611 break;
993f82f8 612
3c1c3635
JF
613 case kJSTypeString:
614 object = CYCopyNSString(context, value);
615 copy = true;
616 break;
993f82f8 617
3c1c3635
JF
618 case kJSTypeObject:
619 // XXX: this might could be more efficient
620 object = CYCastNSObject(pool, context, (JSObjectRef) value);
621 copy = false;
622 break;
993f82f8 623
3c1c3635 624 default:
37954781 625 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
3c1c3635
JF
626 break;
627 }
993f82f8 628
3c1c3635
JF
629 if (cast != copy)
630 return object;
631 else if (copy)
632 return CYPoolRelease(pool, object);
633 else
634 return [object retain];
993f82f8
JF
635}
636
3c1c3635
JF
637NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
638 return CYNSObject(pool, context, value, true);
639}
993f82f8 640
3c1c3635
JF
641NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
642 return CYNSObject(pool, context, value, false);
643}
993f82f8 644
365abb0a 645/* Bridge: NSArray {{{ */
107e3ed0 646@implementation NSArray (Cycript)
62ca2b82 647
b4aa79af 648- (NSString *) cy$toCYON {
c1582939
JF
649 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
650 [json appendString:@"["];
651
652 bool comma(false);
cbaa5f0f 653#ifdef __APPLE__
62ca2b82 654 for (id object in self) {
cbaa5f0f 655#else
cbaa5f0f 656 for (size_t index(0), count([self count]); index != count; ++index) {
af4272e6 657 id object([self objectAtIndex:index]);
cbaa5f0f 658#endif
c1582939
JF
659 if (comma)
660 [json appendString:@","];
661 else
662 comma = true;
7b184c00 663 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
520c130f 664 [json appendString:CYCastNSCYON(object)];
6b8a9500
JF
665 else {
666 [json appendString:@","];
667 comma = false;
668 }
c1582939
JF
669 }
670
671 [json appendString:@"]"];
672 return json;
62ca2b82
JF
673}
674
7b184c00
JF
675- (bool) cy$hasProperty:(NSString *)name {
676 if ([name isEqualToString:@"length"])
677 return true;
678
520c130f 679 size_t index(CYGetIndex(name));
faf69207 680 if (index == _not(size_t) || index >= [self count])
7b184c00
JF
681 return [super cy$hasProperty:name];
682 else
683 return true;
684}
685
cc103044 686- (NSObject *) cy$getProperty:(NSString *)name {
cbaa5f0f
JF
687 if ([name isEqualToString:@"length"]) {
688 NSUInteger count([self count]);
689#ifdef __APPLE__
690 return [NSNumber numberWithUnsignedInteger:count];
691#else
692 return [NSNumber numberWithUnsignedInt:count];
693#endif
694 }
4afefdd9 695
520c130f 696 size_t index(CYGetIndex(name));
faf69207 697 if (index == _not(size_t) || index >= [self count])
cc103044
JF
698 return [super cy$getProperty:name];
699 else
700 return [self objectAtIndex:index];
701}
702
8665da0c
JF
703- (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
704 [super cy$getPropertyNames:names inContext:context];
d3760804
JF
705
706 for (size_t index(0), count([self count]); index != count; ++index) {
707 id object([self objectAtIndex:index]);
708 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
709 char name[32];
710 sprintf(name, "%zu", index);
711 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
712 }
713 }
714}
715
cc103044 716@end
365abb0a 717/* }}} */
c074e774
JF
718/* Bridge: NSBoolNumber {{{ */
719#ifndef __APPLE__
720@implementation NSBoolNumber (Cycript)
721
722- (JSType) cy$JSType {
723 return kJSTypeBoolean;
724}
725
726- (NSObject *) cy$toJSON:(NSString *)key {
727 return self;
728}
729
730- (NSString *) cy$toCYON {
731 return [self boolValue] ? @"true" : @"false";
732}
733
734- (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
735 return CYCastJSValue(context, (bool) [self boolValue]);
736} CYObjectiveCatch }
737
738@end
739#endif
740/* }}} */
365abb0a
JF
741/* Bridge: NSDictionary {{{ */
742@implementation NSDictionary (Cycript)
743
744- (NSString *) cy$toCYON {
745 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
746 [json appendString:@"{"];
747
748 bool comma(false);
cbaa5f0f 749#ifdef __APPLE__
0226d428 750 for (NSObject *key in self) {
cbaa5f0f
JF
751#else
752 NSEnumerator *keys([self keyEnumerator]);
0226d428 753 while (NSObject *key = [keys nextObject]) {
cbaa5f0f 754#endif
365abb0a
JF
755 if (comma)
756 [json appendString:@","];
757 else
758 comma = true;
759 [json appendString:[key cy$toKey]];
760 [json appendString:@":"];
761 NSObject *object([self objectForKey:key]);
520c130f 762 [json appendString:CYCastNSCYON(object)];
365abb0a 763 }
cc103044 764
365abb0a
JF
765 [json appendString:@"}"];
766 return json;
767}
768
769- (bool) cy$hasProperty:(NSString *)name {
770 return [self objectForKey:name] != nil;
771}
772
773- (NSObject *) cy$getProperty:(NSString *)name {
774 return [self objectForKey:name];
775}
776
8665da0c
JF
777- (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
778 [super cy$getPropertyNames:names inContext:context];
d3760804
JF
779
780#ifdef __APPLE__
0226d428 781 for (NSObject *key in self) {
d3760804
JF
782#else
783 NSEnumerator *keys([self keyEnumerator]);
0226d428 784 while (NSObject *key = [keys nextObject]) {
d3760804 785#endif
8665da0c 786 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
d3760804
JF
787 }
788}
789
365abb0a
JF
790@end
791/* }}} */
792/* Bridge: NSMutableArray {{{ */
cc103044
JF
793@implementation NSMutableArray (Cycript)
794
795- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
faf69207
JF
796 if ([name isEqualToString:@"length"]) {
797 // XXX: is this not intelligent?
cbaa5f0f
JF
798 NSNumber *number(reinterpret_cast<NSNumber *>(value));
799#ifdef __APPLE__
800 NSUInteger size([number unsignedIntegerValue]);
801#else
802 NSUInteger size([number unsignedIntValue]);
803#endif
faf69207
JF
804 NSUInteger count([self count]);
805 if (size < count)
806 [self removeObjectsInRange:NSMakeRange(size, count - size)];
807 else if (size != count) {
808 WebUndefined *undefined([WebUndefined undefined]);
809 for (size_t i(count); i != size; ++i)
810 [self addObject:undefined];
811 }
812 return true;
813 }
814
520c130f 815 size_t index(CYGetIndex(name));
faf69207 816 if (index == _not(size_t))
cc103044 817 return [super cy$setProperty:name to:value];
faf69207
JF
818
819 id object(value ?: [NSNull null]);
820
821 size_t count([self count]);
822 if (index < count)
823 [self replaceObjectAtIndex:index withObject:object];
cc103044 824 else {
faf69207
JF
825 if (index != count) {
826 WebUndefined *undefined([WebUndefined undefined]);
827 for (size_t i(count); i != index; ++i)
828 [self addObject:undefined];
829 }
830
831 [self addObject:object];
cc103044 832 }
faf69207 833
365abb0a 834 return true;
7b184c00
JF
835}
836
365abb0a 837- (bool) cy$deleteProperty:(NSString *)name {
520c130f 838 size_t index(CYGetIndex(name));
365abb0a
JF
839 if (index == _not(size_t) || index >= [self count])
840 return [super cy$deleteProperty:name];
841 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
842 return true;
cc103044
JF
843}
844
845@end
365abb0a
JF
846/* }}} */
847/* Bridge: NSMutableDictionary {{{ */
cc103044
JF
848@implementation NSMutableDictionary (Cycript)
849
850- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
b6ea08b6 851 [self setObject:(value ?: [NSNull null]) forKey:name];
cc103044
JF
852 return true;
853}
854
855- (bool) cy$deleteProperty:(NSString *)name {
856 if ([self objectForKey:name] == nil)
857 return false;
858 else {
859 [self removeObjectForKey:name];
860 return true;
861 }
862}
863
62ca2b82 864@end
365abb0a
JF
865/* }}} */
866/* Bridge: NSNumber {{{ */
107e3ed0 867@implementation NSNumber (Cycript)
62ca2b82 868
b4aa79af 869- (JSType) cy$JSType {
b53b30c1 870#ifdef __APPLE__
b4aa79af 871 // XXX: this just seems stupid
b53b30c1
JF
872 if ([self class] == NSCFBoolean_)
873 return kJSTypeBoolean;
874#endif
875 return kJSTypeNumber;
b4aa79af
JF
876}
877
878- (NSObject *) cy$toJSON:(NSString *)key {
879 return self;
880}
881
882- (NSString *) cy$toCYON {
883 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
62ca2b82
JF
884}
885
37954781 886- (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
b4aa79af 887 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
3c1c3635 888} CYObjectiveCatch }
62ca2b82
JF
889
890@end
365abb0a
JF
891/* }}} */
892/* Bridge: NSNull {{{ */
893@implementation NSNull (Cycript)
894
895- (JSType) cy$JSType {
896 return kJSTypeNull;
897}
898
899- (NSObject *) cy$toJSON:(NSString *)key {
900 return self;
901}
902
903- (NSString *) cy$toCYON {
904 return @"null";
905}
906
907@end
908/* }}} */
909/* Bridge: NSObject {{{ */
910@implementation NSObject (Cycript)
911
37954781 912- (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
365abb0a 913 return CYMakeInstance(context, self, false);
3c1c3635 914} CYObjectiveCatch }
365abb0a
JF
915
916- (JSType) cy$JSType {
917 return kJSTypeObject;
918}
919
920- (NSObject *) cy$toJSON:(NSString *)key {
921 return [self description];
922}
923
924- (NSString *) cy$toCYON {
925 return [[self cy$toJSON:@""] cy$toCYON];
926}
927
928- (NSString *) cy$toKey {
929 return [self cy$toCYON];
930}
931
932- (bool) cy$hasProperty:(NSString *)name {
933 return false;
934}
935
936- (NSObject *) cy$getProperty:(NSString *)name {
937 return nil;
938}
939
940- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
941 return false;
942}
943
944- (bool) cy$deleteProperty:(NSString *)name {
945 return false;
946}
947
8665da0c 948- (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
d3760804
JF
949}
950
365abb0a
JF
951@end
952/* }}} */
953/* Bridge: NSProxy {{{ */
954@implementation NSProxy (Cycript)
955
956- (NSObject *) cy$toJSON:(NSString *)key {
957 return [self description];
958}
959
960- (NSString *) cy$toCYON {
961 return [[self cy$toJSON:@""] cy$toCYON];
962}
c1582939 963
365abb0a
JF
964@end
965/* }}} */
966/* Bridge: NSString {{{ */
107e3ed0 967@implementation NSString (Cycript)
62ca2b82 968
b4aa79af
JF
969- (JSType) cy$JSType {
970 return kJSTypeString;
971}
972
973- (NSObject *) cy$toJSON:(NSString *)key {
974 return self;
975}
976
3c1c3635
JF
977- (NSString *) cy$toCYON {
978 std::ostringstream str;
979 CYUTF8String string(CYCastUTF8String(self));
980 CYStringify(str, string.data, string.size);
981 std::string value(str.str());
982 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
983}
b09da87b 984
3c1c3635
JF
985- (NSString *) cy$toKey {
986 if (CYIsKey(CYCastUTF8String(self)))
987 return self;
988 return [self cy$toCYON];
989}
b09da87b 990
3c1c3635
JF
991@end
992/* }}} */
993/* Bridge: WebUndefined {{{ */
994@implementation WebUndefined (Cycript)
b09da87b 995
3c1c3635
JF
996- (JSType) cy$JSType {
997 return kJSTypeUndefined;
b09da87b
JF
998}
999
3c1c3635
JF
1000- (NSObject *) cy$toJSON:(NSString *)key {
1001 return self;
b09da87b 1002}
3c1c3635
JF
1003
1004- (NSString *) cy$toCYON {
1005 return @"undefined";
c1582939
JF
1006}
1007
37954781 1008- (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
3c1c3635
JF
1009 return CYJSUndefined(context);
1010} CYObjectiveCatch }
1011
1012@end
1013/* }}} */
1014
cacd1a88 1015static bool CYIsClass(id self) {
aabea98c 1016#ifdef __APPLE__
cacd1a88
JF
1017 // XXX: this is a lame object_isClass
1018 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
aabea98c
JF
1019#else
1020 return GSObjCIsClass(self);
1021#endif
cacd1a88
JF
1022}
1023
1024Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1025 id self(CYCastNSObject(pool, context, value));
1026 if (CYIsClass(self))
1027 return (Class) self;
37954781 1028 throw CYJSError(context, "got something that is not a Class");
cacd1a88
JF
1029 return NULL;
1030}
1031
aabea98c 1032NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
b09da87b 1033 CYPool pool;
62ca2b82
JF
1034 size_t size(JSPropertyNameArrayGetCount(names));
1035 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1036 for (size_t index(0); index != size; ++index)
aabea98c 1037 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
62ca2b82
JF
1038 return array;
1039}
62ca2b82 1040
ba4fa42f 1041JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
f7c38a29
JF
1042 if (value == nil)
1043 return CYJSNull(context);
1044 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1045 return [value cy$JSValueInContext:context];
1046 else
1047 return CYMakeInstance(context, value, false);
7c6c5b0a 1048} CYPoolCatch(NULL) return /*XXX*/ NULL; }
af4272e6 1049
b21525c7 1050@implementation CYJSObject
62ca2b82 1051
3c1c3635 1052- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
62ca2b82
JF
1053 if ((self = [super init]) != nil) {
1054 object_ = object;
bc60fb46
JF
1055 context_ = CYGetJSContext(context);
1056 //XXX:JSGlobalContextRetain(context_);
75b0a457 1057 JSValueProtect(context_, object_);
62ca2b82 1058 } return self;
3c1c3635 1059} CYObjectiveCatch }
62ca2b82 1060
3c1c3635 1061- (void) dealloc { CYObjectiveTry {
75b0a457 1062 JSValueUnprotect(context_, object_);
bc60fb46 1063 //XXX:JSGlobalContextRelease(context_);
75b0a457 1064 [super dealloc];
3c1c3635 1065} CYObjectiveCatch }
75b0a457 1066
3c1c3635 1067- (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
00b9328f 1068 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
b4aa79af
JF
1069 if (!CYIsCallable(context_, toJSON))
1070 return [super cy$toJSON:key];
1071 else {
1072 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1073 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1074 // XXX: do I really want an NSNull here?!
1075 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1076 }
3c1c3635 1077} CYObjectiveCatch }
b4aa79af 1078
3c1c3635 1079- (NSString *) cy$toCYON { CYObjectiveTry {
af4272e6
JF
1080 CYPool pool;
1081 JSValueRef exception(NULL);
1082 const char *cyon(CYPoolCCYON(pool, context_, object_));
1083 CYThrow(context_, exception);
8aa3e970
JF
1084 if (cyon == NULL)
1085 return [super cy$toCYON];
1086 else
1087 return [NSString stringWithUTF8String:cyon];
3c1c3635 1088} CYObjectiveCatch }
b4aa79af 1089
3c1c3635 1090- (NSUInteger) count { CYObjectiveTry {
62ca2b82
JF
1091 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1092 size_t size(JSPropertyNameArrayGetCount(names));
1093 JSPropertyNameArrayRelease(names);
1094 return size;
3c1c3635 1095} CYObjectiveCatch }
62ca2b82 1096
3c1c3635 1097- (id) objectForKey:(id)key { CYObjectiveTry {
0226d428 1098 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
d0a00196
JF
1099 if (JSValueIsUndefined(context_, value))
1100 return nil;
1101 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
3c1c3635 1102} CYObjectiveCatch }
62ca2b82 1103
3c1c3635 1104- (NSEnumerator *) keyEnumerator { CYObjectiveTry {
62ca2b82 1105 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
ec599edf 1106 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
62ca2b82
JF
1107 JSPropertyNameArrayRelease(names);
1108 return enumerator;
3c1c3635 1109} CYObjectiveCatch }
62ca2b82 1110
3c1c3635 1111- (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
0226d428 1112 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
3c1c3635 1113} CYObjectiveCatch }
62ca2b82 1114
3c1c3635 1115- (void) removeObjectForKey:(id)key { CYObjectiveTry {
62ca2b82 1116 JSValueRef exception(NULL);
0226d428 1117 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
62ca2b82 1118 CYThrow(context_, exception);
3c1c3635 1119} CYObjectiveCatch }
62ca2b82
JF
1120
1121@end
1122
b21525c7 1123@implementation CYJSArray
c1582939 1124
3c1c3635 1125- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
c1582939
JF
1126 if ((self = [super init]) != nil) {
1127 object_ = object;
bc60fb46
JF
1128 context_ = CYGetJSContext(context);
1129 //XXX:JSGlobalContextRetain(context_);
75b0a457 1130 JSValueProtect(context_, object_);
c1582939 1131 } return self;
3c1c3635 1132} CYObjectiveCatch }
c1582939 1133
3c1c3635 1134- (void) dealloc { CYObjectiveTry {
75b0a457 1135 JSValueUnprotect(context_, object_);
bc60fb46 1136 //XXX:JSGlobalContextRelease(context_);
75b0a457 1137 [super dealloc];
3c1c3635 1138} CYObjectiveCatch }
75b0a457 1139
3c1c3635 1140- (NSUInteger) count { CYObjectiveTry {
00b9328f 1141 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
3c1c3635 1142} CYObjectiveCatch }
c1582939 1143
3c1c3635 1144- (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
9a2db8b2
JF
1145 size_t bounds([self count]);
1146 if (index >= bounds)
1147 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
62ca2b82
JF
1148 JSValueRef exception(NULL);
1149 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1150 CYThrow(context_, exception);
478d4ed0 1151 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
3c1c3635 1152} CYObjectiveCatch }
c1582939 1153
3c1c3635 1154- (void) addObject:(id)object { CYObjectiveTry {
faf69207
JF
1155 JSValueRef exception(NULL);
1156 JSValueRef arguments[1];
ba4fa42f 1157 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
498c3570
JF
1158 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1159 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
faf69207 1160 CYThrow(context_, exception);
3c1c3635 1161} CYObjectiveCatch }
faf69207 1162
3c1c3635 1163- (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
9a2db8b2
JF
1164 size_t bounds([self count] + 1);
1165 if (index >= bounds)
1166 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
faf69207
JF
1167 JSValueRef exception(NULL);
1168 JSValueRef arguments[3];
1169 arguments[0] = CYCastJSValue(context_, index);
1170 arguments[1] = CYCastJSValue(context_, 0);
ba4fa42f 1171 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
498c3570
JF
1172 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1173 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
3c1c3635
JF
1174 CYThrow(context_, exception);
1175} CYObjectiveCatch }
af4272e6 1176
3c1c3635
JF
1177- (void) removeLastObject { CYObjectiveTry {
1178 JSValueRef exception(NULL);
498c3570
JF
1179 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1180 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
3c1c3635
JF
1181 CYThrow(context_, exception);
1182} CYObjectiveCatch }
af4272e6 1183
3c1c3635
JF
1184- (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1185 size_t bounds([self count]);
1186 if (index >= bounds)
1187 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1188 JSValueRef exception(NULL);
1189 JSValueRef arguments[2];
1190 arguments[0] = CYCastJSValue(context_, index);
1191 arguments[1] = CYCastJSValue(context_, 1);
498c3570
JF
1192 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1193 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
3c1c3635
JF
1194 CYThrow(context_, exception);
1195} CYObjectiveCatch }
1196
1197- (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1198 size_t bounds([self count]);
1199 if (index >= bounds)
1200 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
ba4fa42f 1201 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
3c1c3635
JF
1202} CYObjectiveCatch }
1203
1204@end
af4272e6 1205
18401062 1206// XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
61933e16
JF
1207struct CYInternal :
1208 CYData
1209{
1210 JSObjectRef object_;
1211
1212 CYInternal() :
1213 object_(NULL)
1214 {
1215 }
1216
1217 ~CYInternal() {
1218 // XXX: delete object_? ;(
1219 }
1220
1221 static CYInternal *Get(id self) {
1222 CYInternal *internal(NULL);
1223 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1224 // XXX: do something epic? ;P
1225 }
1226
1227 return internal;
1228 }
1229
1230 static CYInternal *Set(id self) {
1231 CYInternal *internal(NULL);
aabea98c 1232 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
61933e16
JF
1233 if (internal == NULL) {
1234 internal = new CYInternal();
1235 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1236 }
1237 } else {
1238 // XXX: do something epic? ;P
1239 }
1240
1241 return internal;
1242 }
1243
7b184c00
JF
1244 bool HasProperty(JSContextRef context, JSStringRef name) {
1245 if (object_ == NULL)
1246 return false;
1247 return JSObjectHasProperty(context, object_, name);
1248 }
1249
61933e16
JF
1250 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1251 if (object_ == NULL)
1252 return NULL;
1253 return CYGetProperty(context, object_, name);
1254 }
1255
1256 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1257 if (object_ == NULL)
1258 object_ = JSObjectMake(context, NULL, NULL);
1259 CYSetProperty(context, object_, name, value);
1260 }
1261};
1262
534fb6da 1263static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
9e562cfc
JF
1264 Selector_privateData *internal(new Selector_privateData(sel));
1265 return JSObjectMake(context, Selector_, internal);
dea834b0 1266}
b09da87b 1267
534fb6da 1268static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
4afefdd9 1269 if (JSValueIsObjectOfClass(context, value, Selector_)) {
9e562cfc
JF
1270 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1271 return reinterpret_cast<SEL>(internal->value_);
4afefdd9
JF
1272 } else
1273 return CYCastPointer<SEL>(context, value);
1274}
1275
d3760804
JF
1276void *CYObjectiveC_ExecuteStart(JSContextRef context) {
1277 // XXX: deal with exceptions!
3c1c3635
JF
1278 return (void *) [[NSAutoreleasePool alloc] init];
1279}
ea2d184c 1280
d3760804
JF
1281void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) {
1282 // XXX: deal with exceptions!
3c1c3635
JF
1283 return [(NSAutoreleasePool *) handle release];
1284}
ea2d184c 1285
f0d43c71 1286JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
3c1c3635
JF
1287 if (name == "nil")
1288 return Instance::Make(context, nil);
1289 if (Class _class = objc_getClass(name.data))
1290 return CYMakeInstance(context, _class, true);
1291 return NULL;
7c6c5b0a 1292} CYPoolCatch(NULL) return /*XXX*/ NULL; }
d3760804 1293
0fe90592 1294static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { @try {
d3760804 1295 ffi_call(cif, function, value, values);
0fe90592
JF
1296} @catch (NSException *error ) {
1297 throw CYJSError(context, CYCastJSValue(context, error));
1298} }
ea2d184c 1299
f0d43c71 1300static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYPoolTry {
3c1c3635 1301 switch (type->primitive) {
ea2d184c
JF
1302 case sig::object_P:
1303 case sig::typename_P:
b09da87b 1304 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
7ba62cfd
JF
1305 break;
1306
ea2d184c 1307 case sig::selector_P:
7ba62cfd
JF
1308 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1309 break;
ea2d184c 1310
bd17e6f3 1311 default:
3c1c3635 1312 return false;
ea2d184c 1313 }
ea2d184c 1314
3c1c3635 1315 return true;
7c6c5b0a 1316} CYPoolCatch(false) return /*XXX*/ NULL; }
ea2d184c 1317
f0d43c71 1318static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
ea2d184c 1319 switch (type->primitive) {
3c1c3635 1320 case sig::object_P:
ba4fa42f 1321 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
3c1c3635 1322 JSValueRef value(CYCastJSValue(context, object));
2b52f27e
JF
1323 if (initialize)
1324 [object release];
3c1c3635 1325 return value;
2b52f27e 1326 } else goto null;
dea834b0 1327
b09da87b 1328 case sig::typename_P:
3c1c3635 1329 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
b09da87b 1330
dea834b0
JF
1331 case sig::selector_P:
1332 if (SEL sel = *reinterpret_cast<SEL *>(data))
3c1c3635 1333 return CYMakeSelector(context, sel);
f610e1a0 1334 else goto null;
f610e1a0
JF
1335
1336 null:
3c1c3635 1337 return CYJSNull(context);
bd17e6f3 1338 default:
3c1c3635 1339 return NULL;
ea2d184c 1340 }
7c6c5b0a 1341} CYPoolCatch(NULL) return /*XXX*/ NULL; }
ea2d184c 1342
8a199b13 1343static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
39bb4b6a 1344 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
8a199b13
JF
1345 if (!devoid)
1346 return true;
7c6c5b0a 1347#if OBJC_API_VERSION >= 2
8a199b13
JF
1348 char type[16];
1349 method_getReturnType(method, type, sizeof(type));
b5dd57dc
JF
1350#else
1351 const char *type(method_getTypeEncoding(method));
1352#endif
8a199b13
JF
1353 if (type[0] != 'v')
1354 return true;
1355 }
1356
7b184c00 1357 // XXX: possibly use a more "awesome" check?
8a199b13 1358 return false;
7b184c00
JF
1359}
1360
37954781 1361static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
dc68b74c
JF
1362 if (method != NULL)
1363 return method_getTypeEncoding(method);
856b8cd0
JF
1364
1365 const char *name(sel_getName(sel));
1366
1367 sqlite3_stmt *statement;
1368
1369 _sqlcall(sqlite3_prepare(Bridge_,
1370 "select "
856b8cd0
JF
1371 "\"bridge\".\"value\" "
1372 "from \"bridge\" "
1373 "where"
37954781 1374 " \"bridge\".\"mode\" = -1 and"
856b8cd0
JF
1375 " \"bridge\".\"name\" = ?"
1376 " limit 1"
1377 , -1, &statement, NULL));
1378
37954781 1379 _trace();
856b8cd0
JF
1380 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
1381
856b8cd0 1382 const char *value;
856b8cd0 1383 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
37954781
JF
1384 _trace();
1385 value = NULL;}
1386 else {
1387 _trace();
1388 value = sqlite3_column_pooled(pool, statement, 0);
1389 }
dc68b74c 1390
3c1c3635 1391 _sqlcall(sqlite3_finalize(statement));
dc68b74c 1392
3c1c3635
JF
1393 if (value != NULL)
1394 return value;
37954781 1395_trace();
3c1c3635 1396 return NULL;
dc68b74c
JF
1397}
1398
3c1c3635
JF
1399static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1400 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
dc68b74c 1401
3c1c3635 1402 JSContextRef context(internal->context_);
dc68b74c 1403
3c1c3635
JF
1404 size_t count(internal->cif_.nargs);
1405 JSValueRef values[count];
1406
1407 for (size_t index(0); index != count; ++index)
1408 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1409
1410 JSObjectRef _this(CYCastJSObject(context, values[0]));
1411
1412 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1413 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
dc68b74c
JF
1414}
1415
1416static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1417 Message_privateData *internal(new Message_privateData(sel, type, imp));
1418 return JSObjectMake(context, Message_, internal);
1419}
1420
1421static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1422 JSObjectRef function(CYCastJSObject(context, value));
1423 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1424 return reinterpret_cast<IMP>(internal->GetValue());
1425}
1426
365abb0a
JF
1427static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1428 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1429 Class _class(internal->GetValue());
1430
1431 CYPool pool;
3c1c3635 1432 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1433
1434 if (SEL sel = sel_getUid(name))
1435 if (class_getInstanceMethod(_class, sel) != NULL)
1436 return true;
1437
1438 return false;
1439}
1440
365abb0a
JF
1441static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1442 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1443 Class _class(internal->GetValue());
1444
1445 CYPool pool;
3c1c3635 1446 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1447
1448 if (SEL sel = sel_getUid(name))
39bb4b6a 1449 if (objc_method *method = class_getInstanceMethod(_class, sel))
dc68b74c
JF
1450 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1451
1452 return NULL;
1453}
1454
365abb0a
JF
1455static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1456 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1457 Class _class(internal->GetValue());
1458
1459 CYPool pool;
3c1c3635 1460 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1461
1462 SEL sel(sel_registerName(name));
1463
39bb4b6a 1464 objc_method *method(class_getInstanceMethod(_class, sel));
dc68b74c
JF
1465
1466 const char *type;
1467 IMP imp;
1468
1469 if (JSValueIsObjectOfClass(context, value, Message_)) {
1470 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1471 type = sig::Unparse(pool, &message->signature_);
1472 imp = reinterpret_cast<IMP>(message->GetValue());
1473 } else {
37954781 1474 type = CYPoolTypeEncoding(pool, context, sel, method);
dc68b74c
JF
1475 imp = CYMakeMessage(context, value, type);
1476 }
1477
1478 if (method != NULL)
1479 method_setImplementation(method, imp);
b5dd57dc
JF
1480 else {
1481#ifdef GNU_RUNTIME
1482 GSMethodList list(GSAllocMethodList(1));
1483 GSAppendMethodToList(list, sel, type, imp, YES);
1484 GSAddMethodList(_class, list, YES);
1485 GSFlushMethodCacheForClass(_class);
1486#else
1487 class_addMethod(_class, sel, imp, type);
1488#endif
1489 }
dc68b74c
JF
1490
1491 return true;
1492}
1493
7c6c5b0a 1494#if 0 && OBJC_API_VERSION < 2
365abb0a
JF
1495static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1496 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1497 Class _class(internal->GetValue());
1498
1499 CYPool pool;
aabea98c 1500 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1501
1502 if (SEL sel = sel_getUid(name))
39bb4b6a 1503 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
dc68b74c
JF
1504 objc_method_list list = {NULL, 1, {method}};
1505 class_removeMethods(_class, &list);
1506 return true;
1507 }
1508
1509 return false;
1510}
1511#endif
1512
365abb0a
JF
1513static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1514 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1515 Class _class(internal->GetValue());
1516
7c6c5b0a 1517#if OBJC_API_VERSION >= 2
dc68b74c 1518 unsigned int size;
39bb4b6a 1519 objc_method **data(class_copyMethodList(_class, &size));
dc68b74c
JF
1520 for (size_t i(0); i != size; ++i)
1521 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1522 free(data);
aabea98c
JF
1523#else
1524 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1525 for (int i(0); i != methods->method_count; ++i)
1526 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1527#endif
dc68b74c
JF
1528}
1529
7b184c00
JF
1530static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1531 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1532 id self(internal->GetValue());
1533
1534 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1535 return true;
1536
c239b9f8 1537 CYPool pool;
aabea98c 1538 NSString *name(CYCastNSString(pool, context, property));
7b184c00
JF
1539
1540 if (CYInternal *internal = CYInternal::Get(self))
1541 if (internal->HasProperty(context, property))
1542 return true;
1543
365abb0a
JF
1544 Class _class(object_getClass(self));
1545
7b184c00 1546 CYPoolTry {
365abb0a
JF
1547 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1548 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1549 if ([self cy$hasProperty:name])
1550 return true;
7b184c00
JF
1551 } CYPoolCatch(false)
1552
3c1c3635 1553 const char *string(CYPoolCString(pool, context, name));
7b184c00 1554
aabea98c 1555#ifdef __APPLE__
7b184c00
JF
1556 if (class_getProperty(_class, string) != NULL)
1557 return true;
aabea98c 1558#endif
7b184c00
JF
1559
1560 if (SEL sel = sel_getUid(string))
8a199b13 1561 if (CYImplements(self, _class, sel, true))
7b184c00
JF
1562 return true;
1563
1564 return false;
1565}
1566
3c1c3635 1567static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
7b184c00
JF
1568 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1569 id self(internal->GetValue());
1570
1571 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1572 return Internal::Make(context, self, object);
c239b9f8 1573
3c1c3635 1574 CYPool pool;
aabea98c 1575 NSString *name(CYCastNSString(pool, context, property));
c239b9f8 1576
3c1c3635
JF
1577 if (CYInternal *internal = CYInternal::Get(self))
1578 if (JSValueRef value = internal->GetProperty(context, property))
1579 return value;
c239b9f8 1580
3c1c3635
JF
1581 CYPoolTry {
1582 if (NSObject *data = [self cy$getProperty:name])
1583 return CYCastJSValue(context, data);
1584 } CYPoolCatch(NULL)
c239b9f8 1585
3c1c3635
JF
1586 const char *string(CYPoolCString(pool, context, name));
1587 Class _class(object_getClass(self));
c239b9f8 1588
cbaa5f0f 1589#ifdef __APPLE__
3c1c3635
JF
1590 if (objc_property_t property = class_getProperty(_class, string)) {
1591 PropertyAttributes attributes(property);
1592 SEL sel(sel_registerName(attributes.Getter()));
1593 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1594 }
cbaa5f0f 1595#endif
c239b9f8 1596
3c1c3635
JF
1597 if (SEL sel = sel_getUid(string))
1598 if (CYImplements(self, _class, sel, true))
1599 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
8953777c 1600
3c1c3635
JF
1601 return NULL;
1602} CYCatch }
c239b9f8 1603
3c1c3635 1604static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
dc68b74c
JF
1605 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1606 id self(internal->GetValue());
1607
c239b9f8
JF
1608 CYPool pool;
1609
aabea98c 1610 NSString *name(CYCastNSString(pool, context, property));
3c1c3635 1611 NSObject *data(CYCastNSObject(pool, context, value));
8953777c 1612
3c1c3635
JF
1613 CYPoolTry {
1614 if ([self cy$setProperty:name to:data])
c239b9f8 1615 return true;
3c1c3635 1616 } CYPoolCatch(NULL)
dc68b74c 1617
3c1c3635 1618 const char *string(CYPoolCString(pool, context, name));
c239b9f8
JF
1619 Class _class(object_getClass(self));
1620
8aa3e970 1621#ifdef __APPLE__
3c1c3635
JF
1622 if (objc_property_t property = class_getProperty(_class, string)) {
1623 PropertyAttributes attributes(property);
1624 if (const char *setter = attributes.Setter()) {
1625 SEL sel(sel_registerName(setter));
1626 JSValueRef arguments[1] = {value};
1627 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
9b5527f0
JF
1628 return true;
1629 }
3c1c3635 1630 }
b24eb750 1631#endif
c239b9f8 1632
3c1c3635 1633 size_t length(strlen(string));
9e20b0b7 1634
3c1c3635 1635 char set[length + 5];
f33b048a 1636
3c1c3635
JF
1637 set[0] = 's';
1638 set[1] = 'e';
1639 set[2] = 't';
f33b048a 1640
3c1c3635
JF
1641 if (string[0] != '\0') {
1642 set[3] = toupper(string[0]);
1643 memcpy(set + 4, string + 1, length - 1);
e0dc20ec 1644 }
bd17e6f3 1645
3c1c3635
JF
1646 set[length + 3] = ':';
1647 set[length + 4] = '\0';
9b5527f0 1648
3c1c3635
JF
1649 if (SEL sel = sel_getUid(set))
1650 if (CYImplements(self, _class, sel, false)) {
1651 JSValueRef arguments[1] = {value};
1652 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1653 }
f37b3d2b 1654
3c1c3635
JF
1655 if (CYInternal *internal = CYInternal::Set(self)) {
1656 internal->SetProperty(context, property, value);
f37b3d2b 1657 return true;
3c1c3635 1658 }
f37b3d2b 1659
3c1c3635
JF
1660 return false;
1661} CYCatch }
9b5527f0 1662
3c1c3635
JF
1663static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1664 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1665 id self(internal->GetValue());
9b5527f0 1666
3c1c3635 1667 CYPoolTry {
aabea98c 1668 NSString *name(CYCastNSString(NULL, context, property));
3c1c3635
JF
1669 return [self cy$deleteProperty:name];
1670 } CYPoolCatch(NULL)
7c6c5b0a 1671} CYCatch return /*XXX*/ NULL; }
9b5527f0 1672
3c1c3635
JF
1673static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1674 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1675 id self(internal->GetValue());
9b5527f0 1676
3c1c3635
JF
1677 CYPool pool;
1678 Class _class(object_getClass(self));
9b5527f0 1679
3c1c3635
JF
1680#ifdef __APPLE__
1681 {
1682 unsigned int size;
1683 objc_property_t *data(class_copyPropertyList(_class, &size));
1684 for (size_t i(0); i != size; ++i)
1685 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1686 free(data);
1687 }
1688#endif
d3760804
JF
1689
1690 CYPoolTry {
1691 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
8665da0c
JF
1692 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1693 [self cy$getPropertyNames:names inContext:context];
d3760804 1694 } CYPoolCatch()
9b5527f0
JF
1695}
1696
3c1c3635
JF
1697static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1698 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1699 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1700 return value;
1701} CYCatch }
bd17e6f3 1702
3c1c3635
JF
1703static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1704 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1705 Class _class(internal->GetValue());
1706 if (!CYIsClass(_class))
1707 return false;
bd17e6f3 1708
3c1c3635
JF
1709 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1710 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1711 // XXX: this isn't always safe
1712 return [linternal->GetValue() isKindOfClass:_class];
1713 }
ff783f8c 1714
3c1c3635
JF
1715 return false;
1716} CYCatch }
bd17e6f3 1717
3c1c3635
JF
1718static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1719 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
f33b048a 1720 CYPool pool;
bd17e6f3 1721
3c1c3635
JF
1722 id self(internal->GetValue());
1723 const char *name(CYPoolCString(pool, context, property));
520c130f 1724
3c1c3635 1725 if (object_getInstanceVariable(self, name, NULL) != NULL)
bd17e6f3 1726 return true;
3c1c3635
JF
1727
1728 return false;
bd17e6f3
JF
1729}
1730
3c1c3635
JF
1731static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1732 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1733 CYPool pool;
930aa21b 1734
3c1c3635
JF
1735 id self(internal->GetValue());
1736 const char *name(CYPoolCString(pool, context, property));
f33b048a 1737
aabea98c 1738 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
3c1c3635 1739 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
b81e7fb6 1740 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
3c1c3635
JF
1741 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1742 }
f33b048a 1743
3c1c3635
JF
1744 return NULL;
1745} CYCatch }
283e7e33 1746
3c1c3635
JF
1747static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1748 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1749 CYPool pool;
283e7e33 1750
3c1c3635
JF
1751 id self(internal->GetValue());
1752 const char *name(CYPoolCString(pool, context, property));
283e7e33 1753
aabea98c 1754 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
3c1c3635
JF
1755 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1756 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1757 return true;
283e7e33 1758 }
f33b048a 1759
3c1c3635
JF
1760 return false;
1761} CYCatch }
85a33bf5 1762
3c1c3635
JF
1763static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1764 if (Class super = class_getSuperclass(_class))
1765 Internal_getPropertyNames_(super, names);
ea2d184c 1766
7c6c5b0a 1767#if OBJC_API_VERSION >= 2
3c1c3635 1768 unsigned int size;
aabea98c 1769 objc_ivar **data(class_copyIvarList(_class, &size));
3c1c3635
JF
1770 for (size_t i(0); i != size; ++i)
1771 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1772 free(data);
b5dd57dc
JF
1773#else
1774 if (objc_ivar_list *ivars = _class->ivars)
1775 for (int i(0); i != ivars->ivar_count; ++i)
1776 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1777#endif
3c1c3635
JF
1778}
1779
1780static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1781 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1782 CYPool pool;
ea2d184c 1783
3c1c3635
JF
1784 id self(internal->GetValue());
1785 Class _class(object_getClass(self));
7ba62cfd 1786
3c1c3635 1787 Internal_getPropertyNames_(_class, names);
7ba62cfd 1788}
ea2d184c 1789
3c1c3635
JF
1790static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1791 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1792 return internal->GetOwner();
c239b9f8
JF
1793}
1794
3c1c3635
JF
1795static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1796 CYPool pool;
aabea98c 1797 NSString *name(CYCastNSString(pool, context, property));
3c1c3635
JF
1798 if (Class _class = NSClassFromString(name))
1799 return CYMakeInstance(context, _class, true);
1800 return NULL;
1801} CYCatch }
1802
c239b9f8 1803static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
aabea98c 1804#ifdef __APPLE__
c239b9f8
JF
1805 size_t size(objc_getClassList(NULL, 0));
1806 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1807
1808 get:
1809 size_t writ(objc_getClassList(data, size));
1810 if (size < writ) {
1811 size = writ;
1812 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1813 data = copy;
1814 goto get;
1815 } else goto done;
1816 }
1817
1818 for (size_t i(0); i != writ; ++i)
1819 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1820
1821 done:
1822 free(data);
aabea98c
JF
1823#else
1824 void *state(NULL);
1825 while (Class _class = objc_next_class(&state))
1826 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1827#endif
c239b9f8
JF
1828}
1829
7c6c5b0a 1830#if OBJC_API_VERSION >= 2
3c1c3635 1831static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
c239b9f8
JF
1832 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1833
3c1c3635
JF
1834 CYPool pool;
1835 const char *name(CYPoolCString(pool, context, property));
1836 unsigned int size;
1837 const char **data(objc_copyClassNamesForImage(internal, &size));
1838 JSValueRef value;
1839 for (size_t i(0); i != size; ++i)
1840 if (strcmp(name, data[i]) == 0) {
1841 if (Class _class = objc_getClass(name)) {
1842 value = CYMakeInstance(context, _class, true);
1843 goto free;
1844 } else
1845 break;
1846 }
1847 value = NULL;
1848 free:
1849 free(data);
1850 return value;
1851} CYCatch }
c239b9f8
JF
1852
1853static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1854 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1855 unsigned int size;
1856 const char **data(objc_copyClassNamesForImage(internal, &size));
1857 for (size_t i(0); i != size; ++i)
1858 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1859 free(data);
1860}
1861
3c1c3635
JF
1862static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1863 CYPool pool;
1864 const char *name(CYPoolCString(pool, context, property));
1865 unsigned int size;
1866 const char **data(objc_copyImageNames(&size));
1867 for (size_t i(0); i != size; ++i)
1868 if (strcmp(name, data[i]) == 0) {
1869 name = data[i];
1870 goto free;
1871 }
1872 name = NULL;
1873 free:
1874 free(data);
1875 if (name == NULL)
1876 return NULL;
1877 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1878 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1879 return value;
1880} CYCatch }
c239b9f8
JF
1881
1882static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1883 unsigned int size;
1884 const char **data(objc_copyImageNames(&size));
1885 for (size_t i(0); i != size; ++i)
1886 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1887 free(data);
1888}
aabea98c 1889#endif
c239b9f8 1890
3c1c3635
JF
1891static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1892 CYPool pool;
aabea98c
JF
1893 const char *name(CYPoolCString(pool, context, property));
1894 if (Protocol *protocol = objc_getProtocol(name))
3c1c3635
JF
1895 return CYMakeInstance(context, protocol, true);
1896 return NULL;
1897} CYCatch }
c239b9f8
JF
1898
1899static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
7c6c5b0a 1900#if OBJC_API_VERSION >= 2
c239b9f8
JF
1901 unsigned int size;
1902 Protocol **data(objc_copyProtocolList(&size));
1903 for (size_t i(0); i != size; ++i)
1904 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
1905 free(data);
aabea98c
JF
1906#else
1907 // XXX: fix this!
1908#endif
c239b9f8 1909}
707bcb93 1910
aabea98c 1911#ifdef __APPLE__
534fb6da 1912static bool stret(ffi_type *ffi_type) {
04450da0
JF
1913 return ffi_type->type == FFI_TYPE_STRUCT && (
1914 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1915 struct_forward_array[ffi_type->size] != 0
1916 );
1917}
aabea98c 1918#endif
b09da87b 1919
3c1c3635 1920JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) { CYTry {
7ba62cfd 1921 const char *type;
ea2d184c 1922
cacd1a88
JF
1923 if (_class == NULL)
1924 _class = object_getClass(self);
1925
aabea98c
JF
1926 IMP imp;
1927
1928 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
1929 imp = method_getImplementation(method);
4afefdd9 1930 type = method_getTypeEncoding(method);
aabea98c
JF
1931 } else {
1932 imp = NULL;
1933
3c1c3635
JF
1934 CYPoolTry {
1935 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1936 if (method == nil)
37954781 1937 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3c1c3635
JF
1938 type = CYPoolCString(pool, context, [method _typeString]);
1939 } CYPoolCatch(NULL)
4afefdd9
JF
1940 }
1941
1942 void *setup[2];
f623c5d8 1943 setup[0] = &self;
4afefdd9
JF
1944 setup[1] = &_cmd;
1945
1946 sig::Signature signature;
f33b048a 1947 sig::Parse(pool, &signature, type, &Structor_);
4afefdd9
JF
1948
1949 ffi_cif cif;
1950 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1951
f623c5d8 1952 if (imp == NULL) {
aabea98c
JF
1953#ifdef __APPLE__
1954 if (stret(cif.rtype))
1955 imp = class_getMethodImplementation_stret(_class, _cmd);
1956 else
1957 imp = class_getMethodImplementation(_class, _cmd);
1958#else
f623c5d8 1959 objc_super super = {self, _class};
aabea98c
JF
1960 imp = objc_msg_lookup_super(&super, _cmd);
1961#endif
f623c5d8 1962 }
aabea98c
JF
1963
1964 void (*function)() = reinterpret_cast<void (*)()>(imp);
2b52f27e 1965 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3c1c3635 1966} CYCatch }
367eebb1 1967
3c1c3635
JF
1968static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1969 if (count < 2)
37954781 1970 throw CYJSError(context, "too few arguments to objc_msgSend");
367eebb1 1971
478d4ed0
JF
1972 CYPool pool;
1973
2b52f27e
JF
1974 bool uninitialized;
1975
4afefdd9
JF
1976 id self;
1977 SEL _cmd;
cacd1a88 1978 Class _class;
4afefdd9 1979
3c1c3635
JF
1980 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
1981 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
1982 self = internal->GetValue();
1983 _class = internal->class_;;
1984 uninitialized = false;
1985 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
1986 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
1987 self = internal->GetValue();
1988 _class = nil;
1989 uninitialized = internal->IsUninitialized();
1990 if (uninitialized)
1991 internal->value_ = nil;
1992 } else {
1993 self = CYCastNSObject(pool, context, arguments[0]);
1994 _class = nil;
1995 uninitialized = false;
1996 }
2b52f27e 1997
3c1c3635
JF
1998 if (self == nil)
1999 return CYJSNull(context);
7ba62cfd 2000
3c1c3635 2001 _cmd = CYCastSEL(context, arguments[1]);
ea2d184c 2002
cacd1a88 2003 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
3c1c3635 2004} CYCatch }
7ba62cfd 2005
365abb0a 2006/* Hook: objc_registerClassPair {{{ */
7c6c5b0a 2007#if defined(__APPLE__) && defined(__arm__)
365abb0a
JF
2008// XXX: replace this with associated objects
2009
272c3da3 2010MSHook(void, CYDealloc, id self, SEL sel) {
61933e16
JF
2011 CYInternal *internal;
2012 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2013 if (internal != NULL)
2014 delete internal;
272c3da3 2015 _CYDealloc(self, sel);
61933e16 2016}
f7c38a29 2017
61933e16
JF
2018MSHook(void, objc_registerClassPair, Class _class) {
2019 Class super(class_getSuperclass(_class));
2020 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2021 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
272c3da3 2022 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
f7c38a29
JF
2023 }
2024
61933e16 2025 _objc_registerClassPair(_class);
f7c38a29
JF
2026}
2027
3c1c3635
JF
2028static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2029 if (count != 1)
37954781 2030 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
3c1c3635
JF
2031 CYPool pool;
2032 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2033 if (value == NULL || !CYIsClass(value))
37954781 2034 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
3c1c3635
JF
2035 Class _class((Class) value);
2036 $objc_registerClassPair(_class);
d447cc5e 2037 return CYJSUndefined(context);
3c1c3635 2038} CYCatch }
b5dd57dc 2039#endif
3c1c3635 2040/* }}} */
d447cc5e 2041
dea834b0
JF
2042static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2043 JSValueRef setup[count + 2];
2044 setup[0] = _this;
2045 setup[1] = object;
4afefdd9 2046 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
dea834b0
JF
2047 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2048}
2049
dc68b74c
JF
2050static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2051 CYPool pool;
2052 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2053
2054 // XXX: handle Instance::Uninitialized?
2055 id self(CYCastNSObject(pool, context, _this));
2056
2057 void *setup[2];
2058 setup[0] = &self;
2059 setup[1] = &internal->sel_;
2060
2061 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2062}
2063
3c1c3635
JF
2064static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2065 if (count != 2)
37954781 2066 throw CYJSError(context, "incorrect number of arguments to Super constructor");
4afefdd9 2067 CYPool pool;
3c1c3635
JF
2068 id self(CYCastNSObject(pool, context, arguments[0]));
2069 Class _class(CYCastClass(pool, context, arguments[1]));
2070 return cy::Super::Make(context, self, _class);
2071} CYCatch }
bce8339b 2072
3c1c3635
JF
2073static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2074 if (count != 1)
37954781
JF
2075 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2076 CYPool pool;
2077 const char *name(CYPoolCString(pool, context, arguments[0]));
3c1c3635
JF
2078 return CYMakeSelector(context, sel_registerName(name));
2079} CYCatch }
7b184c00 2080
3c1c3635
JF
2081static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2082 if (count > 1)
37954781 2083 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
3c1c3635
JF
2084 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2085 return Instance::Make(context, self);
2086} CYCatch }
ea2d184c 2087
534fb6da 2088static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
61933e16
JF
2089 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2090 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
04450da0
JF
2091}
2092
7b184c00
JF
2093static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2094 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2095 Type_privateData *typical(internal->GetType());
2096
2097 sig::Type *type;
2098 ffi_type *ffi;
2099
2100 if (typical == NULL) {
2101 type = NULL;
2102 ffi = NULL;
2103 } else {
2104 type = typical->type_;
2105 ffi = typical->ffi_;
2106 }
2107
53ba31e9 2108 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
7b184c00 2109}
4afefdd9 2110
dc68b74c
JF
2111static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2112 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
ec599edf 2113 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
dc68b74c
JF
2114}
2115
3c1c3635 2116static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
365abb0a
JF
2117 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2118 id self(internal->GetValue());
2119 if (!CYIsClass(self))
2120 return CYJSUndefined(context);
3c1c3635
JF
2121 return CYGetClassPrototype(context, self);
2122} CYCatch }
365abb0a
JF
2123
2124static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
dc68b74c
JF
2125 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2126 id self(internal->GetValue());
b5dd57dc 2127 if (!CYIsClass(self))
dc68b74c 2128 return CYJSUndefined(context);
b5dd57dc 2129 return Messages::Make(context, (Class) self);
dc68b74c
JF
2130}
2131
3c1c3635 2132static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
365abb0a
JF
2133 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2134 return NULL;
2135
7b184c00 2136 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
8665da0c 2137 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
3c1c3635 2138} CYCatch }
7b184c00 2139
3c1c3635 2140static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
365abb0a
JF
2141 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2142 return NULL;
2143
7b184c00
JF
2144 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2145
3c1c3635 2146 CYPoolTry {
b5dd57dc
JF
2147 NSString *key;
2148 if (count == 0)
2149 key = nil;
2150 else
2151 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
3c1c3635 2152 // XXX: check for support of cy$toJSON?
8665da0c 2153 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
3c1c3635 2154 } CYPoolCatch(NULL)
7c6c5b0a 2155} CYCatch return /*XXX*/ NULL; }
b4aa79af 2156
3c1c3635 2157static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
365abb0a
JF
2158 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2159 return NULL;
2160
9e562cfc 2161 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
7b184c00 2162
3c1c3635
JF
2163 CYPoolTry {
2164 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
8665da0c 2165 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
3c1c3635 2166 } CYPoolCatch(NULL)
7c6c5b0a 2167} CYCatch return /*XXX*/ NULL; }
478d4ed0 2168
3c1c3635 2169static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
9e562cfc 2170 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3c1c3635
JF
2171 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2172} CYCatch }
478d4ed0 2173
b4aa79af
JF
2174static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2175 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2176}
2177
3c1c3635 2178static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
7b184c00
JF
2179 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2180 const char *name(sel_getName(internal->GetValue()));
2181
3c1c3635 2182 CYPoolTry {
95678376
JF
2183 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2184 return CYCastJSValue(context, CYJSString(context, string));
3c1c3635 2185 } CYPoolCatch(NULL)
7c6c5b0a 2186} CYCatch return /*XXX*/ NULL; }
e5bc40db 2187
3c1c3635
JF
2188static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2189 if (count != 1)
37954781
JF
2190 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2191
3c1c3635
JF
2192 CYPool pool;
2193 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
37954781
JF
2194 SEL sel(internal->GetValue());
2195
2196 objc_method *method;
2197 if (Class _class = CYCastClass(pool, context, arguments[0]))
2198 method = class_getInstanceMethod(_class, sel);
2199 else
2200 method = NULL;
2201
2202 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2203 return CYCastJSValue(context, CYJSString(type));
e5bc40db 2204
3c1c3635
JF
2205 return CYJSNull(context);
2206} CYCatch }
e5bc40db 2207
856b8cd0 2208static JSStaticValue Selector_staticValues[2] = {
61933e16 2209 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
04450da0
JF
2210 {NULL, NULL, NULL, 0}
2211};
953647c1 2212
365abb0a 2213static JSStaticValue Instance_staticValues[5] = {
9e562cfc 2214 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
365abb0a
JF
2215 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2216 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
9e562cfc 2217 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
9b5527f0
JF
2218 {NULL, NULL, NULL, 0}
2219};
2220
7b184c00
JF
2221static JSStaticFunction Instance_staticFunctions[5] = {
2222 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b4aa79af
JF
2223 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2224 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0
JF
2225 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2226 {NULL, NULL, 0}
2227};
2228
9b5527f0
JF
2229static JSStaticFunction Internal_staticFunctions[2] = {
2230 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2231 {NULL, NULL, 0}
2232};
2233
b4aa79af
JF
2234static JSStaticFunction Selector_staticFunctions[5] = {
2235 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2236 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0 2237 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b09da87b
JF
2238 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2239 {NULL, NULL, 0}
2240};
ea2d184c 2241
3c9f7e22 2242void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
37954781
JF
2243 apr_pool_t *pool(CYGetGlobalPool());
2244
807a88be
JF
2245 Object_type = new(pool) Type_privateData("@");
2246 Selector_type = new(pool) Type_privateData(":");
7b184c00 2247
b53b30c1 2248#ifdef __APPLE__
c1582939 2249 NSCFBoolean_ = objc_getClass("NSCFBoolean");
c239b9f8 2250 NSCFType_ = objc_getClass("NSCFType");
b5dd57dc
JF
2251 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2252 NSZombie_ = objc_getClass("_NSZombie_");
c074e774
JF
2253#else
2254 NSBoolNumber_ = objc_getClass("NSBoolNumber");
b53b30c1
JF
2255#endif
2256
2257 NSArray_ = objc_getClass("NSArray");
b5dd57dc 2258 NSDictionary_ = objc_getClass("NSDictionary");
c239b9f8 2259 Object_ = objc_getClass("Object");
3c1c3635
JF
2260
2261 JSClassDefinition definition;
2262
2263 definition = kJSClassDefinitionEmpty;
2264 definition.className = "Instance";
2265 definition.staticValues = Instance_staticValues;
2266 definition.staticFunctions = Instance_staticFunctions;
2267 definition.hasProperty = &Instance_hasProperty;
2268 definition.getProperty = &Instance_getProperty;
2269 definition.setProperty = &Instance_setProperty;
2270 definition.deleteProperty = &Instance_deleteProperty;
2271 definition.getPropertyNames = &Instance_getPropertyNames;
2272 definition.callAsConstructor = &Instance_callAsConstructor;
2273 definition.hasInstance = &Instance_hasInstance;
37954781 2274 definition.finalize = &CYFinalize;
3c1c3635
JF
2275 Instance_ = JSClassCreate(&definition);
2276
2277 definition = kJSClassDefinitionEmpty;
2278 definition.className = "Internal";
2279 definition.staticFunctions = Internal_staticFunctions;
2280 definition.hasProperty = &Internal_hasProperty;
2281 definition.getProperty = &Internal_getProperty;
2282 definition.setProperty = &Internal_setProperty;
2283 definition.getPropertyNames = &Internal_getPropertyNames;
37954781 2284 definition.finalize = &CYFinalize;
3c1c3635
JF
2285 Internal_ = JSClassCreate(&definition);
2286
2287 definition = kJSClassDefinitionEmpty;
2288 definition.className = "Message";
37954781 2289 definition.staticFunctions = cy::Functor::StaticFunctions;
3c1c3635 2290 definition.callAsFunction = &Message_callAsFunction;
37954781 2291 definition.finalize = &CYFinalize;
3c1c3635
JF
2292 Message_ = JSClassCreate(&definition);
2293
2294 definition = kJSClassDefinitionEmpty;
2295 definition.className = "Messages";
2296 definition.hasProperty = &Messages_hasProperty;
2297 definition.getProperty = &Messages_getProperty;
2298 definition.setProperty = &Messages_setProperty;
7c6c5b0a 2299#if 0 && OBJC_API_VERSION < 2
3c1c3635
JF
2300 definition.deleteProperty = &Messages_deleteProperty;
2301#endif
2302 definition.getPropertyNames = &Messages_getPropertyNames;
37954781 2303 definition.finalize = &CYFinalize;
3c1c3635
JF
2304 Messages_ = JSClassCreate(&definition);
2305
2306 definition = kJSClassDefinitionEmpty;
2307 definition.className = "Selector";
2308 definition.staticValues = Selector_staticValues;
2309 definition.staticFunctions = Selector_staticFunctions;
2310 definition.callAsFunction = &Selector_callAsFunction;
37954781 2311 definition.finalize = &CYFinalize;
3c1c3635
JF
2312 Selector_ = JSClassCreate(&definition);
2313
2314 definition = kJSClassDefinitionEmpty;
2315 definition.className = "Super";
2316 definition.staticFunctions = Internal_staticFunctions;
37954781 2317 definition.finalize = &CYFinalize;
3c1c3635
JF
2318 Super_ = JSClassCreate(&definition);
2319
2320 definition = kJSClassDefinitionEmpty;
2321 definition.className = "ObjectiveC::Classes";
2322 definition.getProperty = &ObjectiveC_Classes_getProperty;
2323 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2324 ObjectiveC_Classes_ = JSClassCreate(&definition);
2325
7c6c5b0a 2326#if OBJC_API_VERSION >= 2
3c1c3635
JF
2327 definition = kJSClassDefinitionEmpty;
2328 definition.className = "ObjectiveC::Images";
2329 definition.getProperty = &ObjectiveC_Images_getProperty;
2330 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2331 ObjectiveC_Images_ = JSClassCreate(&definition);
2332
2333 definition = kJSClassDefinitionEmpty;
2334 definition.className = "ObjectiveC::Image::Classes";
2335 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2336 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2337 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3c9f7e22 2338#endif
3c1c3635 2339
3c9f7e22
JF
2340 definition = kJSClassDefinitionEmpty;
2341 definition.className = "ObjectiveC::Protocols";
2342 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2343 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2344 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2345
2346#if defined(__APPLE__) && defined(__arm__)
2347 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2348#endif
2349
2350#ifdef __APPLE__
2351 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2352#endif
2353} CYPoolCatch() }
2354
2355void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2356 JSObjectRef global(CYGetGlobalObject(context));
498c3570 2357 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
3c9f7e22
JF
2358
2359 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2360 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC);
2361
2362 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2363 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2364
2365#if OBJC_API_VERSION >= 2
3c1c3635 2366 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
aabea98c 2367#endif
3c1c3635
JF
2368
2369 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2370 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2371 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2372 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2373
498c3570
JF
2374 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2375 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3c1c3635
JF
2376
2377 CYSetProperty(context, global, CYJSString("Instance"), Instance);
2378 CYSetProperty(context, global, CYJSString("Selector"), Selector);
2379 CYSetProperty(context, global, CYJSString("Super"), Super);
2380
7c6c5b0a 2381#if defined(__APPLE__) && defined(__arm__)
3c1c3635 2382 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
b5dd57dc
JF
2383#endif
2384
3c1c3635
JF
2385 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2386
498c3570
JF
2387 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2388 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2389 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3c9f7e22 2390} CYPoolCatch() }
b5dd57dc
JF
2391
2392static CYHooks CYObjectiveCHooks = {
2393 &CYObjectiveC_ExecuteStart,
2394 &CYObjectiveC_ExecuteEnd,
2395 &CYObjectiveC_RuntimeProperty,
2396 &CYObjectiveC_CallFunction,
3c9f7e22 2397 &CYObjectiveC_Initialize,
b5dd57dc
JF
2398 &CYObjectiveC_SetupContext,
2399 &CYObjectiveC_PoolFFI,
2400 &CYObjectiveC_FromFFI,
2401};
2402
2403struct CYObjectiveC {
2404 CYObjectiveC() {
2405 hooks_ = &CYObjectiveCHooks;
2406 }
2407} CYObjectiveC;