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