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