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