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