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