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