]> git.saurik.com Git - cycript.git/blame - ObjectiveC/Library.mm
Merge CYCastNSObject{,_}, an obsolete distinction.
[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
993e8ed5 605_finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
3c1c3635 606 JSValueRef exception(NULL);
993e8ed5
JF
607 JSObjectRef constructor(CYGetCachedObject(context, cache));
608 bool is(JSValueIsInstanceOfConstructor(context, value, constructor, &exception));
3c1c3635 609 CYThrow(context, exception);
993e8ed5 610 return is;
3c1c3635 611}
4afefdd9 612
3c1c3635 613NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
993e8ed5 614 if (JSValueIsObjectOfClass(context, object, Instance_)) {
3c1c3635
JF
615 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
616 return internal->GetValue();
4afefdd9 617 }
993e8ed5
JF
618
619 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
620 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
621 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
3c1c3635 622}
4afefdd9 623
3c1c3635
JF
624NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
625 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
626}
4afefdd9 627
c074e774
JF
628#ifndef __APPLE__
629@interface NSBoolNumber : NSNumber {
630}
631@end
632#endif
633
3c1c3635
JF
634id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
635 id object;
636 bool copy;
637
638 switch (JSType type = JSValueGetType(context, value)) {
639 case kJSTypeUndefined:
640 object = [WebUndefined undefined];
641 copy = false;
642 break;
643
644 case kJSTypeNull:
645 return NULL;
646 break;
647
648 case kJSTypeBoolean:
cbaa5f0f 649#ifdef __APPLE__
3c1c3635
JF
650 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
651 copy = false;
652#else
c074e774 653 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
3c1c3635 654 copy = true;
b24eb750 655#endif
3c1c3635 656 break;
c239b9f8 657
3c1c3635
JF
658 case kJSTypeNumber:
659 object = CYCopyNSNumber(context, value);
660 copy = true;
661 break;
993f82f8 662
3c1c3635
JF
663 case kJSTypeString:
664 object = CYCopyNSString(context, value);
665 copy = true;
666 break;
993f82f8 667
3c1c3635
JF
668 case kJSTypeObject:
669 // XXX: this might could be more efficient
670 object = CYCastNSObject(pool, context, (JSObjectRef) value);
671 copy = false;
672 break;
993f82f8 673
3c1c3635 674 default:
37954781 675 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
3c1c3635
JF
676 break;
677 }
993f82f8 678
3c1c3635
JF
679 if (cast != copy)
680 return object;
681 else if (copy)
682 return CYPoolRelease(pool, object);
683 else
684 return [object retain];
993f82f8
JF
685}
686
3c1c3635
JF
687NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
688 return CYNSObject(pool, context, value, true);
689}
993f82f8 690
3c1c3635
JF
691NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
692 return CYNSObject(pool, context, value, false);
693}
993f82f8 694
365abb0a 695/* Bridge: NSArray {{{ */
107e3ed0 696@implementation NSArray (Cycript)
62ca2b82 697
f2f0d1d1
JF
698- (id) cy$box {
699 return [[self mutableCopy] autorelease];
700}
701
b4aa79af 702- (NSString *) cy$toCYON {
c1582939 703 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
5b1f57ee 704 [json appendString:@"@["];
c1582939
JF
705
706 bool comma(false);
cbaa5f0f 707#ifdef __APPLE__
62ca2b82 708 for (id object in self) {
cbaa5f0f 709#else
cbaa5f0f 710 for (size_t index(0), count([self count]); index != count; ++index) {
af4272e6 711 id object([self objectAtIndex:index]);
cbaa5f0f 712#endif
c1582939
JF
713 if (comma)
714 [json appendString:@","];
715 else
716 comma = true;
7b184c00 717 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
520c130f 718 [json appendString:CYCastNSCYON(object)];
6b8a9500
JF
719 else {
720 [json appendString:@","];
721 comma = false;
722 }
c1582939
JF
723 }
724
725 [json appendString:@"]"];
726 return json;
62ca2b82
JF
727}
728
7b184c00
JF
729- (bool) cy$hasProperty:(NSString *)name {
730 if ([name isEqualToString:@"length"])
731 return true;
732
520c130f 733 size_t index(CYGetIndex(name));
faf69207 734 if (index == _not(size_t) || index >= [self count])
7b184c00
JF
735 return [super cy$hasProperty:name];
736 else
737 return true;
738}
739
cc103044 740- (NSObject *) cy$getProperty:(NSString *)name {
cbaa5f0f
JF
741 if ([name isEqualToString:@"length"]) {
742 NSUInteger count([self count]);
743#ifdef __APPLE__
744 return [NSNumber numberWithUnsignedInteger:count];
745#else
746 return [NSNumber numberWithUnsignedInt:count];
747#endif
748 }
4afefdd9 749
520c130f 750 size_t index(CYGetIndex(name));
faf69207 751 if (index == _not(size_t) || index >= [self count])
cc103044
JF
752 return [super cy$getProperty:name];
753 else
754 return [self objectAtIndex:index];
755}
756
8665da0c
JF
757- (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
758 [super cy$getPropertyNames:names inContext:context];
d3760804
JF
759
760 for (size_t index(0), count([self count]); index != count; ++index) {
761 id object([self objectAtIndex:index]);
762 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
763 char name[32];
764 sprintf(name, "%zu", index);
765 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
766 }
767 }
768}
769
334bdca2
JF
770+ (bool) cy$hasImplicitProperties {
771 return false;
772}
773
cc103044 774@end
365abb0a 775/* }}} */
aaa3cd1e
JF
776/* Bridge: NSBlock {{{ */
777#ifdef __APPLE__
778@interface NSBlock
779- (void) invoke;
780@end
781#endif
782/* }}} */
c074e774
JF
783/* Bridge: NSBoolNumber {{{ */
784#ifndef __APPLE__
785@implementation NSBoolNumber (Cycript)
786
787- (JSType) cy$JSType {
788 return kJSTypeBoolean;
789}
790
791- (NSObject *) cy$toJSON:(NSString *)key {
792 return self;
793}
794
795- (NSString *) cy$toCYON {
5b1f57ee 796 return [self boolValue] ? @"@true" : @"@false";
c074e774
JF
797}
798
88c6482c 799- (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
c074e774
JF
800 return CYCastJSValue(context, (bool) [self boolValue]);
801} CYObjectiveCatch }
802
803@end
804#endif
805/* }}} */
365abb0a
JF
806/* Bridge: NSDictionary {{{ */
807@implementation NSDictionary (Cycript)
808
f2f0d1d1
JF
809- (id) cy$box {
810 return [[self mutableCopy] autorelease];
811}
812
365abb0a
JF
813- (NSString *) cy$toCYON {
814 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
5b1f57ee 815 [json appendString:@"@{"];
365abb0a
JF
816
817 bool comma(false);
cbaa5f0f 818#ifdef __APPLE__
0226d428 819 for (NSObject *key in self) {
cbaa5f0f
JF
820#else
821 NSEnumerator *keys([self keyEnumerator]);
0226d428 822 while (NSObject *key = [keys nextObject]) {
cbaa5f0f 823#endif
365abb0a
JF
824 if (comma)
825 [json appendString:@","];
826 else
827 comma = true;
5663aea5 828 [json appendString:CYCastNSCYON(key)];
365abb0a
JF
829 [json appendString:@":"];
830 NSObject *object([self objectForKey:key]);
520c130f 831 [json appendString:CYCastNSCYON(object)];
365abb0a 832 }
cc103044 833
365abb0a
JF
834 [json appendString:@"}"];
835 return json;
836}
837
838- (bool) cy$hasProperty:(NSString *)name {
839 return [self objectForKey:name] != nil;
840}
841
842- (NSObject *) cy$getProperty:(NSString *)name {
843 return [self objectForKey:name];
844}
845
8665da0c
JF
846- (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
847 [super cy$getPropertyNames:names inContext:context];
d3760804
JF
848
849#ifdef __APPLE__
0226d428 850 for (NSObject *key in self) {
d3760804
JF
851#else
852 NSEnumerator *keys([self keyEnumerator]);
0226d428 853 while (NSObject *key = [keys nextObject]) {
d3760804 854#endif
8665da0c 855 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
d3760804
JF
856 }
857}
858
3e264692
JF
859+ (bool) cy$hasImplicitProperties {
860 return false;
861}
862
365abb0a
JF
863@end
864/* }}} */
865/* Bridge: NSMutableArray {{{ */
cc103044
JF
866@implementation NSMutableArray (Cycript)
867
868- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
faf69207
JF
869 if ([name isEqualToString:@"length"]) {
870 // XXX: is this not intelligent?
cbaa5f0f
JF
871 NSNumber *number(reinterpret_cast<NSNumber *>(value));
872#ifdef __APPLE__
873 NSUInteger size([number unsignedIntegerValue]);
874#else
875 NSUInteger size([number unsignedIntValue]);
876#endif
faf69207
JF
877 NSUInteger count([self count]);
878 if (size < count)
879 [self removeObjectsInRange:NSMakeRange(size, count - size)];
880 else if (size != count) {
881 WebUndefined *undefined([WebUndefined undefined]);
882 for (size_t i(count); i != size; ++i)
883 [self addObject:undefined];
884 }
885 return true;
886 }
887
520c130f 888 size_t index(CYGetIndex(name));
faf69207 889 if (index == _not(size_t))
cc103044 890 return [super cy$setProperty:name to:value];
faf69207
JF
891
892 id object(value ?: [NSNull null]);
893
894 size_t count([self count]);
895 if (index < count)
896 [self replaceObjectAtIndex:index withObject:object];
cc103044 897 else {
faf69207
JF
898 if (index != count) {
899 WebUndefined *undefined([WebUndefined undefined]);
900 for (size_t i(count); i != index; ++i)
901 [self addObject:undefined];
902 }
903
904 [self addObject:object];
cc103044 905 }
faf69207 906
365abb0a 907 return true;
7b184c00
JF
908}
909
365abb0a 910- (bool) cy$deleteProperty:(NSString *)name {
520c130f 911 size_t index(CYGetIndex(name));
365abb0a
JF
912 if (index == _not(size_t) || index >= [self count])
913 return [super cy$deleteProperty:name];
914 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
915 return true;
cc103044
JF
916}
917
918@end
365abb0a
JF
919/* }}} */
920/* Bridge: NSMutableDictionary {{{ */
cc103044
JF
921@implementation NSMutableDictionary (Cycript)
922
923- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
b6ea08b6 924 [self setObject:(value ?: [NSNull null]) forKey:name];
cc103044
JF
925 return true;
926}
927
928- (bool) cy$deleteProperty:(NSString *)name {
929 if ([self objectForKey:name] == nil)
930 return false;
931 else {
932 [self removeObjectForKey:name];
933 return true;
934 }
935}
936
62ca2b82 937@end
365abb0a
JF
938/* }}} */
939/* Bridge: NSNumber {{{ */
107e3ed0 940@implementation NSNumber (Cycript)
62ca2b82 941
b4aa79af 942- (JSType) cy$JSType {
b53b30c1 943#ifdef __APPLE__
b4aa79af 944 // XXX: this just seems stupid
b53b30c1
JF
945 if ([self class] == NSCFBoolean_)
946 return kJSTypeBoolean;
947#endif
948 return kJSTypeNumber;
b4aa79af
JF
949}
950
951- (NSObject *) cy$toJSON:(NSString *)key {
952 return self;
953}
954
955- (NSString *) cy$toCYON {
5b1f57ee 956 return [self cy$JSType] != kJSTypeBoolean ? [NSString stringWithFormat:@"@%@", self] : [self boolValue] ? @"@true" : @"@false";
62ca2b82
JF
957}
958
88c6482c 959- (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
b4aa79af 960 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
3c1c3635 961} CYObjectiveCatch }
62ca2b82
JF
962
963@end
365abb0a
JF
964/* }}} */
965/* Bridge: NSNull {{{ */
966@implementation NSNull (Cycript)
967
968- (JSType) cy$JSType {
969 return kJSTypeNull;
970}
971
972- (NSObject *) cy$toJSON:(NSString *)key {
973 return self;
974}
975
976- (NSString *) cy$toCYON {
5b1f57ee 977 return @"@null";
365abb0a
JF
978}
979
980@end
981/* }}} */
982/* Bridge: NSObject {{{ */
983@implementation NSObject (Cycript)
984
f2f0d1d1
JF
985- (id) cy$box {
986 return self;
987}
988
88c6482c 989- (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
95221eed 990 return NULL;
3c1c3635 991} CYObjectiveCatch }
365abb0a
JF
992
993- (JSType) cy$JSType {
994 return kJSTypeObject;
995}
996
997- (NSObject *) cy$toJSON:(NSString *)key {
998 return [self description];
999}
1000
1001- (NSString *) cy$toCYON {
1002 return [[self cy$toJSON:@""] cy$toCYON];
1003}
1004
365abb0a
JF
1005- (bool) cy$hasProperty:(NSString *)name {
1006 return false;
1007}
1008
1009- (NSObject *) cy$getProperty:(NSString *)name {
1010 return nil;
1011}
1012
1013- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1014 return false;
1015}
1016
1017- (bool) cy$deleteProperty:(NSString *)name {
1018 return false;
1019}
1020
8665da0c 1021- (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
d3760804
JF
1022}
1023
3e264692
JF
1024+ (bool) cy$hasImplicitProperties {
1025 return true;
1026}
1027
365abb0a
JF
1028@end
1029/* }}} */
1030/* Bridge: NSProxy {{{ */
1031@implementation NSProxy (Cycript)
1032
1033- (NSObject *) cy$toJSON:(NSString *)key {
1034 return [self description];
1035}
1036
1037- (NSString *) cy$toCYON {
1038 return [[self cy$toJSON:@""] cy$toCYON];
1039}
c1582939 1040
365abb0a
JF
1041@end
1042/* }}} */
1043/* Bridge: NSString {{{ */
107e3ed0 1044@implementation NSString (Cycript)
62ca2b82 1045
f2f0d1d1
JF
1046- (id) cy$box {
1047 return [[self copy] autorelease];
1048}
1049
b4aa79af
JF
1050- (JSType) cy$JSType {
1051 return kJSTypeString;
1052}
1053
1054- (NSObject *) cy$toJSON:(NSString *)key {
1055 return self;
1056}
1057
3c1c3635
JF
1058- (NSString *) cy$toCYON {
1059 std::ostringstream str;
5b1f57ee 1060 str << '@';
3c1c3635
JF
1061 CYUTF8String string(CYCastUTF8String(self));
1062 CYStringify(str, string.data, string.size);
1063 std::string value(str.str());
1064 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1065}
b09da87b 1066
6aa16f29
JF
1067- (bool) cy$hasProperty:(NSString *)name {
1068 if ([name isEqualToString:@"length"])
1069 return true;
1070
1071 size_t index(CYGetIndex(name));
1072 if (index == _not(size_t) || index >= [self length])
1073 return [super cy$hasProperty:name];
1074 else
1075 return true;
1076}
1077
1078- (NSObject *) cy$getProperty:(NSString *)name {
1079 if ([name isEqualToString:@"length"]) {
1080 NSUInteger count([self length]);
1081#ifdef __APPLE__
1082 return [NSNumber numberWithUnsignedInteger:count];
1083#else
1084 return [NSNumber numberWithUnsignedInt:count];
1085#endif
1086 }
1087
1088 size_t index(CYGetIndex(name));
1089 if (index == _not(size_t) || index >= [self length])
1090 return [super cy$getProperty:name];
1091 else
1092 return [self substringWithRange:NSMakeRange(index, 1)];
1093}
1094
1095- (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1096 [super cy$getPropertyNames:names inContext:context];
1097
1098 for (size_t index(0), length([self length]); index != length; ++index) {
1099 char name[32];
1100 sprintf(name, "%zu", index);
1101 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1102 }
1103}
1104
1105// XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1106+ (bool) cy$hasImplicitProperties {
1107 return false;
1108}
1109
88c6482c 1110- (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
95221eed
JF
1111 return CYCastJSValue(context, CYJSString(context, self));
1112} CYObjectiveCatch }
1113
3c1c3635
JF
1114@end
1115/* }}} */
1116/* Bridge: WebUndefined {{{ */
1117@implementation WebUndefined (Cycript)
b09da87b 1118
3c1c3635
JF
1119- (JSType) cy$JSType {
1120 return kJSTypeUndefined;
b09da87b
JF
1121}
1122
3c1c3635
JF
1123- (NSObject *) cy$toJSON:(NSString *)key {
1124 return self;
b09da87b 1125}
3c1c3635
JF
1126
1127- (NSString *) cy$toCYON {
1128 return @"undefined";
c1582939
JF
1129}
1130
88c6482c 1131- (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
3c1c3635
JF
1132 return CYJSUndefined(context);
1133} CYObjectiveCatch }
1134
1135@end
1136/* }}} */
1137
cacd1a88 1138static bool CYIsClass(id self) {
aabea98c 1139#ifdef __APPLE__
cacd1a88
JF
1140 // XXX: this is a lame object_isClass
1141 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
aabea98c
JF
1142#else
1143 return GSObjCIsClass(self);
1144#endif
cacd1a88
JF
1145}
1146
1147Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1148 id self(CYCastNSObject(pool, context, value));
1149 if (CYIsClass(self))
1150 return (Class) self;
37954781 1151 throw CYJSError(context, "got something that is not a Class");
cacd1a88
JF
1152 return NULL;
1153}
1154
aabea98c 1155NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
b09da87b 1156 CYPool pool;
62ca2b82
JF
1157 size_t size(JSPropertyNameArrayGetCount(names));
1158 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1159 for (size_t index(0); index != size; ++index)
aabea98c 1160 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
62ca2b82
JF
1161 return array;
1162}
62ca2b82 1163
ba4fa42f 1164JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
f7c38a29
JF
1165 if (value == nil)
1166 return CYJSNull(context);
f7c38a29
JF
1167 else
1168 return CYMakeInstance(context, value, false);
7c6c5b0a 1169} CYPoolCatch(NULL) return /*XXX*/ NULL; }
af4272e6 1170
b21525c7 1171@implementation CYJSObject
62ca2b82 1172
3c1c3635 1173- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
62ca2b82
JF
1174 if ((self = [super init]) != nil) {
1175 object_ = object;
bc60fb46 1176 context_ = CYGetJSContext(context);
54e3490b 1177 JSGlobalContextRetain(context_);
75b0a457 1178 JSValueProtect(context_, object_);
62ca2b82 1179 } return self;
3c1c3635 1180} CYObjectiveCatch }
62ca2b82 1181
3c1c3635 1182- (void) dealloc { CYObjectiveTry {
75b0a457 1183 JSValueUnprotect(context_, object_);
54e3490b 1184 JSGlobalContextRelease(context_);
75b0a457 1185 [super dealloc];
3c1c3635 1186} CYObjectiveCatch }
75b0a457 1187
3c1c3635 1188- (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
00b9328f 1189 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
b4aa79af
JF
1190 if (!CYIsCallable(context_, toJSON))
1191 return [super cy$toJSON:key];
1192 else {
1193 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1194 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1195 // XXX: do I really want an NSNull here?!
1196 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1197 }
3c1c3635 1198} CYObjectiveCatch }
b4aa79af 1199
3c1c3635 1200- (NSString *) cy$toCYON { CYObjectiveTry {
af4272e6
JF
1201 CYPool pool;
1202 JSValueRef exception(NULL);
1203 const char *cyon(CYPoolCCYON(pool, context_, object_));
1204 CYThrow(context_, exception);
8aa3e970
JF
1205 if (cyon == NULL)
1206 return [super cy$toCYON];
1207 else
1208 return [NSString stringWithUTF8String:cyon];
3c1c3635 1209} CYObjectiveCatch }
b4aa79af 1210
3c1c3635 1211- (NSUInteger) count { CYObjectiveTry {
62ca2b82
JF
1212 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1213 size_t size(JSPropertyNameArrayGetCount(names));
1214 JSPropertyNameArrayRelease(names);
1215 return size;
3c1c3635 1216} CYObjectiveCatch }
62ca2b82 1217
3c1c3635 1218- (id) objectForKey:(id)key { CYObjectiveTry {
0226d428 1219 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
d0a00196
JF
1220 if (JSValueIsUndefined(context_, value))
1221 return nil;
1222 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
3c1c3635 1223} CYObjectiveCatch }
62ca2b82 1224
3c1c3635 1225- (NSEnumerator *) keyEnumerator { CYObjectiveTry {
62ca2b82 1226 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
ec599edf 1227 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
62ca2b82
JF
1228 JSPropertyNameArrayRelease(names);
1229 return enumerator;
3c1c3635 1230} CYObjectiveCatch }
62ca2b82 1231
3c1c3635 1232- (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
0226d428 1233 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
3c1c3635 1234} CYObjectiveCatch }
62ca2b82 1235
3c1c3635 1236- (void) removeObjectForKey:(id)key { CYObjectiveTry {
62ca2b82 1237 JSValueRef exception(NULL);
0226d428 1238 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
62ca2b82 1239 CYThrow(context_, exception);
3c1c3635 1240} CYObjectiveCatch }
62ca2b82
JF
1241
1242@end
1243
b21525c7 1244@implementation CYJSArray
c1582939 1245
4ee70134
JF
1246- (NSString *) cy$toCYON {
1247 CYPool pool;
1248 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context_, object_)];
1249}
1250
3c1c3635 1251- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
c1582939
JF
1252 if ((self = [super init]) != nil) {
1253 object_ = object;
bc60fb46 1254 context_ = CYGetJSContext(context);
54e3490b 1255 JSGlobalContextRetain(context_);
75b0a457 1256 JSValueProtect(context_, object_);
c1582939 1257 } return self;
3c1c3635 1258} CYObjectiveCatch }
c1582939 1259
3c1c3635 1260- (void) dealloc { CYObjectiveTry {
75b0a457 1261 JSValueUnprotect(context_, object_);
54e3490b 1262 JSGlobalContextRelease(context_);
75b0a457 1263 [super dealloc];
3c1c3635 1264} CYObjectiveCatch }
75b0a457 1265
3c1c3635 1266- (NSUInteger) count { CYObjectiveTry {
07db5f4d 1267 return CYArrayLength(context_, object_);
3c1c3635 1268} CYObjectiveCatch }
c1582939 1269
3c1c3635 1270- (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
9a2db8b2
JF
1271 size_t bounds([self count]);
1272 if (index >= bounds)
1273 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
62ca2b82
JF
1274 JSValueRef exception(NULL);
1275 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1276 CYThrow(context_, exception);
478d4ed0 1277 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
3c1c3635 1278} CYObjectiveCatch }
c1582939 1279
3c1c3635 1280- (void) addObject:(id)object { CYObjectiveTry {
07db5f4d 1281 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
3c1c3635 1282} CYObjectiveCatch }
faf69207 1283
3c1c3635 1284- (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
9a2db8b2
JF
1285 size_t bounds([self count] + 1);
1286 if (index >= bounds)
1287 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
faf69207
JF
1288 JSValueRef exception(NULL);
1289 JSValueRef arguments[3];
1290 arguments[0] = CYCastJSValue(context_, index);
1291 arguments[1] = CYCastJSValue(context_, 0);
ba4fa42f 1292 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
9772d9bf 1293 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
498c3570 1294 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
3c1c3635
JF
1295 CYThrow(context_, exception);
1296} CYObjectiveCatch }
af4272e6 1297
3c1c3635
JF
1298- (void) removeLastObject { CYObjectiveTry {
1299 JSValueRef exception(NULL);
9772d9bf 1300 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
498c3570 1301 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
3c1c3635
JF
1302 CYThrow(context_, exception);
1303} CYObjectiveCatch }
af4272e6 1304
3c1c3635
JF
1305- (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1306 size_t bounds([self count]);
1307 if (index >= bounds)
1308 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1309 JSValueRef exception(NULL);
1310 JSValueRef arguments[2];
1311 arguments[0] = CYCastJSValue(context_, index);
1312 arguments[1] = CYCastJSValue(context_, 1);
9772d9bf 1313 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
498c3570 1314 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
3c1c3635
JF
1315 CYThrow(context_, exception);
1316} CYObjectiveCatch }
1317
1318- (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1319 size_t bounds([self count]);
1320 if (index >= bounds)
1321 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
ba4fa42f 1322 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
3c1c3635
JF
1323} CYObjectiveCatch }
1324
1325@end
af4272e6 1326
c44063e0
JF
1327// XXX: inherit from or replace with CYJSObject
1328@interface CYInternal : NSObject {
54e3490b 1329 JSGlobalContextRef context_;
61933e16 1330 JSObjectRef object_;
c44063e0 1331}
61933e16 1332
c44063e0 1333@end
61933e16 1334
c44063e0 1335@implementation CYInternal
61933e16 1336
c44063e0
JF
1337- (void) dealloc {
1338 JSValueUnprotect(context_, object_);
54e3490b 1339 JSGlobalContextRelease(context_);
c44063e0
JF
1340 [super dealloc];
1341}
61933e16 1342
c44063e0
JF
1343- (id) initInContext:(JSContextRef)context {
1344 if ((self = [super init]) != nil) {
1345 context_ = CYGetJSContext(context);
54e3490b 1346 JSGlobalContextRetain(context_);
c44063e0
JF
1347 } return self;
1348}
61933e16 1349
c44063e0
JF
1350- (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1351 if (object_ == NULL)
1352 return false;
61933e16 1353
c44063e0
JF
1354 return JSObjectHasProperty(context, object_, name);
1355}
61933e16 1356
c44063e0
JF
1357- (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1358 if (object_ == NULL)
1359 return NULL;
1360
1361 return CYGetProperty(context, object_, name);
1362}
1363
1364- (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1365 @synchronized (self) {
1366 if (object_ == NULL) {
1367 object_ = JSObjectMake(context, NULL, NULL);
1368 JSValueProtect(context, object_);
1369 }
7b184c00
JF
1370 }
1371
c44063e0
JF
1372 CYSetProperty(context, object_, name, value);
1373}
1374
1375+ (CYInternal *) get:(id)object {
1376 if ($objc_getAssociatedObject == NULL)
1377 return nil;
1378
1379 @synchronized (object) {
1380 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1381 return internal;
61933e16
JF
1382 }
1383
c44063e0
JF
1384 return nil;
1385}
1386
1387+ (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1388 if ($objc_getAssociatedObject == NULL)
1389 return nil;
1390
1391 @synchronized (object) {
1392 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1393 return internal;
1394
1395 if ($objc_setAssociatedObject == NULL)
1396 return nil;
1397
1398 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1399 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1400 return internal;
61933e16 1401 }
c44063e0
JF
1402
1403 return nil;
1404}
1405
1406@end
61933e16 1407
534fb6da 1408static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
9e562cfc
JF
1409 Selector_privateData *internal(new Selector_privateData(sel));
1410 return JSObjectMake(context, Selector_, internal);
dea834b0 1411}
b09da87b 1412
534fb6da 1413static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
4afefdd9 1414 if (JSValueIsObjectOfClass(context, value, Selector_)) {
9e562cfc
JF
1415 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1416 return reinterpret_cast<SEL>(internal->value_);
4afefdd9
JF
1417 } else
1418 return CYCastPointer<SEL>(context, value);
1419}
1420
b64ab4da 1421void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
3c1c3635 1422 return (void *) [[NSAutoreleasePool alloc] init];
ea840434 1423} CYSadCatch(NULL) }
ea2d184c 1424
b64ab4da 1425void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
3c1c3635 1426 return [(NSAutoreleasePool *) handle release];
ea840434 1427} CYSadCatch() }
ea2d184c 1428
f0d43c71 1429JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
3c1c3635
JF
1430 if (name == "nil")
1431 return Instance::Make(context, nil);
1432 if (Class _class = objc_getClass(name.data))
1433 return CYMakeInstance(context, _class, true);
64b8d29f
JF
1434 if (Protocol *protocol = objc_getProtocol(name.data))
1435 return CYMakeInstance(context, protocol, true);
3c1c3635 1436 return NULL;
7c6c5b0a 1437} CYPoolCatch(NULL) return /*XXX*/ NULL; }
d3760804 1438
b64ab4da 1439static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
d3760804 1440 ffi_call(cif, function, value, values);
ea840434 1441} CYSadCatch() }
ea2d184c 1442
b64ab4da 1443static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
3c1c3635 1444 switch (type->primitive) {
ecf94af8
JF
1445 // XXX: do something epic about blocks
1446 case sig::block_P:
ea2d184c
JF
1447 case sig::object_P:
1448 case sig::typename_P:
b09da87b 1449 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
7ba62cfd
JF
1450 break;
1451
ea2d184c 1452 case sig::selector_P:
7ba62cfd
JF
1453 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1454 break;
ea2d184c 1455
bd17e6f3 1456 default:
3c1c3635 1457 return false;
ea2d184c 1458 }
ea2d184c 1459
3c1c3635 1460 return true;
ea840434 1461} CYSadCatch(false) }
ea2d184c 1462
f0d43c71 1463static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
ea2d184c 1464 switch (type->primitive) {
ecf94af8
JF
1465 // XXX: do something epic about blocks
1466 case sig::block_P:
3c1c3635 1467 case sig::object_P:
ba4fa42f 1468 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
3c1c3635 1469 JSValueRef value(CYCastJSValue(context, object));
2b52f27e
JF
1470 if (initialize)
1471 [object release];
3c1c3635 1472 return value;
2b52f27e 1473 } else goto null;
dea834b0 1474
b09da87b 1475 case sig::typename_P:
3c1c3635 1476 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
b09da87b 1477
dea834b0
JF
1478 case sig::selector_P:
1479 if (SEL sel = *reinterpret_cast<SEL *>(data))
3c1c3635 1480 return CYMakeSelector(context, sel);
f610e1a0 1481 else goto null;
f610e1a0
JF
1482
1483 null:
3c1c3635 1484 return CYJSNull(context);
bd17e6f3 1485 default:
3c1c3635 1486 return NULL;
ea2d184c 1487 }
7c6c5b0a 1488} CYPoolCatch(NULL) return /*XXX*/ NULL; }
ea2d184c 1489
8a199b13 1490static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
39bb4b6a 1491 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
8a199b13
JF
1492 if (!devoid)
1493 return true;
7c6c5b0a 1494#if OBJC_API_VERSION >= 2
8a199b13
JF
1495 char type[16];
1496 method_getReturnType(method, type, sizeof(type));
b5dd57dc
JF
1497#else
1498 const char *type(method_getTypeEncoding(method));
1499#endif
8a199b13
JF
1500 if (type[0] != 'v')
1501 return true;
1502 }
1503
7b184c00 1504 // XXX: possibly use a more "awesome" check?
8a199b13 1505 return false;
7b184c00
JF
1506}
1507
37954781 1508static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
dc68b74c
JF
1509 if (method != NULL)
1510 return method_getTypeEncoding(method);
856b8cd0
JF
1511
1512 const char *name(sel_getName(sel));
2f51d6ab 1513 size_t length(strlen(name));
856b8cd0 1514
2f51d6ab
JF
1515 char keyed[length + 2];
1516 keyed[0] = '6';
1517 keyed[length + 1] = '\0';
1518 memcpy(keyed + 1, name, length);
dc68b74c 1519
2f51d6ab
JF
1520 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1521 return entry->value_;
dc68b74c 1522
3c1c3635 1523 return NULL;
dc68b74c
JF
1524}
1525
3c1c3635
JF
1526static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1527 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
dc68b74c 1528
3c1c3635 1529 JSContextRef context(internal->context_);
dc68b74c 1530
3c1c3635
JF
1531 size_t count(internal->cif_.nargs);
1532 JSValueRef values[count];
1533
1534 for (size_t index(0); index != count; ++index)
1535 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1536
1537 JSObjectRef _this(CYCastJSObject(context, values[0]));
1538
1539 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1540 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
dc68b74c
JF
1541}
1542
1543static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1544 Message_privateData *internal(new Message_privateData(sel, type, imp));
1545 return JSObjectMake(context, Message_, internal);
1546}
1547
1548static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1549 JSObjectRef function(CYCastJSObject(context, value));
1550 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2fd4c9a9 1551 // XXX: see notes in Library.cpp about needing to leak
dc68b74c
JF
1552 return reinterpret_cast<IMP>(internal->GetValue());
1553}
1554
365abb0a
JF
1555static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1556 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1557 Class _class(internal->GetValue());
1558
1559 CYPool pool;
3c1c3635 1560 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1561
1562 if (SEL sel = sel_getUid(name))
1563 if (class_getInstanceMethod(_class, sel) != NULL)
1564 return true;
1565
1566 return false;
1567}
1568
365abb0a
JF
1569static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1570 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1571 Class _class(internal->GetValue());
1572
1573 CYPool pool;
3c1c3635 1574 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1575
1576 if (SEL sel = sel_getUid(name))
39bb4b6a 1577 if (objc_method *method = class_getInstanceMethod(_class, sel))
dc68b74c
JF
1578 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1579
1580 return NULL;
1581}
1582
365abb0a
JF
1583static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1584 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1585 Class _class(internal->GetValue());
1586
1587 CYPool pool;
3c1c3635 1588 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1589
1590 SEL sel(sel_registerName(name));
1591
39bb4b6a 1592 objc_method *method(class_getInstanceMethod(_class, sel));
dc68b74c
JF
1593
1594 const char *type;
1595 IMP imp;
1596
1597 if (JSValueIsObjectOfClass(context, value, Message_)) {
1598 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1599 type = sig::Unparse(pool, &message->signature_);
1600 imp = reinterpret_cast<IMP>(message->GetValue());
1601 } else {
37954781 1602 type = CYPoolTypeEncoding(pool, context, sel, method);
dc68b74c
JF
1603 imp = CYMakeMessage(context, value, type);
1604 }
1605
1606 if (method != NULL)
1607 method_setImplementation(method, imp);
b5dd57dc
JF
1608 else {
1609#ifdef GNU_RUNTIME
1610 GSMethodList list(GSAllocMethodList(1));
1611 GSAppendMethodToList(list, sel, type, imp, YES);
1612 GSAddMethodList(_class, list, YES);
1613 GSFlushMethodCacheForClass(_class);
1614#else
1615 class_addMethod(_class, sel, imp, type);
1616#endif
1617 }
dc68b74c
JF
1618
1619 return true;
1620}
1621
7c6c5b0a 1622#if 0 && OBJC_API_VERSION < 2
365abb0a
JF
1623static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1624 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1625 Class _class(internal->GetValue());
1626
1627 CYPool pool;
aabea98c 1628 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1629
1630 if (SEL sel = sel_getUid(name))
39bb4b6a 1631 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
dc68b74c
JF
1632 objc_method_list list = {NULL, 1, {method}};
1633 class_removeMethods(_class, &list);
1634 return true;
1635 }
1636
1637 return false;
1638}
1639#endif
1640
365abb0a
JF
1641static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1642 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1643 Class _class(internal->GetValue());
1644
7c6c5b0a 1645#if OBJC_API_VERSION >= 2
dc68b74c 1646 unsigned int size;
39bb4b6a 1647 objc_method **data(class_copyMethodList(_class, &size));
dc68b74c
JF
1648 for (size_t i(0); i != size; ++i)
1649 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1650 free(data);
aabea98c
JF
1651#else
1652 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1653 for (int i(0); i != methods->method_count; ++i)
1654 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1655#endif
dc68b74c
JF
1656}
1657
3e264692
JF
1658static bool CYHasImplicitProperties(Class _class) {
1659 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1660 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1661 return true;
1662 return [_class cy$hasImplicitProperties];
1663}
1664
7b184c00
JF
1665static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1666 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1667 id self(internal->GetValue());
1668
1669 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1670 return true;
1671
c239b9f8 1672 CYPool pool;
aabea98c 1673 NSString *name(CYCastNSString(pool, context, property));
7b184c00 1674
c44063e0
JF
1675 if (CYInternal *internal = [CYInternal get:self])
1676 if ([internal hasProperty:property inContext:context])
7b184c00
JF
1677 return true;
1678
365abb0a
JF
1679 Class _class(object_getClass(self));
1680
7b184c00 1681 CYPoolTry {
365abb0a
JF
1682 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1683 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1684 if ([self cy$hasProperty:name])
1685 return true;
7b184c00
JF
1686 } CYPoolCatch(false)
1687
3c1c3635 1688 const char *string(CYPoolCString(pool, context, name));
7b184c00 1689
aabea98c 1690#ifdef __APPLE__
7b184c00
JF
1691 if (class_getProperty(_class, string) != NULL)
1692 return true;
aabea98c 1693#endif
7b184c00 1694
3e264692
JF
1695 if (CYHasImplicitProperties(_class))
1696 if (SEL sel = sel_getUid(string))
1697 if (CYImplements(self, _class, sel, true))
1698 return true;
7b184c00
JF
1699
1700 return false;
1701}
1702
3c1c3635 1703static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
7b184c00
JF
1704 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1705 id self(internal->GetValue());
1706
1707 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1708 return Internal::Make(context, self, object);
c239b9f8 1709
3c1c3635 1710 CYPool pool;
aabea98c 1711 NSString *name(CYCastNSString(pool, context, property));
c239b9f8 1712
c44063e0
JF
1713 if (CYInternal *internal = [CYInternal get:self])
1714 if (JSValueRef value = [internal getProperty:property inContext:context])
3c1c3635 1715 return value;
c239b9f8 1716
3c1c3635
JF
1717 CYPoolTry {
1718 if (NSObject *data = [self cy$getProperty:name])
1719 return CYCastJSValue(context, data);
1720 } CYPoolCatch(NULL)
c239b9f8 1721
3c1c3635
JF
1722 const char *string(CYPoolCString(pool, context, name));
1723 Class _class(object_getClass(self));
c239b9f8 1724
cbaa5f0f 1725#ifdef __APPLE__
3c1c3635
JF
1726 if (objc_property_t property = class_getProperty(_class, string)) {
1727 PropertyAttributes attributes(property);
1728 SEL sel(sel_registerName(attributes.Getter()));
1729 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1730 }
cbaa5f0f 1731#endif
c239b9f8 1732
3e264692
JF
1733 if (CYHasImplicitProperties(_class))
1734 if (SEL sel = sel_getUid(string))
1735 if (CYImplements(self, _class, sel, true))
1736 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
8953777c 1737
3c1c3635
JF
1738 return NULL;
1739} CYCatch }
c239b9f8 1740
3c1c3635 1741static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
dc68b74c
JF
1742 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1743 id self(internal->GetValue());
1744
c239b9f8
JF
1745 CYPool pool;
1746
aabea98c 1747 NSString *name(CYCastNSString(pool, context, property));
3c1c3635 1748 NSObject *data(CYCastNSObject(pool, context, value));
8953777c 1749
3c1c3635
JF
1750 CYPoolTry {
1751 if ([self cy$setProperty:name to:data])
c239b9f8 1752 return true;
3c1c3635 1753 } CYPoolCatch(NULL)
dc68b74c 1754
3c1c3635 1755 const char *string(CYPoolCString(pool, context, name));
c239b9f8
JF
1756 Class _class(object_getClass(self));
1757
8aa3e970 1758#ifdef __APPLE__
3c1c3635
JF
1759 if (objc_property_t property = class_getProperty(_class, string)) {
1760 PropertyAttributes attributes(property);
1761 if (const char *setter = attributes.Setter()) {
1762 SEL sel(sel_registerName(setter));
1763 JSValueRef arguments[1] = {value};
1764 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
9b5527f0
JF
1765 return true;
1766 }
3c1c3635 1767 }
b24eb750 1768#endif
c239b9f8 1769
3c1c3635 1770 size_t length(strlen(string));
9e20b0b7 1771
3c1c3635 1772 char set[length + 5];
f33b048a 1773
3c1c3635
JF
1774 set[0] = 's';
1775 set[1] = 'e';
1776 set[2] = 't';
f33b048a 1777
3c1c3635
JF
1778 if (string[0] != '\0') {
1779 set[3] = toupper(string[0]);
1780 memcpy(set + 4, string + 1, length - 1);
e0dc20ec 1781 }
bd17e6f3 1782
3c1c3635
JF
1783 set[length + 3] = ':';
1784 set[length + 4] = '\0';
9b5527f0 1785
3c1c3635
JF
1786 if (SEL sel = sel_getUid(set))
1787 if (CYImplements(self, _class, sel, false)) {
1788 JSValueRef arguments[1] = {value};
1789 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
975cde38 1790 return true;
3c1c3635 1791 }
f37b3d2b 1792
c44063e0
JF
1793 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1794 [internal setProperty:property toValue:value inContext:context];
f37b3d2b 1795 return true;
3c1c3635 1796 }
f37b3d2b 1797
3c1c3635
JF
1798 return false;
1799} CYCatch }
9b5527f0 1800
3c1c3635
JF
1801static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1802 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1803 id self(internal->GetValue());
9b5527f0 1804
3c1c3635 1805 CYPoolTry {
aabea98c 1806 NSString *name(CYCastNSString(NULL, context, property));
3c1c3635
JF
1807 return [self cy$deleteProperty:name];
1808 } CYPoolCatch(NULL)
7c6c5b0a 1809} CYCatch return /*XXX*/ NULL; }
9b5527f0 1810
ec18fc0e
JF
1811static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1812 const char *name(sel_getName(method_getName(method)));
1813 if (strchr(name, ':') != NULL)
1814 return;
1815
1816 const char *type(method_getTypeEncoding(method));
1817 if (type == NULL || *type == '\0' || *type == 'v')
1818 return;
1819
1820 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1821}
1822
3c1c3635
JF
1823static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1824 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1825 id self(internal->GetValue());
9b5527f0 1826
3c1c3635
JF
1827 CYPool pool;
1828 Class _class(object_getClass(self));
9b5527f0 1829
3c1c3635
JF
1830#ifdef __APPLE__
1831 {
1832 unsigned int size;
1833 objc_property_t *data(class_copyPropertyList(_class, &size));
1834 for (size_t i(0); i != size; ++i)
1835 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1836 free(data);
1837 }
1838#endif
d3760804 1839
326a9dba
JF
1840 if (CYHasImplicitProperties(_class))
1841 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
ec18fc0e 1842#if OBJC_API_VERSION >= 2
326a9dba
JF
1843 unsigned int size;
1844 objc_method **data(class_copyMethodList(current, &size));
1845 for (size_t i(0); i != size; ++i)
1846 Instance_getPropertyNames_message(names, data[i]);
1847 free(data);
ec18fc0e 1848#else
326a9dba
JF
1849 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1850 for (int i(0); i != methods->method_count; ++i)
1851 Instance_getPropertyNames_message(names, &methods->method_list[i]);
ec18fc0e 1852#endif
326a9dba 1853 }
ec18fc0e 1854
d3760804
JF
1855 CYPoolTry {
1856 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
8665da0c
JF
1857 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1858 [self cy$getPropertyNames:names inContext:context];
d3760804 1859 } CYPoolCatch()
9b5527f0
JF
1860}
1861
3c1c3635
JF
1862static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1863 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1864 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1865 return value;
1866} CYCatch }
bd17e6f3 1867
aaa3cd1e
JF
1868static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1869 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1870 id self(internal->GetValue());
1871
1872 if (![self isKindOfClass:NSBlock_])
1873 CYThrow("non-NSBlock object is not a function");
1874
1875 struct BlockDescriptor1 {
1876 unsigned long int reserved;
1877 unsigned long int size;
1878 };
1879
1880 struct BlockDescriptor2 {
1881 void (*copy_helper)(void *dst, void *src);
1882 void (*dispose_helper)(void *src);
1883 };
1884
1885 struct BlockDescriptor3 {
1886 const char *signature;
1887 const char *layout;
1888 };
1889
1890 struct BlockLiteral {
1891 Class isa;
1892 int flags;
1893 int reserved;
1894 void (*invoke)(void *, ...);
1895 void *descriptor;
1896 } *literal = reinterpret_cast<BlockLiteral *>(self);
1897
1898 enum {
1899 BLOCK_DEALLOCATING = 0x0001,
1900 BLOCK_REFCOUNT_MASK = 0xfffe,
1901 BLOCK_NEEDS_FREE = 1 << 24,
1902 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
1903 BLOCK_HAS_CTOR = 1 << 26,
1904 BLOCK_IS_GC = 1 << 27,
1905 BLOCK_IS_GLOBAL = 1 << 28,
1906 BLOCK_HAS_STRET = 1 << 29,
1907 BLOCK_HAS_SIGNATURE = 1 << 30,
1908 };
1909
1910 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1911 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1912 descriptor += sizeof(BlockDescriptor1);
1913 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1914 descriptor += sizeof(BlockDescriptor2);
1915 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1916
1917 if (const char *type = descriptor3->signature) {
1918 CYPool pool;
1919
1920 void *setup[1];
1921 setup[0] = &self;
1922
1923 sig::Signature signature;
1924 sig::Parse(pool, &signature, type, &Structor_);
1925
1926 ffi_cif cif;
1927 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1928
1929 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1930 return CYCallFunction(pool, context, 1, setup, count, arguments, false, exception, &signature, &cif, function);
1931 }
1932 }
1933
1934 if (count != 0)
1935 CYThrow("NSBlock without signature field passed arguments");
1936
1937 CYPoolTry {
1938 [self invoke];
1939 } CYPoolCatch(NULL);
1940
1941 return NULL;
1942} CYCatch }
1943
3c1c3635
JF
1944static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1945 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1946 Class _class(internal->GetValue());
1947 if (!CYIsClass(_class))
1948 return false;
bd17e6f3 1949
97343f31 1950 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
3c1c3635
JF
1951 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1952 // XXX: this isn't always safe
1953 return [linternal->GetValue() isKindOfClass:_class];
1954 }
ff783f8c 1955
3c1c3635
JF
1956 return false;
1957} CYCatch }
bd17e6f3 1958
f2f0d1d1
JF
1959static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1960 if (count == 0)
1961 throw CYJSError(context, "incorrect number of arguments to Instance");
1962 CYPool pool;
1963 id value(CYCastNSObject(pool, context, arguments[0]));
1964 if (value == nil)
1965 value = [NSNull null];
1966 return CYCastJSValue(context, [value cy$box]);
1967} CYCatch }
1968
3c1c3635
JF
1969static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1970 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
f33b048a 1971 CYPool pool;
bd17e6f3 1972
3c1c3635
JF
1973 id self(internal->GetValue());
1974 const char *name(CYPoolCString(pool, context, property));
520c130f 1975
3c1c3635 1976 if (object_getInstanceVariable(self, name, NULL) != NULL)
bd17e6f3 1977 return true;
3c1c3635
JF
1978
1979 return false;
bd17e6f3
JF
1980}
1981
3c1c3635
JF
1982static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1983 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1984 CYPool pool;
930aa21b 1985
3c1c3635
JF
1986 id self(internal->GetValue());
1987 const char *name(CYPoolCString(pool, context, property));
f33b048a 1988
aabea98c 1989 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
3c1c3635 1990 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
b81e7fb6 1991 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
3c1c3635
JF
1992 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1993 }
f33b048a 1994
3c1c3635
JF
1995 return NULL;
1996} CYCatch }
283e7e33 1997
3c1c3635
JF
1998static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1999 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2000 CYPool pool;
283e7e33 2001
3c1c3635
JF
2002 id self(internal->GetValue());
2003 const char *name(CYPoolCString(pool, context, property));
283e7e33 2004
aabea98c 2005 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
3c1c3635
JF
2006 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2007 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2008 return true;
283e7e33 2009 }
f33b048a 2010
3c1c3635
JF
2011 return false;
2012} CYCatch }
85a33bf5 2013
3c1c3635
JF
2014static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2015 if (Class super = class_getSuperclass(_class))
2016 Internal_getPropertyNames_(super, names);
ea2d184c 2017
7c6c5b0a 2018#if OBJC_API_VERSION >= 2
3c1c3635 2019 unsigned int size;
aabea98c 2020 objc_ivar **data(class_copyIvarList(_class, &size));
3c1c3635
JF
2021 for (size_t i(0); i != size; ++i)
2022 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2023 free(data);
b5dd57dc
JF
2024#else
2025 if (objc_ivar_list *ivars = _class->ivars)
2026 for (int i(0); i != ivars->ivar_count; ++i)
2027 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2028#endif
3c1c3635
JF
2029}
2030
2031static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2032 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2033 CYPool pool;
ea2d184c 2034
3c1c3635
JF
2035 id self(internal->GetValue());
2036 Class _class(object_getClass(self));
7ba62cfd 2037
3c1c3635 2038 Internal_getPropertyNames_(_class, names);
7ba62cfd 2039}
ea2d184c 2040
3c1c3635
JF
2041static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2042 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2043 return internal->GetOwner();
c239b9f8
JF
2044}
2045
3c1c3635
JF
2046static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2047 CYPool pool;
aabea98c 2048 NSString *name(CYCastNSString(pool, context, property));
3c1c3635
JF
2049 if (Class _class = NSClassFromString(name))
2050 return CYMakeInstance(context, _class, true);
2051 return NULL;
2052} CYCatch }
2053
c239b9f8 2054static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
aabea98c 2055#ifdef __APPLE__
c239b9f8
JF
2056 size_t size(objc_getClassList(NULL, 0));
2057 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2058
2059 get:
2060 size_t writ(objc_getClassList(data, size));
2061 if (size < writ) {
2062 size = writ;
2063 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2064 data = copy;
2065 goto get;
2066 } else goto done;
2067 }
2068
2069 for (size_t i(0); i != writ; ++i)
2070 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2071
2072 done:
2073 free(data);
aabea98c
JF
2074#else
2075 void *state(NULL);
2076 while (Class _class = objc_next_class(&state))
2077 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2078#endif
c239b9f8
JF
2079}
2080
7c6c5b0a 2081#if OBJC_API_VERSION >= 2
3c1c3635 2082static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
c239b9f8
JF
2083 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2084
3c1c3635
JF
2085 CYPool pool;
2086 const char *name(CYPoolCString(pool, context, property));
2087 unsigned int size;
2088 const char **data(objc_copyClassNamesForImage(internal, &size));
2089 JSValueRef value;
2090 for (size_t i(0); i != size; ++i)
2091 if (strcmp(name, data[i]) == 0) {
2092 if (Class _class = objc_getClass(name)) {
2093 value = CYMakeInstance(context, _class, true);
2094 goto free;
2095 } else
2096 break;
2097 }
2098 value = NULL;
2099 free:
2100 free(data);
2101 return value;
2102} CYCatch }
c239b9f8
JF
2103
2104static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2105 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2106 unsigned int size;
2107 const char **data(objc_copyClassNamesForImage(internal, &size));
2108 for (size_t i(0); i != size; ++i)
2109 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2110 free(data);
2111}
2112
3c1c3635
JF
2113static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2114 CYPool pool;
2115 const char *name(CYPoolCString(pool, context, property));
2116 unsigned int size;
2117 const char **data(objc_copyImageNames(&size));
2118 for (size_t i(0); i != size; ++i)
2119 if (strcmp(name, data[i]) == 0) {
2120 name = data[i];
2121 goto free;
2122 }
2123 name = NULL;
2124 free:
2125 free(data);
2126 if (name == NULL)
2127 return NULL;
2128 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2129 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2130 return value;
2131} CYCatch }
c239b9f8
JF
2132
2133static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2134 unsigned int size;
2135 const char **data(objc_copyImageNames(&size));
2136 for (size_t i(0); i != size; ++i)
2137 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2138 free(data);
2139}
aabea98c 2140#endif
c239b9f8 2141
3c1c3635
JF
2142static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2143 CYPool pool;
aabea98c
JF
2144 const char *name(CYPoolCString(pool, context, property));
2145 if (Protocol *protocol = objc_getProtocol(name))
3c1c3635
JF
2146 return CYMakeInstance(context, protocol, true);
2147 return NULL;
2148} CYCatch }
c239b9f8
JF
2149
2150static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
7c6c5b0a 2151#if OBJC_API_VERSION >= 2
c239b9f8
JF
2152 unsigned int size;
2153 Protocol **data(objc_copyProtocolList(&size));
2154 for (size_t i(0); i != size; ++i)
2155 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2156 free(data);
aabea98c
JF
2157#else
2158 // XXX: fix this!
2159#endif
c239b9f8 2160}
707bcb93 2161
26ef7a82
JF
2162static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2163 CYPool pool;
2164 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2165 if (name == "nil")
2166 return Instance::Make(context, nil);
2167 return NULL;
2168} CYCatch }
2169
2170static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2171 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2172}
2173
aabea98c 2174#ifdef __APPLE__
534fb6da 2175static bool stret(ffi_type *ffi_type) {
04450da0
JF
2176 return ffi_type->type == FFI_TYPE_STRUCT && (
2177 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2178 struct_forward_array[ffi_type->size] != 0
2179 );
2180}
aabea98c 2181#endif
b09da87b 2182
3c1c3635 2183JSValueRef 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 2184 const char *type;
ea2d184c 2185
cacd1a88
JF
2186 if (_class == NULL)
2187 _class = object_getClass(self);
2188
aabea98c
JF
2189 IMP imp;
2190
2191 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2192 imp = method_getImplementation(method);
4afefdd9 2193 type = method_getTypeEncoding(method);
aabea98c
JF
2194 } else {
2195 imp = NULL;
2196
3c1c3635
JF
2197 CYPoolTry {
2198 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2199 if (method == nil)
37954781 2200 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3c1c3635
JF
2201 type = CYPoolCString(pool, context, [method _typeString]);
2202 } CYPoolCatch(NULL)
4afefdd9
JF
2203 }
2204
2205 void *setup[2];
f623c5d8 2206 setup[0] = &self;
4afefdd9
JF
2207 setup[1] = &_cmd;
2208
2209 sig::Signature signature;
f33b048a 2210 sig::Parse(pool, &signature, type, &Structor_);
4afefdd9 2211
0add079d
JF
2212 size_t used(count + 3);
2213 if (used > signature.count) {
2214 sig::Element *elements(new (pool) sig::Element[used]);
2215 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2216
2217 for (size_t index(signature.count); index != used; ++index) {
2218 sig::Element *element(&elements[index]);
2219 element->name = NULL;
2220 element->offset = _not(size_t);
2221
2222 sig::Type *type(new (pool) sig::Type);
2223 memset(type, 0, sizeof(*type));
2224 type->primitive = sig::object_P;
2225 element->type = type;
2226 }
2227
2228 signature.elements = elements;
2229 signature.count = used;
2230 }
2231
4afefdd9
JF
2232 ffi_cif cif;
2233 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2234
f623c5d8 2235 if (imp == NULL) {
aabea98c
JF
2236#ifdef __APPLE__
2237 if (stret(cif.rtype))
2238 imp = class_getMethodImplementation_stret(_class, _cmd);
2239 else
2240 imp = class_getMethodImplementation(_class, _cmd);
2241#else
f623c5d8 2242 objc_super super = {self, _class};
aabea98c
JF
2243 imp = objc_msg_lookup_super(&super, _cmd);
2244#endif
f623c5d8 2245 }
aabea98c
JF
2246
2247 void (*function)() = reinterpret_cast<void (*)()>(imp);
2b52f27e 2248 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3c1c3635 2249} CYCatch }
367eebb1 2250
3c1c3635
JF
2251static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2252 if (count < 2)
37954781 2253 throw CYJSError(context, "too few arguments to objc_msgSend");
367eebb1 2254
478d4ed0
JF
2255 CYPool pool;
2256
2b52f27e
JF
2257 bool uninitialized;
2258
4afefdd9
JF
2259 id self;
2260 SEL _cmd;
cacd1a88 2261 Class _class;
4afefdd9 2262
3c1c3635
JF
2263 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2264 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2265 self = internal->GetValue();
2266 _class = internal->class_;;
2267 uninitialized = false;
97343f31 2268 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
3c1c3635
JF
2269 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2270 self = internal->GetValue();
2271 _class = nil;
2272 uninitialized = internal->IsUninitialized();
2273 if (uninitialized)
2274 internal->value_ = nil;
2275 } else {
2276 self = CYCastNSObject(pool, context, arguments[0]);
2277 _class = nil;
2278 uninitialized = false;
2279 }
2b52f27e 2280
3c1c3635
JF
2281 if (self == nil)
2282 return CYJSNull(context);
7ba62cfd 2283
3c1c3635 2284 _cmd = CYCastSEL(context, arguments[1]);
ea2d184c 2285
cacd1a88 2286 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
3c1c3635 2287} CYCatch }
7ba62cfd 2288
dea834b0
JF
2289static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2290 JSValueRef setup[count + 2];
2291 setup[0] = _this;
2292 setup[1] = object;
4afefdd9 2293 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
dea834b0
JF
2294 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2295}
2296
dc68b74c
JF
2297static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2298 CYPool pool;
2299 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2300
2301 // XXX: handle Instance::Uninitialized?
2302 id self(CYCastNSObject(pool, context, _this));
2303
2304 void *setup[2];
2305 setup[0] = &self;
2306 setup[1] = &internal->sel_;
2307
2308 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2309}
2310
3c1c3635
JF
2311static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2312 if (count != 2)
37954781 2313 throw CYJSError(context, "incorrect number of arguments to Super constructor");
4afefdd9 2314 CYPool pool;
3c1c3635
JF
2315 id self(CYCastNSObject(pool, context, arguments[0]));
2316 Class _class(CYCastClass(pool, context, arguments[1]));
2317 return cy::Super::Make(context, self, _class);
2318} CYCatch }
bce8339b 2319
3c1c3635
JF
2320static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2321 if (count != 1)
37954781
JF
2322 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2323 CYPool pool;
2324 const char *name(CYPoolCString(pool, context, arguments[0]));
3c1c3635
JF
2325 return CYMakeSelector(context, sel_registerName(name));
2326} CYCatch }
7b184c00 2327
3c1c3635
JF
2328static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2329 if (count > 1)
37954781 2330 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
3c1c3635 2331 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
15024d7e 2332 return CYMakeInstance(context, self, false);
3c1c3635 2333} CYCatch }
ea2d184c 2334
534fb6da 2335static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
61933e16
JF
2336 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2337 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
04450da0
JF
2338}
2339
7b184c00
JF
2340static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2341 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2342 Type_privateData *typical(internal->GetType());
2343
2344 sig::Type *type;
2345 ffi_type *ffi;
2346
2347 if (typical == NULL) {
2348 type = NULL;
2349 ffi = NULL;
2350 } else {
2351 type = typical->type_;
2352 ffi = typical->ffi_;
2353 }
2354
53ba31e9 2355 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
7b184c00 2356}
4afefdd9 2357
dc68b74c
JF
2358static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2359 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
ec599edf 2360 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
dc68b74c
JF
2361}
2362
2f1295ff 2363static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
365abb0a
JF
2364 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2365 id self(internal->GetValue());
2366 if (!CYIsClass(self))
2367 return CYJSUndefined(context);
3c1c3635
JF
2368 return CYGetClassPrototype(context, self);
2369} CYCatch }
365abb0a
JF
2370
2371static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
dc68b74c
JF
2372 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2373 id self(internal->GetValue());
b5dd57dc 2374 if (!CYIsClass(self))
dc68b74c 2375 return CYJSUndefined(context);
b5dd57dc 2376 return Messages::Make(context, (Class) self);
dc68b74c
JF
2377}
2378
3c1c3635 2379static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
97343f31 2380 if (!JSValueIsObjectOfClass(context, _this, Instance_))
365abb0a
JF
2381 return NULL;
2382
7b184c00 2383 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
8665da0c 2384 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
3c1c3635 2385} CYCatch }
7b184c00 2386
3c1c3635 2387static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
97343f31 2388 if (!JSValueIsObjectOfClass(context, _this, Instance_))
365abb0a
JF
2389 return NULL;
2390
7b184c00
JF
2391 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2392
3c1c3635 2393 CYPoolTry {
b5dd57dc
JF
2394 NSString *key;
2395 if (count == 0)
2396 key = nil;
2397 else
2398 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
3c1c3635 2399 // XXX: check for support of cy$toJSON?
8665da0c 2400 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
3c1c3635 2401 } CYPoolCatch(NULL)
7c6c5b0a 2402} CYCatch return /*XXX*/ NULL; }
b4aa79af 2403
c30687a7 2404static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
97343f31 2405 if (!JSValueIsObjectOfClass(context, _this, Instance_))
c30687a7
JF
2406 return NULL;
2407
2408 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
95221eed
JF
2409 id value(internal->GetValue());
2410
88c6482c 2411 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
95221eed
JF
2412 return _this;
2413
88c6482c 2414 if (JSValueRef result = [value cy$valueOfInContext:context])
95221eed
JF
2415 return result;
2416
2417 return _this;
c30687a7 2418} CYCatch return /*XXX*/ NULL; }
20ded97a
JF
2419
2420static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
97343f31 2421 if (!JSValueIsObjectOfClass(context, _this, Instance_))
20ded97a
JF
2422 return NULL;
2423
2424 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2425 // XXX: but... but... THIS ISN'T A POINTER! :(
2426 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2427} CYCatch return /*XXX*/ NULL; }
c30687a7 2428
3c1c3635 2429static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
97343f31 2430 if (!JSValueIsObjectOfClass(context, _this, Instance_))
365abb0a
JF
2431 return NULL;
2432
9e562cfc 2433 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
7db9993a 2434 id value(internal->GetValue());
6d056e33 2435
7db9993a
JF
2436 if (value == nil)
2437 return CYCastJSValue(context, "nil");
2438
3c1c3635
JF
2439 CYPoolTry {
2440 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
6d056e33 2441 return CYCastJSValue(context, CYJSString(context, [value description]));
3c1c3635 2442 } CYPoolCatch(NULL)
7c6c5b0a 2443} CYCatch return /*XXX*/ NULL; }
478d4ed0 2444
3c1c3635 2445static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
9e562cfc 2446 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3c1c3635
JF
2447 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2448} CYCatch }
478d4ed0 2449
b4aa79af
JF
2450static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2451 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2452}
2453
3c1c3635 2454static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
7b184c00
JF
2455 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2456 const char *name(sel_getName(internal->GetValue()));
2457
3c1c3635 2458 CYPoolTry {
95678376
JF
2459 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2460 return CYCastJSValue(context, CYJSString(context, string));
3c1c3635 2461 } CYPoolCatch(NULL)
7c6c5b0a 2462} CYCatch return /*XXX*/ NULL; }
e5bc40db 2463
3c1c3635
JF
2464static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2465 if (count != 1)
37954781
JF
2466 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2467
3c1c3635
JF
2468 CYPool pool;
2469 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
37954781
JF
2470 SEL sel(internal->GetValue());
2471
2472 objc_method *method;
2473 if (Class _class = CYCastClass(pool, context, arguments[0]))
2474 method = class_getInstanceMethod(_class, sel);
2475 else
2476 method = NULL;
2477
2478 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2479 return CYCastJSValue(context, CYJSString(type));
e5bc40db 2480
3c1c3635
JF
2481 return CYJSNull(context);
2482} CYCatch }
e5bc40db 2483
856b8cd0 2484static JSStaticValue Selector_staticValues[2] = {
61933e16 2485 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
04450da0
JF
2486 {NULL, NULL, NULL, 0}
2487};
953647c1 2488
365abb0a 2489static JSStaticValue Instance_staticValues[5] = {
9e562cfc 2490 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
365abb0a 2491 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2f1295ff 2492 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
9e562cfc 2493 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
9b5527f0
JF
2494 {NULL, NULL, NULL, 0}
2495};
2496
95221eed 2497static JSStaticFunction Instance_staticFunctions[7] = {
7b184c00 2498 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b4aa79af
JF
2499 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2500 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
95221eed 2501 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
20ded97a 2502 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0
JF
2503 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2504 {NULL, NULL, 0}
2505};
2506
9b5527f0
JF
2507static JSStaticFunction Internal_staticFunctions[2] = {
2508 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2509 {NULL, NULL, 0}
2510};
2511
b4aa79af
JF
2512static JSStaticFunction Selector_staticFunctions[5] = {
2513 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2514 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0 2515 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b09da87b
JF
2516 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2517 {NULL, NULL, 0}
2518};
ea2d184c 2519
3c9f7e22 2520void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
c44063e0
JF
2521 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2522 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2523 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2524
37954781
JF
2525 apr_pool_t *pool(CYGetGlobalPool());
2526
807a88be
JF
2527 Object_type = new(pool) Type_privateData("@");
2528 Selector_type = new(pool) Type_privateData(":");
7b184c00 2529
b53b30c1 2530#ifdef __APPLE__
c1582939 2531 NSCFBoolean_ = objc_getClass("NSCFBoolean");
18ed94e4
JF
2532 if (NSCFBoolean_ == nil)
2533 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2534
c239b9f8 2535 NSCFType_ = objc_getClass("NSCFType");
aaa4a269 2536 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
b5dd57dc
JF
2537 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2538 NSZombie_ = objc_getClass("_NSZombie_");
c074e774
JF
2539#else
2540 NSBoolNumber_ = objc_getClass("NSBoolNumber");
b53b30c1
JF
2541#endif
2542
2543 NSArray_ = objc_getClass("NSArray");
aaa3cd1e 2544 NSBlock_ = objc_getClass("NSBlock");
b5dd57dc 2545 NSDictionary_ = objc_getClass("NSDictionary");
4cb8aa43 2546 NSString_ = objc_getClass("NSString");
c239b9f8 2547 Object_ = objc_getClass("Object");
3c1c3635
JF
2548
2549 JSClassDefinition definition;
2550
2551 definition = kJSClassDefinitionEmpty;
2552 definition.className = "Instance";
2553 definition.staticValues = Instance_staticValues;
2554 definition.staticFunctions = Instance_staticFunctions;
2555 definition.hasProperty = &Instance_hasProperty;
2556 definition.getProperty = &Instance_getProperty;
2557 definition.setProperty = &Instance_setProperty;
2558 definition.deleteProperty = &Instance_deleteProperty;
2559 definition.getPropertyNames = &Instance_getPropertyNames;
2560 definition.callAsConstructor = &Instance_callAsConstructor;
aaa3cd1e 2561 definition.callAsFunction = &Instance_callAsFunction;
3c1c3635 2562 definition.hasInstance = &Instance_hasInstance;
37954781 2563 definition.finalize = &CYFinalize;
3c1c3635
JF
2564 Instance_ = JSClassCreate(&definition);
2565
1fb9f0d0
JF
2566 definition.className = "ArrayInstance";
2567 ArrayInstance_ = JSClassCreate(&definition);
2568
aaa3cd1e
JF
2569 definition.className = "FunctionInstance";
2570 FunctionInstance_ = JSClassCreate(&definition);
2571
1fb9f0d0
JF
2572 definition.className = "ObjectInstance";
2573 ObjectInstance_ = JSClassCreate(&definition);
2574
2575 definition.className = "StringInstance";
2576 StringInstance_ = JSClassCreate(&definition);
2577
3c1c3635
JF
2578 definition = kJSClassDefinitionEmpty;
2579 definition.className = "Internal";
2580 definition.staticFunctions = Internal_staticFunctions;
2581 definition.hasProperty = &Internal_hasProperty;
2582 definition.getProperty = &Internal_getProperty;
2583 definition.setProperty = &Internal_setProperty;
2584 definition.getPropertyNames = &Internal_getPropertyNames;
37954781 2585 definition.finalize = &CYFinalize;
3c1c3635
JF
2586 Internal_ = JSClassCreate(&definition);
2587
2588 definition = kJSClassDefinitionEmpty;
2589 definition.className = "Message";
37954781 2590 definition.staticFunctions = cy::Functor::StaticFunctions;
3c1c3635 2591 definition.callAsFunction = &Message_callAsFunction;
37954781 2592 definition.finalize = &CYFinalize;
3c1c3635
JF
2593 Message_ = JSClassCreate(&definition);
2594
2595 definition = kJSClassDefinitionEmpty;
2596 definition.className = "Messages";
2597 definition.hasProperty = &Messages_hasProperty;
2598 definition.getProperty = &Messages_getProperty;
2599 definition.setProperty = &Messages_setProperty;
7c6c5b0a 2600#if 0 && OBJC_API_VERSION < 2
3c1c3635
JF
2601 definition.deleteProperty = &Messages_deleteProperty;
2602#endif
2603 definition.getPropertyNames = &Messages_getPropertyNames;
37954781 2604 definition.finalize = &CYFinalize;
3c1c3635
JF
2605 Messages_ = JSClassCreate(&definition);
2606
2607 definition = kJSClassDefinitionEmpty;
2608 definition.className = "Selector";
2609 definition.staticValues = Selector_staticValues;
2610 definition.staticFunctions = Selector_staticFunctions;
2611 definition.callAsFunction = &Selector_callAsFunction;
37954781 2612 definition.finalize = &CYFinalize;
3c1c3635
JF
2613 Selector_ = JSClassCreate(&definition);
2614
2615 definition = kJSClassDefinitionEmpty;
2616 definition.className = "Super";
2617 definition.staticFunctions = Internal_staticFunctions;
37954781 2618 definition.finalize = &CYFinalize;
3c1c3635
JF
2619 Super_ = JSClassCreate(&definition);
2620
2621 definition = kJSClassDefinitionEmpty;
2622 definition.className = "ObjectiveC::Classes";
2623 definition.getProperty = &ObjectiveC_Classes_getProperty;
2624 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2625 ObjectiveC_Classes_ = JSClassCreate(&definition);
2626
26ef7a82
JF
2627 definition = kJSClassDefinitionEmpty;
2628 definition.className = "ObjectiveC::Constants";
2629 definition.getProperty = &ObjectiveC_Constants_getProperty;
2630 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2631 ObjectiveC_Constants_ = JSClassCreate(&definition);
2632
7c6c5b0a 2633#if OBJC_API_VERSION >= 2
3c1c3635
JF
2634 definition = kJSClassDefinitionEmpty;
2635 definition.className = "ObjectiveC::Images";
2636 definition.getProperty = &ObjectiveC_Images_getProperty;
2637 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2638 ObjectiveC_Images_ = JSClassCreate(&definition);
2639
2640 definition = kJSClassDefinitionEmpty;
2641 definition.className = "ObjectiveC::Image::Classes";
2642 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2643 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2644 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3c9f7e22 2645#endif
3c1c3635 2646
3c9f7e22
JF
2647 definition = kJSClassDefinitionEmpty;
2648 definition.className = "ObjectiveC::Protocols";
2649 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2650 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2651 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2652
3c9f7e22
JF
2653#ifdef __APPLE__
2654 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2655#endif
2656} CYPoolCatch() }
2657
2658void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2659 JSObjectRef global(CYGetGlobalObject(context));
498c3570 2660 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2385c806
JF
2661 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2662 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
26ef7a82 2663 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
3c9f7e22
JF
2664
2665 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2385c806 2666 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
3c9f7e22 2667
26ef7a82
JF
2668 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2669 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2670 CYArrayPush(context, alls, protocols);
2671
2672 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2673 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2674 CYArrayPush(context, alls, classes);
2675
2676 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2677 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2678 CYArrayPush(context, alls, constants);
3c9f7e22
JF
2679
2680#if OBJC_API_VERSION >= 2
3c1c3635 2681 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
aabea98c 2682#endif
3c1c3635
JF
2683
2684 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2685 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2686 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2687 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2688
498c3570
JF
2689 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2690 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3c1c3635 2691
1fb9f0d0 2692 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
4a2eef6c
JF
2693 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2694 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2695 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2696 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2697
aaa3cd1e
JF
2698 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2699 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2700 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2701 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2702 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2703
1fb9f0d0 2704 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
11f3e89e
JF
2705 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2706 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2707 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2708 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2709
1fb9f0d0 2710 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
6732f195
JF
2711 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2712 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
6732f195
JF
2713 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2714 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2715
2385c806
JF
2716 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2717 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2718 CYSetProperty(context, cycript, CYJSString("Super"), Super);
3c1c3635 2719
f2f0d1d1
JF
2720 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2721 CYSetProperty(context, Instance, CYJSString("box"), box);
2722
8ad1528b 2723#if defined(__APPLE__) && defined(__arm__) && 0
98ea05a3 2724 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
b5dd57dc
JF
2725#endif
2726
98ea05a3 2727 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3c1c3635 2728
498c3570
JF
2729 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2730 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3c9f7e22 2731} CYPoolCatch() }
b5dd57dc
JF
2732
2733static CYHooks CYObjectiveCHooks = {
2734 &CYObjectiveC_ExecuteStart,
2735 &CYObjectiveC_ExecuteEnd,
b5dd57dc 2736 &CYObjectiveC_CallFunction,
3c9f7e22 2737 &CYObjectiveC_Initialize,
b5dd57dc
JF
2738 &CYObjectiveC_SetupContext,
2739 &CYObjectiveC_PoolFFI,
2740 &CYObjectiveC_FromFFI,
2741};
2742
2743struct CYObjectiveC {
2744 CYObjectiveC() {
2745 hooks_ = &CYObjectiveCHooks;
6faa533c
DWT
2746 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2747 _assert(hooks_ != NULL);
b5dd57dc
JF
2748 }
2749} CYObjectiveC;