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