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