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