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