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