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