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