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