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