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