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