]> git.saurik.com Git - cycript.git/blame - ObjectiveC/Library.mm
Reorganize typed identifier storage for other uses.
[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
3c1c3635
JF
1488static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1489 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
dc68b74c 1490
3c1c3635 1491 JSContextRef context(internal->context_);
dc68b74c 1492
3c1c3635
JF
1493 size_t count(internal->cif_.nargs);
1494 JSValueRef values[count];
1495
1496 for (size_t index(0); index != count; ++index)
1497 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1498
1499 JSObjectRef _this(CYCastJSObject(context, values[0]));
1500
1501 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1502 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
dc68b74c
JF
1503}
1504
1505static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1506 Message_privateData *internal(new Message_privateData(sel, type, imp));
1507 return JSObjectMake(context, Message_, internal);
1508}
1509
1510static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1511 JSObjectRef function(CYCastJSObject(context, value));
1512 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2fd4c9a9 1513 // XXX: see notes in Library.cpp about needing to leak
dc68b74c
JF
1514 return reinterpret_cast<IMP>(internal->GetValue());
1515}
1516
365abb0a
JF
1517static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1518 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1519 Class _class(internal->GetValue());
1520
1521 CYPool pool;
3c1c3635 1522 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1523
1524 if (SEL sel = sel_getUid(name))
1525 if (class_getInstanceMethod(_class, sel) != NULL)
1526 return true;
1527
1528 return false;
1529}
1530
365abb0a
JF
1531static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1532 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1533 Class _class(internal->GetValue());
1534
1535 CYPool pool;
3c1c3635 1536 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1537
1538 if (SEL sel = sel_getUid(name))
39bb4b6a 1539 if (objc_method *method = class_getInstanceMethod(_class, sel))
dc68b74c
JF
1540 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1541
1542 return NULL;
1543}
1544
365abb0a
JF
1545static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1546 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1547 Class _class(internal->GetValue());
1548
1549 CYPool pool;
3c1c3635 1550 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1551
1552 SEL sel(sel_registerName(name));
1553
39bb4b6a 1554 objc_method *method(class_getInstanceMethod(_class, sel));
dc68b74c
JF
1555
1556 const char *type;
1557 IMP imp;
1558
1559 if (JSValueIsObjectOfClass(context, value, Message_)) {
1560 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1561 type = sig::Unparse(pool, &message->signature_);
1562 imp = reinterpret_cast<IMP>(message->GetValue());
1563 } else {
37954781 1564 type = CYPoolTypeEncoding(pool, context, sel, method);
dc68b74c
JF
1565 imp = CYMakeMessage(context, value, type);
1566 }
1567
1568 if (method != NULL)
1569 method_setImplementation(method, imp);
b5dd57dc
JF
1570 else {
1571#ifdef GNU_RUNTIME
1572 GSMethodList list(GSAllocMethodList(1));
1573 GSAppendMethodToList(list, sel, type, imp, YES);
1574 GSAddMethodList(_class, list, YES);
1575 GSFlushMethodCacheForClass(_class);
1576#else
1577 class_addMethod(_class, sel, imp, type);
1578#endif
1579 }
dc68b74c
JF
1580
1581 return true;
1582}
1583
7c6c5b0a 1584#if 0 && OBJC_API_VERSION < 2
365abb0a
JF
1585static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1586 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1587 Class _class(internal->GetValue());
1588
1589 CYPool pool;
aabea98c 1590 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1591
1592 if (SEL sel = sel_getUid(name))
39bb4b6a 1593 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
dc68b74c
JF
1594 objc_method_list list = {NULL, 1, {method}};
1595 class_removeMethods(_class, &list);
1596 return true;
1597 }
1598
1599 return false;
1600}
1601#endif
1602
365abb0a
JF
1603static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1604 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1605 Class _class(internal->GetValue());
1606
7c6c5b0a 1607#if OBJC_API_VERSION >= 2
dc68b74c 1608 unsigned int size;
39bb4b6a 1609 objc_method **data(class_copyMethodList(_class, &size));
dc68b74c
JF
1610 for (size_t i(0); i != size; ++i)
1611 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1612 free(data);
aabea98c
JF
1613#else
1614 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1615 for (int i(0); i != methods->method_count; ++i)
1616 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1617#endif
dc68b74c
JF
1618}
1619
3e264692
JF
1620static bool CYHasImplicitProperties(Class _class) {
1621 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
8e0afb16 1622 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
3e264692
JF
1623 return true;
1624 return [_class cy$hasImplicitProperties];
1625}
1626
7b184c00
JF
1627static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1628 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1629 id self(internal->GetValue());
1630
1631 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1632 return true;
1633
c239b9f8 1634 CYPool pool;
aabea98c 1635 NSString *name(CYCastNSString(pool, context, property));
7b184c00 1636
c44063e0
JF
1637 if (CYInternal *internal = [CYInternal get:self])
1638 if ([internal hasProperty:property inContext:context])
7b184c00
JF
1639 return true;
1640
365abb0a
JF
1641 Class _class(object_getClass(self));
1642
7b184c00 1643 CYPoolTry {
365abb0a 1644 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
8e0afb16 1645 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
365abb0a
JF
1646 if ([self cy$hasProperty:name])
1647 return true;
7b184c00
JF
1648 } CYPoolCatch(false)
1649
3c1c3635 1650 const char *string(CYPoolCString(pool, context, name));
7b184c00 1651
aabea98c 1652#ifdef __APPLE__
7b184c00
JF
1653 if (class_getProperty(_class, string) != NULL)
1654 return true;
aabea98c 1655#endif
7b184c00 1656
3e264692
JF
1657 if (CYHasImplicitProperties(_class))
1658 if (SEL sel = sel_getUid(string))
1659 if (CYImplements(self, _class, sel, true))
1660 return true;
7b184c00
JF
1661
1662 return false;
1663}
1664
3c1c3635 1665static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
7b184c00
JF
1666 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1667 id self(internal->GetValue());
1668
1669 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1670 return Internal::Make(context, self, object);
c239b9f8 1671
3c1c3635 1672 CYPool pool;
aabea98c 1673 NSString *name(CYCastNSString(pool, context, property));
c239b9f8 1674
c44063e0
JF
1675 if (CYInternal *internal = [CYInternal get:self])
1676 if (JSValueRef value = [internal getProperty:property inContext:context])
3c1c3635 1677 return value;
c239b9f8 1678
3c1c3635 1679 CYPoolTry {
6b9e29d2
JF
1680 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1681 return value;
3c1c3635 1682 } CYPoolCatch(NULL)
c239b9f8 1683
3c1c3635
JF
1684 const char *string(CYPoolCString(pool, context, name));
1685 Class _class(object_getClass(self));
c239b9f8 1686
cbaa5f0f 1687#ifdef __APPLE__
3c1c3635
JF
1688 if (objc_property_t property = class_getProperty(_class, string)) {
1689 PropertyAttributes attributes(property);
1690 SEL sel(sel_registerName(attributes.Getter()));
1691 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1692 }
cbaa5f0f 1693#endif
c239b9f8 1694
3e264692
JF
1695 if (CYHasImplicitProperties(_class))
1696 if (SEL sel = sel_getUid(string))
1697 if (CYImplements(self, _class, sel, true))
1698 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
8953777c 1699
3c1c3635
JF
1700 return NULL;
1701} CYCatch }
c239b9f8 1702
3c1c3635 1703static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
dc68b74c
JF
1704 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1705 id self(internal->GetValue());
1706
c239b9f8
JF
1707 CYPool pool;
1708
aabea98c 1709 NSString *name(CYCastNSString(pool, context, property));
3c1c3635 1710 NSObject *data(CYCastNSObject(pool, context, value));
8953777c 1711
3c1c3635
JF
1712 CYPoolTry {
1713 if ([self cy$setProperty:name to:data])
c239b9f8 1714 return true;
3c1c3635 1715 } CYPoolCatch(NULL)
dc68b74c 1716
3c1c3635 1717 const char *string(CYPoolCString(pool, context, name));
c239b9f8
JF
1718 Class _class(object_getClass(self));
1719
8aa3e970 1720#ifdef __APPLE__
3c1c3635
JF
1721 if (objc_property_t property = class_getProperty(_class, string)) {
1722 PropertyAttributes attributes(property);
1723 if (const char *setter = attributes.Setter()) {
1724 SEL sel(sel_registerName(setter));
1725 JSValueRef arguments[1] = {value};
1726 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
9b5527f0
JF
1727 return true;
1728 }
3c1c3635 1729 }
b24eb750 1730#endif
c239b9f8 1731
3c1c3635 1732 size_t length(strlen(string));
9e20b0b7 1733
3c1c3635 1734 char set[length + 5];
f33b048a 1735
3c1c3635
JF
1736 set[0] = 's';
1737 set[1] = 'e';
1738 set[2] = 't';
f33b048a 1739
3c1c3635
JF
1740 if (string[0] != '\0') {
1741 set[3] = toupper(string[0]);
1742 memcpy(set + 4, string + 1, length - 1);
e0dc20ec 1743 }
bd17e6f3 1744
3c1c3635
JF
1745 set[length + 3] = ':';
1746 set[length + 4] = '\0';
9b5527f0 1747
3c1c3635 1748 if (SEL sel = sel_getUid(set))
8e0afb16 1749 if (CYImplements(self, _class, sel)) {
3c1c3635
JF
1750 JSValueRef arguments[1] = {value};
1751 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
975cde38 1752 return true;
3c1c3635 1753 }
f37b3d2b 1754
c44063e0
JF
1755 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1756 [internal setProperty:property toValue:value inContext:context];
f37b3d2b 1757 return true;
3c1c3635 1758 }
f37b3d2b 1759
3c1c3635
JF
1760 return false;
1761} CYCatch }
9b5527f0 1762
3c1c3635
JF
1763static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1764 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1765 id self(internal->GetValue());
9b5527f0 1766
3c1c3635 1767 CYPoolTry {
aabea98c 1768 NSString *name(CYCastNSString(NULL, context, property));
3c1c3635
JF
1769 return [self cy$deleteProperty:name];
1770 } CYPoolCatch(NULL)
7c6c5b0a 1771} CYCatch return /*XXX*/ NULL; }
9b5527f0 1772
ec18fc0e
JF
1773static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1774 const char *name(sel_getName(method_getName(method)));
1775 if (strchr(name, ':') != NULL)
1776 return;
1777
1778 const char *type(method_getTypeEncoding(method));
1779 if (type == NULL || *type == '\0' || *type == 'v')
1780 return;
1781
1782 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1783}
1784
3c1c3635
JF
1785static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1786 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1787 id self(internal->GetValue());
9b5527f0 1788
3c1c3635
JF
1789 CYPool pool;
1790 Class _class(object_getClass(self));
9b5527f0 1791
3c1c3635
JF
1792#ifdef __APPLE__
1793 {
1794 unsigned int size;
1795 objc_property_t *data(class_copyPropertyList(_class, &size));
1796 for (size_t i(0); i != size; ++i)
1797 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1798 free(data);
1799 }
1800#endif
d3760804 1801
326a9dba
JF
1802 if (CYHasImplicitProperties(_class))
1803 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
ec18fc0e 1804#if OBJC_API_VERSION >= 2
326a9dba
JF
1805 unsigned int size;
1806 objc_method **data(class_copyMethodList(current, &size));
1807 for (size_t i(0); i != size; ++i)
1808 Instance_getPropertyNames_message(names, data[i]);
1809 free(data);
ec18fc0e 1810#else
326a9dba
JF
1811 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1812 for (int i(0); i != methods->method_count; ++i)
1813 Instance_getPropertyNames_message(names, &methods->method_list[i]);
ec18fc0e 1814#endif
326a9dba 1815 }
ec18fc0e 1816
d3760804
JF
1817 CYPoolTry {
1818 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
8e0afb16 1819 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
8665da0c 1820 [self cy$getPropertyNames:names inContext:context];
d3760804 1821 } CYPoolCatch()
9b5527f0
JF
1822}
1823
3c1c3635
JF
1824static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1825 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1826 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1827 return value;
1828} CYCatch }
bd17e6f3 1829
aaa3cd1e
JF
1830static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1831 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1832 id self(internal->GetValue());
1833
1834 if (![self isKindOfClass:NSBlock_])
1835 CYThrow("non-NSBlock object is not a function");
f5d7110c
JF
1836 // XXX: replace above logic with the following assertion
1837 //_assert([self isKindOfClass:NSBlock_]);
1838 // to do this, make it so FunctionInstance_ is the class of blocks
1839 // to do /that/, generalize the various "is exactly Instance_" checks
1840 // then, move Instance_callAsFunction to only be on FunctionInstance
aaa3cd1e
JF
1841
1842 struct BlockDescriptor1 {
1843 unsigned long int reserved;
1844 unsigned long int size;
1845 };
1846
1847 struct BlockDescriptor2 {
1848 void (*copy_helper)(void *dst, void *src);
1849 void (*dispose_helper)(void *src);
1850 };
1851
1852 struct BlockDescriptor3 {
1853 const char *signature;
1854 const char *layout;
1855 };
1856
1857 struct BlockLiteral {
1858 Class isa;
1859 int flags;
1860 int reserved;
1861 void (*invoke)(void *, ...);
1862 void *descriptor;
1863 } *literal = reinterpret_cast<BlockLiteral *>(self);
1864
1865 enum {
1866 BLOCK_DEALLOCATING = 0x0001,
1867 BLOCK_REFCOUNT_MASK = 0xfffe,
1868 BLOCK_NEEDS_FREE = 1 << 24,
1869 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
1870 BLOCK_HAS_CTOR = 1 << 26,
1871 BLOCK_IS_GC = 1 << 27,
1872 BLOCK_IS_GLOBAL = 1 << 28,
1873 BLOCK_HAS_STRET = 1 << 29,
1874 BLOCK_HAS_SIGNATURE = 1 << 30,
1875 };
1876
1877 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1878 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1879 descriptor += sizeof(BlockDescriptor1);
1880 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1881 descriptor += sizeof(BlockDescriptor2);
1882 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1883
1884 if (const char *type = descriptor3->signature) {
1885 CYPool pool;
1886
1887 void *setup[1];
1888 setup[0] = &self;
1889
1890 sig::Signature signature;
1891 sig::Parse(pool, &signature, type, &Structor_);
1892
1893 ffi_cif cif;
1894 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1895
1896 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1897 return CYCallFunction(pool, context, 1, setup, count, arguments, false, exception, &signature, &cif, function);
1898 }
1899 }
1900
1901 if (count != 0)
1902 CYThrow("NSBlock without signature field passed arguments");
1903
1904 CYPoolTry {
1905 [self invoke];
1906 } CYPoolCatch(NULL);
1907
1908 return NULL;
1909} CYCatch }
1910
3c1c3635
JF
1911static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1912 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1913 Class _class(internal->GetValue());
1914 if (!CYIsClass(_class))
1915 return false;
bd17e6f3 1916
8150077d 1917 if (CYJSValueIsNSObject(context, instance)) {
3c1c3635
JF
1918 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1919 // XXX: this isn't always safe
1920 return [linternal->GetValue() isKindOfClass:_class];
1921 }
ff783f8c 1922
3c1c3635
JF
1923 return false;
1924} CYCatch }
bd17e6f3 1925
f2f0d1d1
JF
1926static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1927 if (count == 0)
1928 throw CYJSError(context, "incorrect number of arguments to Instance");
1929 CYPool pool;
1930 id value(CYCastNSObject(pool, context, arguments[0]));
1931 if (value == nil)
1932 value = [NSNull null];
1933 return CYCastJSValue(context, [value cy$box]);
1934} CYCatch }
1935
3c1c3635
JF
1936static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1937 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
f33b048a 1938 CYPool pool;
bd17e6f3 1939
3c1c3635
JF
1940 id self(internal->GetValue());
1941 const char *name(CYPoolCString(pool, context, property));
520c130f 1942
3c1c3635 1943 if (object_getInstanceVariable(self, name, NULL) != NULL)
bd17e6f3 1944 return true;
3c1c3635
JF
1945
1946 return false;
bd17e6f3
JF
1947}
1948
3c1c3635
JF
1949static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1950 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1951 CYPool pool;
930aa21b 1952
3c1c3635
JF
1953 id self(internal->GetValue());
1954 const char *name(CYPoolCString(pool, context, property));
f33b048a 1955
aabea98c 1956 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
3c1c3635 1957 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
b81e7fb6 1958 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
3c1c3635
JF
1959 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1960 }
f33b048a 1961
3c1c3635
JF
1962 return NULL;
1963} CYCatch }
283e7e33 1964
3c1c3635
JF
1965static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1966 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1967 CYPool pool;
283e7e33 1968
3c1c3635
JF
1969 id self(internal->GetValue());
1970 const char *name(CYPoolCString(pool, context, property));
283e7e33 1971
aabea98c 1972 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
3c1c3635
JF
1973 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1974 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1975 return true;
283e7e33 1976 }
f33b048a 1977
3c1c3635
JF
1978 return false;
1979} CYCatch }
85a33bf5 1980
3c1c3635
JF
1981static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1982 if (Class super = class_getSuperclass(_class))
1983 Internal_getPropertyNames_(super, names);
ea2d184c 1984
7c6c5b0a 1985#if OBJC_API_VERSION >= 2
3c1c3635 1986 unsigned int size;
aabea98c 1987 objc_ivar **data(class_copyIvarList(_class, &size));
3c1c3635
JF
1988 for (size_t i(0); i != size; ++i)
1989 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1990 free(data);
b5dd57dc
JF
1991#else
1992 if (objc_ivar_list *ivars = _class->ivars)
1993 for (int i(0); i != ivars->ivar_count; ++i)
1994 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1995#endif
3c1c3635
JF
1996}
1997
1998static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1999 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2000 CYPool pool;
ea2d184c 2001
3c1c3635
JF
2002 id self(internal->GetValue());
2003 Class _class(object_getClass(self));
7ba62cfd 2004
3c1c3635 2005 Internal_getPropertyNames_(_class, names);
7ba62cfd 2006}
ea2d184c 2007
3c1c3635
JF
2008static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2009 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2010 return internal->GetOwner();
c239b9f8
JF
2011}
2012
3c1c3635
JF
2013static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2014 CYPool pool;
aabea98c 2015 NSString *name(CYCastNSString(pool, context, property));
3c1c3635
JF
2016 if (Class _class = NSClassFromString(name))
2017 return CYMakeInstance(context, _class, true);
2018 return NULL;
2019} CYCatch }
2020
c239b9f8 2021static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
aabea98c 2022#ifdef __APPLE__
c239b9f8
JF
2023 size_t size(objc_getClassList(NULL, 0));
2024 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2025
2026 get:
2027 size_t writ(objc_getClassList(data, size));
2028 if (size < writ) {
2029 size = writ;
2030 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2031 data = copy;
2032 goto get;
2033 } else goto done;
2034 }
2035
2036 for (size_t i(0); i != writ; ++i)
2037 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2038
2039 done:
2040 free(data);
aabea98c
JF
2041#else
2042 void *state(NULL);
2043 while (Class _class = objc_next_class(&state))
2044 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2045#endif
c239b9f8
JF
2046}
2047
7c6c5b0a 2048#if OBJC_API_VERSION >= 2
3c1c3635 2049static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
c239b9f8
JF
2050 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2051
3c1c3635
JF
2052 CYPool pool;
2053 const char *name(CYPoolCString(pool, context, property));
2054 unsigned int size;
2055 const char **data(objc_copyClassNamesForImage(internal, &size));
2056 JSValueRef value;
2057 for (size_t i(0); i != size; ++i)
2058 if (strcmp(name, data[i]) == 0) {
2059 if (Class _class = objc_getClass(name)) {
2060 value = CYMakeInstance(context, _class, true);
2061 goto free;
2062 } else
2063 break;
2064 }
2065 value = NULL;
2066 free:
2067 free(data);
2068 return value;
2069} CYCatch }
c239b9f8
JF
2070
2071static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2072 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2073 unsigned int size;
2074 const char **data(objc_copyClassNamesForImage(internal, &size));
2075 for (size_t i(0); i != size; ++i)
2076 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2077 free(data);
2078}
2079
3c1c3635
JF
2080static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2081 CYPool pool;
2082 const char *name(CYPoolCString(pool, context, property));
2083 unsigned int size;
2084 const char **data(objc_copyImageNames(&size));
2085 for (size_t i(0); i != size; ++i)
2086 if (strcmp(name, data[i]) == 0) {
2087 name = data[i];
2088 goto free;
2089 }
2090 name = NULL;
2091 free:
2092 free(data);
2093 if (name == NULL)
2094 return NULL;
2095 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2096 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2097 return value;
2098} CYCatch }
c239b9f8
JF
2099
2100static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2101 unsigned int size;
2102 const char **data(objc_copyImageNames(&size));
2103 for (size_t i(0); i != size; ++i)
2104 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2105 free(data);
2106}
aabea98c 2107#endif
c239b9f8 2108
3c1c3635
JF
2109static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2110 CYPool pool;
aabea98c
JF
2111 const char *name(CYPoolCString(pool, context, property));
2112 if (Protocol *protocol = objc_getProtocol(name))
3c1c3635
JF
2113 return CYMakeInstance(context, protocol, true);
2114 return NULL;
2115} CYCatch }
c239b9f8
JF
2116
2117static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
7c6c5b0a 2118#if OBJC_API_VERSION >= 2
c239b9f8
JF
2119 unsigned int size;
2120 Protocol **data(objc_copyProtocolList(&size));
2121 for (size_t i(0); i != size; ++i)
2122 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2123 free(data);
aabea98c
JF
2124#else
2125 // XXX: fix this!
2126#endif
c239b9f8 2127}
707bcb93 2128
26ef7a82
JF
2129static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2130 CYPool pool;
2131 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2132 if (name == "nil")
2133 return Instance::Make(context, nil);
2134 return NULL;
2135} CYCatch }
2136
2137static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2138 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2139}
2140
aabea98c 2141#ifdef __APPLE__
534fb6da 2142static bool stret(ffi_type *ffi_type) {
04450da0
JF
2143 return ffi_type->type == FFI_TYPE_STRUCT && (
2144 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2145 struct_forward_array[ffi_type->size] != 0
2146 );
2147}
aabea98c 2148#endif
b09da87b 2149
3c1c3635 2150JSValueRef 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 2151 const char *type;
ea2d184c 2152
cacd1a88
JF
2153 if (_class == NULL)
2154 _class = object_getClass(self);
2155
aabea98c
JF
2156 IMP imp;
2157
2158 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2159 imp = method_getImplementation(method);
4afefdd9 2160 type = method_getTypeEncoding(method);
aabea98c
JF
2161 } else {
2162 imp = NULL;
2163
3c1c3635
JF
2164 CYPoolTry {
2165 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2166 if (method == nil)
37954781 2167 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3c1c3635
JF
2168 type = CYPoolCString(pool, context, [method _typeString]);
2169 } CYPoolCatch(NULL)
4afefdd9
JF
2170 }
2171
2172 void *setup[2];
f623c5d8 2173 setup[0] = &self;
4afefdd9
JF
2174 setup[1] = &_cmd;
2175
2176 sig::Signature signature;
f33b048a 2177 sig::Parse(pool, &signature, type, &Structor_);
4afefdd9 2178
0add079d
JF
2179 size_t used(count + 3);
2180 if (used > signature.count) {
2181 sig::Element *elements(new (pool) sig::Element[used]);
2182 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2183
2184 for (size_t index(signature.count); index != used; ++index) {
2185 sig::Element *element(&elements[index]);
2186 element->name = NULL;
2187 element->offset = _not(size_t);
2188
2189 sig::Type *type(new (pool) sig::Type);
2190 memset(type, 0, sizeof(*type));
2191 type->primitive = sig::object_P;
2192 element->type = type;
2193 }
2194
2195 signature.elements = elements;
2196 signature.count = used;
2197 }
2198
4afefdd9
JF
2199 ffi_cif cif;
2200 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2201
f623c5d8 2202 if (imp == NULL) {
aabea98c
JF
2203#ifdef __APPLE__
2204 if (stret(cif.rtype))
2205 imp = class_getMethodImplementation_stret(_class, _cmd);
2206 else
2207 imp = class_getMethodImplementation(_class, _cmd);
2208#else
f623c5d8 2209 objc_super super = {self, _class};
aabea98c
JF
2210 imp = objc_msg_lookup_super(&super, _cmd);
2211#endif
f623c5d8 2212 }
aabea98c
JF
2213
2214 void (*function)() = reinterpret_cast<void (*)()>(imp);
2b52f27e 2215 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3c1c3635 2216} CYCatch }
367eebb1 2217
3c1c3635
JF
2218static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2219 if (count < 2)
37954781 2220 throw CYJSError(context, "too few arguments to objc_msgSend");
367eebb1 2221
478d4ed0
JF
2222 CYPool pool;
2223
2b52f27e
JF
2224 bool uninitialized;
2225
4afefdd9
JF
2226 id self;
2227 SEL _cmd;
cacd1a88 2228 Class _class;
4afefdd9 2229
3c1c3635
JF
2230 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2231 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2232 self = internal->GetValue();
2233 _class = internal->class_;;
2234 uninitialized = false;
8150077d 2235 } else if (CYJSValueIsNSObject(context, arguments[0])) {
3c1c3635
JF
2236 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2237 self = internal->GetValue();
2238 _class = nil;
2239 uninitialized = internal->IsUninitialized();
2240 if (uninitialized)
2241 internal->value_ = nil;
2242 } else {
2243 self = CYCastNSObject(pool, context, arguments[0]);
2244 _class = nil;
2245 uninitialized = false;
2246 }
2b52f27e 2247
3c1c3635
JF
2248 if (self == nil)
2249 return CYJSNull(context);
7ba62cfd 2250
3c1c3635 2251 _cmd = CYCastSEL(context, arguments[1]);
ea2d184c 2252
cacd1a88 2253 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
3c1c3635 2254} CYCatch }
7ba62cfd 2255
dea834b0
JF
2256static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2257 JSValueRef setup[count + 2];
2258 setup[0] = _this;
2259 setup[1] = object;
4afefdd9 2260 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
dea834b0
JF
2261 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2262}
2263
dc68b74c
JF
2264static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2265 CYPool pool;
2266 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2267
2268 // XXX: handle Instance::Uninitialized?
2269 id self(CYCastNSObject(pool, context, _this));
2270
2271 void *setup[2];
2272 setup[0] = &self;
2273 setup[1] = &internal->sel_;
2274
2275 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2276}
2277
3c1c3635
JF
2278static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2279 if (count != 2)
37954781 2280 throw CYJSError(context, "incorrect number of arguments to Super constructor");
4afefdd9 2281 CYPool pool;
3c1c3635
JF
2282 id self(CYCastNSObject(pool, context, arguments[0]));
2283 Class _class(CYCastClass(pool, context, arguments[1]));
2284 return cy::Super::Make(context, self, _class);
2285} CYCatch }
bce8339b 2286
3c1c3635
JF
2287static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2288 if (count != 1)
37954781
JF
2289 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2290 CYPool pool;
2291 const char *name(CYPoolCString(pool, context, arguments[0]));
3c1c3635
JF
2292 return CYMakeSelector(context, sel_registerName(name));
2293} CYCatch }
7b184c00 2294
3c1c3635
JF
2295static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2296 if (count > 1)
37954781 2297 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
3c1c3635 2298 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
15024d7e 2299 return CYMakeInstance(context, self, false);
3c1c3635 2300} CYCatch }
ea2d184c 2301
534fb6da 2302static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
61933e16
JF
2303 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2304 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
04450da0
JF
2305}
2306
7b184c00
JF
2307static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2308 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2309 Type_privateData *typical(internal->GetType());
2310
2311 sig::Type *type;
2312 ffi_type *ffi;
2313
2314 if (typical == NULL) {
2315 type = NULL;
2316 ffi = NULL;
2317 } else {
2318 type = typical->type_;
2319 ffi = typical->ffi_;
2320 }
2321
53ba31e9 2322 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
7b184c00 2323}
4afefdd9 2324
dc68b74c
JF
2325static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2326 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
ec599edf 2327 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
dc68b74c
JF
2328}
2329
2f1295ff 2330static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
365abb0a
JF
2331 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2332 id self(internal->GetValue());
2333 if (!CYIsClass(self))
2334 return CYJSUndefined(context);
3c1c3635
JF
2335 return CYGetClassPrototype(context, self);
2336} CYCatch }
365abb0a
JF
2337
2338static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
dc68b74c
JF
2339 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2340 id self(internal->GetValue());
b5dd57dc 2341 if (!CYIsClass(self))
dc68b74c 2342 return CYJSUndefined(context);
b5dd57dc 2343 return Messages::Make(context, (Class) self);
dc68b74c
JF
2344}
2345
3c1c3635 2346static JSValueRef Instance_callAsFunction_toCYON(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)));
dd18424c 2351 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
3c1c3635 2352} CYCatch }
7b184c00 2353
3c1c3635 2354static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
8150077d 2355 if (!CYJSValueIsNSObject(context, _this))
365abb0a
JF
2356 return NULL;
2357
7b184c00 2358 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
e23a9070 2359 id value(internal->GetValue());
7b184c00 2360
3c1c3635 2361 CYPoolTry {
b5dd57dc
JF
2362 NSString *key;
2363 if (count == 0)
2364 key = nil;
2365 else
2366 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
e23a9070
JF
2367
2368 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2369 return CYJSUndefined(context);
2370 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2371 return json;
2372 else
2373 return CYCastJSValue(context, CYJSString(context, [value description]));
3c1c3635 2374 } CYPoolCatch(NULL)
7c6c5b0a 2375} CYCatch return /*XXX*/ NULL; }
b4aa79af 2376
c30687a7 2377static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
8150077d 2378 if (!CYJSValueIsNSObject(context, _this))
c30687a7
JF
2379 return NULL;
2380
2381 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
95221eed
JF
2382 id value(internal->GetValue());
2383
88c6482c 2384 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
95221eed
JF
2385 return _this;
2386
88c6482c 2387 if (JSValueRef result = [value cy$valueOfInContext:context])
95221eed
JF
2388 return result;
2389
2390 return _this;
c30687a7 2391} CYCatch return /*XXX*/ NULL; }
20ded97a
JF
2392
2393static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
8150077d 2394 if (!CYJSValueIsNSObject(context, _this))
20ded97a
JF
2395 return NULL;
2396
2397 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2398 // XXX: but... but... THIS ISN'T A POINTER! :(
2399 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2400} CYCatch return /*XXX*/ NULL; }
c30687a7 2401
3c1c3635 2402static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
8150077d 2403 if (!CYJSValueIsNSObject(context, _this))
365abb0a
JF
2404 return NULL;
2405
9e562cfc 2406 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
7db9993a 2407 id value(internal->GetValue());
6d056e33 2408
3c1c3635
JF
2409 CYPoolTry {
2410 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
6d056e33 2411 return CYCastJSValue(context, CYJSString(context, [value description]));
3c1c3635 2412 } CYPoolCatch(NULL)
7c6c5b0a 2413} CYCatch return /*XXX*/ NULL; }
478d4ed0 2414
b63701b2 2415static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
80ea020e
JF
2416 if (!CYJSValueIsNSObject(context, _this))
2417 return NULL;
2418
2419 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2420 id value(internal->GetValue());
2421
2422 if (!CYIsClass(value))
2423 CYThrow("non-Class object cannot be used as Type");
2424
2425 // XXX: this is a very silly implementation
2426
2427 std::ostringstream type;
2428 type << "@\"";
2429 type << class_getName(value);
2430 type << "\"";
2431
2432 CYPoolTry {
2433 return CYMakeType(context, type.str().c_str());
2434 } CYPoolCatch(NULL)
2435} CYCatch return /*XXX*/ NULL; }
2436
3c1c3635 2437static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
9e562cfc 2438 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3c1c3635
JF
2439 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2440} CYCatch }
478d4ed0 2441
b4aa79af
JF
2442static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2443 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2444}
2445
3c1c3635 2446static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
7b184c00
JF
2447 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2448 const char *name(sel_getName(internal->GetValue()));
2449
3c1c3635 2450 CYPoolTry {
95678376
JF
2451 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2452 return CYCastJSValue(context, CYJSString(context, string));
3c1c3635 2453 } CYPoolCatch(NULL)
7c6c5b0a 2454} CYCatch return /*XXX*/ NULL; }
e5bc40db 2455
3c1c3635
JF
2456static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2457 if (count != 1)
37954781
JF
2458 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2459
3c1c3635
JF
2460 CYPool pool;
2461 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
37954781
JF
2462 SEL sel(internal->GetValue());
2463
2464 objc_method *method;
2465 if (Class _class = CYCastClass(pool, context, arguments[0]))
2466 method = class_getInstanceMethod(_class, sel);
2467 else
2468 method = NULL;
2469
2470 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2471 return CYCastJSValue(context, CYJSString(type));
e5bc40db 2472
3c1c3635
JF
2473 return CYJSNull(context);
2474} CYCatch }
e5bc40db 2475
856b8cd0 2476static JSStaticValue Selector_staticValues[2] = {
61933e16 2477 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
04450da0
JF
2478 {NULL, NULL, NULL, 0}
2479};
953647c1 2480
365abb0a 2481static JSStaticValue Instance_staticValues[5] = {
9e562cfc 2482 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
365abb0a 2483 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2f1295ff 2484 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
9e562cfc 2485 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
9b5527f0
JF
2486 {NULL, NULL, NULL, 0}
2487};
2488
b63701b2 2489static JSStaticFunction Instance_staticFunctions[7] = {
7b184c00 2490 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b4aa79af
JF
2491 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2492 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
95221eed 2493 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
20ded97a 2494 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0 2495 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b63701b2
JF
2496 {NULL, NULL, 0}
2497};
2498
2499static JSStaticFunction Class_staticFunctions[2] = {
2500 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0
JF
2501 {NULL, NULL, 0}
2502};
2503
9b5527f0
JF
2504static JSStaticFunction Internal_staticFunctions[2] = {
2505 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2506 {NULL, NULL, 0}
2507};
2508
b4aa79af
JF
2509static JSStaticFunction Selector_staticFunctions[5] = {
2510 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2511 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0 2512 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b09da87b
JF
2513 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2514 {NULL, NULL, 0}
2515};
ea2d184c 2516
e23a9070
JF
2517#ifdef __APPLE__
2518JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_(context) {
2519 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2520} CYObjectiveCatch }
2521#endif
2522
3c9f7e22 2523void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
c44063e0
JF
2524 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2525 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2526 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2527
37954781
JF
2528 apr_pool_t *pool(CYGetGlobalPool());
2529
807a88be
JF
2530 Object_type = new(pool) Type_privateData("@");
2531 Selector_type = new(pool) Type_privateData(":");
7b184c00 2532
b53b30c1 2533#ifdef __APPLE__
0fe4a14b
JF
2534 // XXX: apparently, iOS now has both of these
2535 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
18ed94e4 2536 if (NSCFBoolean_ == nil)
0fe4a14b 2537 NSCFBoolean_ = objc_getClass("NSCFBoolean");
18ed94e4 2538
c239b9f8 2539 NSCFType_ = objc_getClass("NSCFType");
aaa4a269 2540 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
b5dd57dc
JF
2541 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2542 NSZombie_ = objc_getClass("_NSZombie_");
c074e774
JF
2543#else
2544 NSBoolNumber_ = objc_getClass("NSBoolNumber");
b53b30c1
JF
2545#endif
2546
2547 NSArray_ = objc_getClass("NSArray");
aaa3cd1e 2548 NSBlock_ = objc_getClass("NSBlock");
b5dd57dc 2549 NSDictionary_ = objc_getClass("NSDictionary");
4cb8aa43 2550 NSString_ = objc_getClass("NSString");
c239b9f8 2551 Object_ = objc_getClass("Object");
3c1c3635
JF
2552
2553 JSClassDefinition definition;
2554
2555 definition = kJSClassDefinitionEmpty;
2556 definition.className = "Instance";
2557 definition.staticValues = Instance_staticValues;
2558 definition.staticFunctions = Instance_staticFunctions;
2559 definition.hasProperty = &Instance_hasProperty;
2560 definition.getProperty = &Instance_getProperty;
2561 definition.setProperty = &Instance_setProperty;
2562 definition.deleteProperty = &Instance_deleteProperty;
2563 definition.getPropertyNames = &Instance_getPropertyNames;
2564 definition.callAsConstructor = &Instance_callAsConstructor;
aaa3cd1e 2565 definition.callAsFunction = &Instance_callAsFunction;
3c1c3635 2566 definition.hasInstance = &Instance_hasInstance;
37954781 2567 definition.finalize = &CYFinalize;
3c1c3635
JF
2568 Instance_ = JSClassCreate(&definition);
2569
1fb9f0d0
JF
2570 definition.className = "ArrayInstance";
2571 ArrayInstance_ = JSClassCreate(&definition);
2572
3d79777a
JF
2573 definition.className = "FunctionInstance";
2574 FunctionInstance_ = JSClassCreate(&definition);
2575
1fb9f0d0
JF
2576 definition.className = "ObjectInstance";
2577 ObjectInstance_ = JSClassCreate(&definition);
2578
2579 definition.className = "StringInstance";
2580 StringInstance_ = JSClassCreate(&definition);
2581
b63701b2
JF
2582 definition = kJSClassDefinitionEmpty;
2583 definition.className = "Class";
2584 definition.staticFunctions = Class_staticFunctions;
2585 Class_ = JSClassCreate(&definition);
f5d7110c 2586
3c1c3635
JF
2587 definition = kJSClassDefinitionEmpty;
2588 definition.className = "Internal";
2589 definition.staticFunctions = Internal_staticFunctions;
2590 definition.hasProperty = &Internal_hasProperty;
2591 definition.getProperty = &Internal_getProperty;
2592 definition.setProperty = &Internal_setProperty;
2593 definition.getPropertyNames = &Internal_getPropertyNames;
37954781 2594 definition.finalize = &CYFinalize;
3c1c3635
JF
2595 Internal_ = JSClassCreate(&definition);
2596
2597 definition = kJSClassDefinitionEmpty;
2598 definition.className = "Message";
37954781 2599 definition.staticFunctions = cy::Functor::StaticFunctions;
3c1c3635 2600 definition.callAsFunction = &Message_callAsFunction;
37954781 2601 definition.finalize = &CYFinalize;
3c1c3635
JF
2602 Message_ = JSClassCreate(&definition);
2603
2604 definition = kJSClassDefinitionEmpty;
2605 definition.className = "Messages";
2606 definition.hasProperty = &Messages_hasProperty;
2607 definition.getProperty = &Messages_getProperty;
2608 definition.setProperty = &Messages_setProperty;
7c6c5b0a 2609#if 0 && OBJC_API_VERSION < 2
3c1c3635
JF
2610 definition.deleteProperty = &Messages_deleteProperty;
2611#endif
2612 definition.getPropertyNames = &Messages_getPropertyNames;
37954781 2613 definition.finalize = &CYFinalize;
3c1c3635
JF
2614 Messages_ = JSClassCreate(&definition);
2615
2616 definition = kJSClassDefinitionEmpty;
2617 definition.className = "Selector";
2618 definition.staticValues = Selector_staticValues;
2619 definition.staticFunctions = Selector_staticFunctions;
2620 definition.callAsFunction = &Selector_callAsFunction;
37954781 2621 definition.finalize = &CYFinalize;
3c1c3635
JF
2622 Selector_ = JSClassCreate(&definition);
2623
2624 definition = kJSClassDefinitionEmpty;
2625 definition.className = "Super";
2626 definition.staticFunctions = Internal_staticFunctions;
37954781 2627 definition.finalize = &CYFinalize;
3c1c3635
JF
2628 Super_ = JSClassCreate(&definition);
2629
2630 definition = kJSClassDefinitionEmpty;
2631 definition.className = "ObjectiveC::Classes";
2632 definition.getProperty = &ObjectiveC_Classes_getProperty;
2633 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2634 ObjectiveC_Classes_ = JSClassCreate(&definition);
2635
26ef7a82
JF
2636 definition = kJSClassDefinitionEmpty;
2637 definition.className = "ObjectiveC::Constants";
2638 definition.getProperty = &ObjectiveC_Constants_getProperty;
2639 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2640 ObjectiveC_Constants_ = JSClassCreate(&definition);
2641
7c6c5b0a 2642#if OBJC_API_VERSION >= 2
3c1c3635
JF
2643 definition = kJSClassDefinitionEmpty;
2644 definition.className = "ObjectiveC::Images";
2645 definition.getProperty = &ObjectiveC_Images_getProperty;
2646 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2647 ObjectiveC_Images_ = JSClassCreate(&definition);
2648
2649 definition = kJSClassDefinitionEmpty;
2650 definition.className = "ObjectiveC::Image::Classes";
2651 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2652 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2653 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3c9f7e22 2654#endif
3c1c3635 2655
3c9f7e22
JF
2656 definition = kJSClassDefinitionEmpty;
2657 definition.className = "ObjectiveC::Protocols";
2658 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2659 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2660 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2661
3c9f7e22 2662#ifdef __APPLE__
e23a9070 2663 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
3c9f7e22
JF
2664#endif
2665} CYPoolCatch() }
2666
2667void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2668 JSObjectRef global(CYGetGlobalObject(context));
498c3570 2669 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2385c806
JF
2670 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2671 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
26ef7a82 2672 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
3c9f7e22
JF
2673
2674 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2385c806 2675 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
3c9f7e22 2676
26ef7a82
JF
2677 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2678 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2679 CYArrayPush(context, alls, protocols);
2680
2681 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2682 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2683 CYArrayPush(context, alls, classes);
2684
2685 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2686 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2687 CYArrayPush(context, alls, constants);
3c9f7e22
JF
2688
2689#if OBJC_API_VERSION >= 2
3c1c3635 2690 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
aabea98c 2691#endif
3c1c3635 2692
b63701b2 2693 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
3c1c3635
JF
2694 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2695 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2696 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2697 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2698
498c3570
JF
2699 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2700 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3c1c3635 2701
1fb9f0d0 2702 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
4a2eef6c
JF
2703 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2704 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2705 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2706 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2707
aaa3cd1e
JF
2708 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2709 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2710 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2711 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2712 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2713
1fb9f0d0 2714 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
11f3e89e
JF
2715 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2716 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2717 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2718 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2719
1fb9f0d0 2720 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
6732f195
JF
2721 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2722 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
6732f195
JF
2723 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2724 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2725
b63701b2
JF
2726 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2727 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2728 JSObjectSetPrototype(context, Class_prototype, Instance_prototype);
bc3080fd 2729
2385c806
JF
2730 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2731 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2732 CYSetProperty(context, cycript, CYJSString("Super"), Super);
3c1c3635 2733
f2f0d1d1
JF
2734 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2735 CYSetProperty(context, Instance, CYJSString("box"), box);
2736
8ad1528b 2737#if defined(__APPLE__) && defined(__arm__) && 0
98ea05a3 2738 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
b5dd57dc
JF
2739#endif
2740
98ea05a3 2741 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3c1c3635 2742
498c3570
JF
2743 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2744 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3c9f7e22 2745} CYPoolCatch() }
b5dd57dc
JF
2746
2747static CYHooks CYObjectiveCHooks = {
2748 &CYObjectiveC_ExecuteStart,
2749 &CYObjectiveC_ExecuteEnd,
b5dd57dc 2750 &CYObjectiveC_CallFunction,
3c9f7e22 2751 &CYObjectiveC_Initialize,
b5dd57dc
JF
2752 &CYObjectiveC_SetupContext,
2753 &CYObjectiveC_PoolFFI,
2754 &CYObjectiveC_FromFFI,
2755};
2756
2757struct CYObjectiveC {
2758 CYObjectiveC() {
2759 hooks_ = &CYObjectiveCHooks;
6faa533c
DWT
2760 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2761 _assert(hooks_ != NULL);
b5dd57dc
JF
2762 }
2763} CYObjectiveC;