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