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