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