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