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