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