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