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