]> git.saurik.com Git - cycript.git/blame - ObjectiveC/Library.mm
Add support for Objective-C boxed expression syntax.
[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
3c1c3635 1234- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
c1582939
JF
1235 if ((self = [super init]) != nil) {
1236 object_ = object;
bc60fb46
JF
1237 context_ = CYGetJSContext(context);
1238 //XXX:JSGlobalContextRetain(context_);
75b0a457 1239 JSValueProtect(context_, object_);
c1582939 1240 } return self;
3c1c3635 1241} CYObjectiveCatch }
c1582939 1242
3c1c3635 1243- (void) dealloc { CYObjectiveTry {
75b0a457 1244 JSValueUnprotect(context_, object_);
bc60fb46 1245 //XXX:JSGlobalContextRelease(context_);
75b0a457 1246 [super dealloc];
3c1c3635 1247} CYObjectiveCatch }
75b0a457 1248
3c1c3635 1249- (NSUInteger) count { CYObjectiveTry {
07db5f4d 1250 return CYArrayLength(context_, object_);
3c1c3635 1251} CYObjectiveCatch }
c1582939 1252
3c1c3635 1253- (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
9a2db8b2
JF
1254 size_t bounds([self count]);
1255 if (index >= bounds)
1256 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
62ca2b82
JF
1257 JSValueRef exception(NULL);
1258 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1259 CYThrow(context_, exception);
478d4ed0 1260 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
3c1c3635 1261} CYObjectiveCatch }
c1582939 1262
3c1c3635 1263- (void) addObject:(id)object { CYObjectiveTry {
07db5f4d 1264 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
3c1c3635 1265} CYObjectiveCatch }
faf69207 1266
3c1c3635 1267- (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
9a2db8b2
JF
1268 size_t bounds([self count] + 1);
1269 if (index >= bounds)
1270 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
faf69207
JF
1271 JSValueRef exception(NULL);
1272 JSValueRef arguments[3];
1273 arguments[0] = CYCastJSValue(context_, index);
1274 arguments[1] = CYCastJSValue(context_, 0);
ba4fa42f 1275 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
9772d9bf 1276 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
498c3570 1277 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
3c1c3635
JF
1278 CYThrow(context_, exception);
1279} CYObjectiveCatch }
af4272e6 1280
3c1c3635
JF
1281- (void) removeLastObject { CYObjectiveTry {
1282 JSValueRef exception(NULL);
9772d9bf 1283 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
498c3570 1284 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
3c1c3635
JF
1285 CYThrow(context_, exception);
1286} CYObjectiveCatch }
af4272e6 1287
3c1c3635
JF
1288- (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1289 size_t bounds([self count]);
1290 if (index >= bounds)
1291 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1292 JSValueRef exception(NULL);
1293 JSValueRef arguments[2];
1294 arguments[0] = CYCastJSValue(context_, index);
1295 arguments[1] = CYCastJSValue(context_, 1);
9772d9bf 1296 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
498c3570 1297 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
3c1c3635
JF
1298 CYThrow(context_, exception);
1299} CYObjectiveCatch }
1300
1301- (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1302 size_t bounds([self count]);
1303 if (index >= bounds)
1304 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
ba4fa42f 1305 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
3c1c3635
JF
1306} CYObjectiveCatch }
1307
1308@end
af4272e6 1309
18401062 1310// XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
61933e16
JF
1311struct CYInternal :
1312 CYData
1313{
1314 JSObjectRef object_;
1315
1316 CYInternal() :
1317 object_(NULL)
1318 {
1319 }
1320
1321 ~CYInternal() {
1322 // XXX: delete object_? ;(
1323 }
1324
1325 static CYInternal *Get(id self) {
1326 CYInternal *internal(NULL);
1327 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1328 // XXX: do something epic? ;P
1329 }
1330
1331 return internal;
1332 }
1333
1334 static CYInternal *Set(id self) {
1335 CYInternal *internal(NULL);
aabea98c 1336 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
61933e16
JF
1337 if (internal == NULL) {
1338 internal = new CYInternal();
1339 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1340 }
1341 } else {
1342 // XXX: do something epic? ;P
1343 }
1344
1345 return internal;
1346 }
1347
7b184c00
JF
1348 bool HasProperty(JSContextRef context, JSStringRef name) {
1349 if (object_ == NULL)
1350 return false;
1351 return JSObjectHasProperty(context, object_, name);
1352 }
1353
61933e16
JF
1354 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1355 if (object_ == NULL)
1356 return NULL;
1357 return CYGetProperty(context, object_, name);
1358 }
1359
1360 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1361 if (object_ == NULL)
1362 object_ = JSObjectMake(context, NULL, NULL);
1363 CYSetProperty(context, object_, name, value);
1364 }
1365};
1366
534fb6da 1367static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
9e562cfc
JF
1368 Selector_privateData *internal(new Selector_privateData(sel));
1369 return JSObjectMake(context, Selector_, internal);
dea834b0 1370}
b09da87b 1371
534fb6da 1372static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
4afefdd9 1373 if (JSValueIsObjectOfClass(context, value, Selector_)) {
9e562cfc
JF
1374 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1375 return reinterpret_cast<SEL>(internal->value_);
4afefdd9
JF
1376 } else
1377 return CYCastPointer<SEL>(context, value);
1378}
1379
b64ab4da 1380void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
3c1c3635 1381 return (void *) [[NSAutoreleasePool alloc] init];
ea840434 1382} CYSadCatch(NULL) }
ea2d184c 1383
b64ab4da 1384void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
3c1c3635 1385 return [(NSAutoreleasePool *) handle release];
ea840434 1386} CYSadCatch() }
ea2d184c 1387
f0d43c71 1388JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
3c1c3635
JF
1389 if (name == "nil")
1390 return Instance::Make(context, nil);
1391 if (Class _class = objc_getClass(name.data))
1392 return CYMakeInstance(context, _class, true);
64b8d29f
JF
1393 if (Protocol *protocol = objc_getProtocol(name.data))
1394 return CYMakeInstance(context, protocol, true);
3c1c3635 1395 return NULL;
7c6c5b0a 1396} CYPoolCatch(NULL) return /*XXX*/ NULL; }
d3760804 1397
b64ab4da 1398static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
d3760804 1399 ffi_call(cif, function, value, values);
ea840434 1400} CYSadCatch() }
ea2d184c 1401
b64ab4da 1402static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
3c1c3635 1403 switch (type->primitive) {
ecf94af8
JF
1404 // XXX: do something epic about blocks
1405 case sig::block_P:
ea2d184c
JF
1406 case sig::object_P:
1407 case sig::typename_P:
b09da87b 1408 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
7ba62cfd
JF
1409 break;
1410
ea2d184c 1411 case sig::selector_P:
7ba62cfd
JF
1412 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1413 break;
ea2d184c 1414
bd17e6f3 1415 default:
3c1c3635 1416 return false;
ea2d184c 1417 }
ea2d184c 1418
3c1c3635 1419 return true;
ea840434 1420} CYSadCatch(false) }
ea2d184c 1421
f0d43c71 1422static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
ea2d184c 1423 switch (type->primitive) {
ecf94af8
JF
1424 // XXX: do something epic about blocks
1425 case sig::block_P:
3c1c3635 1426 case sig::object_P:
ba4fa42f 1427 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
3c1c3635 1428 JSValueRef value(CYCastJSValue(context, object));
2b52f27e
JF
1429 if (initialize)
1430 [object release];
3c1c3635 1431 return value;
2b52f27e 1432 } else goto null;
dea834b0 1433
b09da87b 1434 case sig::typename_P:
3c1c3635 1435 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
b09da87b 1436
dea834b0
JF
1437 case sig::selector_P:
1438 if (SEL sel = *reinterpret_cast<SEL *>(data))
3c1c3635 1439 return CYMakeSelector(context, sel);
f610e1a0 1440 else goto null;
f610e1a0
JF
1441
1442 null:
3c1c3635 1443 return CYJSNull(context);
bd17e6f3 1444 default:
3c1c3635 1445 return NULL;
ea2d184c 1446 }
7c6c5b0a 1447} CYPoolCatch(NULL) return /*XXX*/ NULL; }
ea2d184c 1448
8a199b13 1449static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
39bb4b6a 1450 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
8a199b13
JF
1451 if (!devoid)
1452 return true;
7c6c5b0a 1453#if OBJC_API_VERSION >= 2
8a199b13
JF
1454 char type[16];
1455 method_getReturnType(method, type, sizeof(type));
b5dd57dc
JF
1456#else
1457 const char *type(method_getTypeEncoding(method));
1458#endif
8a199b13
JF
1459 if (type[0] != 'v')
1460 return true;
1461 }
1462
7b184c00 1463 // XXX: possibly use a more "awesome" check?
8a199b13 1464 return false;
7b184c00
JF
1465}
1466
37954781 1467static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
dc68b74c
JF
1468 if (method != NULL)
1469 return method_getTypeEncoding(method);
856b8cd0
JF
1470
1471 const char *name(sel_getName(sel));
2f51d6ab 1472 size_t length(strlen(name));
856b8cd0 1473
2f51d6ab
JF
1474 char keyed[length + 2];
1475 keyed[0] = '6';
1476 keyed[length + 1] = '\0';
1477 memcpy(keyed + 1, name, length);
dc68b74c 1478
2f51d6ab
JF
1479 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1480 return entry->value_;
dc68b74c 1481
3c1c3635 1482 return NULL;
dc68b74c
JF
1483}
1484
3c1c3635
JF
1485static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1486 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
dc68b74c 1487
3c1c3635 1488 JSContextRef context(internal->context_);
dc68b74c 1489
3c1c3635
JF
1490 size_t count(internal->cif_.nargs);
1491 JSValueRef values[count];
1492
1493 for (size_t index(0); index != count; ++index)
1494 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1495
1496 JSObjectRef _this(CYCastJSObject(context, values[0]));
1497
1498 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1499 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
dc68b74c
JF
1500}
1501
1502static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1503 Message_privateData *internal(new Message_privateData(sel, type, imp));
1504 return JSObjectMake(context, Message_, internal);
1505}
1506
1507static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1508 JSObjectRef function(CYCastJSObject(context, value));
1509 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2fd4c9a9 1510 // XXX: see notes in Library.cpp about needing to leak
dc68b74c
JF
1511 return reinterpret_cast<IMP>(internal->GetValue());
1512}
1513
365abb0a
JF
1514static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1515 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1516 Class _class(internal->GetValue());
1517
1518 CYPool pool;
3c1c3635 1519 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1520
1521 if (SEL sel = sel_getUid(name))
1522 if (class_getInstanceMethod(_class, sel) != NULL)
1523 return true;
1524
1525 return false;
1526}
1527
365abb0a
JF
1528static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1529 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1530 Class _class(internal->GetValue());
1531
1532 CYPool pool;
3c1c3635 1533 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1534
1535 if (SEL sel = sel_getUid(name))
39bb4b6a 1536 if (objc_method *method = class_getInstanceMethod(_class, sel))
dc68b74c
JF
1537 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1538
1539 return NULL;
1540}
1541
365abb0a
JF
1542static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1543 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1544 Class _class(internal->GetValue());
1545
1546 CYPool pool;
3c1c3635 1547 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1548
1549 SEL sel(sel_registerName(name));
1550
39bb4b6a 1551 objc_method *method(class_getInstanceMethod(_class, sel));
dc68b74c
JF
1552
1553 const char *type;
1554 IMP imp;
1555
1556 if (JSValueIsObjectOfClass(context, value, Message_)) {
1557 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1558 type = sig::Unparse(pool, &message->signature_);
1559 imp = reinterpret_cast<IMP>(message->GetValue());
1560 } else {
37954781 1561 type = CYPoolTypeEncoding(pool, context, sel, method);
dc68b74c
JF
1562 imp = CYMakeMessage(context, value, type);
1563 }
1564
1565 if (method != NULL)
1566 method_setImplementation(method, imp);
b5dd57dc
JF
1567 else {
1568#ifdef GNU_RUNTIME
1569 GSMethodList list(GSAllocMethodList(1));
1570 GSAppendMethodToList(list, sel, type, imp, YES);
1571 GSAddMethodList(_class, list, YES);
1572 GSFlushMethodCacheForClass(_class);
1573#else
1574 class_addMethod(_class, sel, imp, type);
1575#endif
1576 }
dc68b74c
JF
1577
1578 return true;
1579}
1580
7c6c5b0a 1581#if 0 && OBJC_API_VERSION < 2
365abb0a
JF
1582static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1583 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1584 Class _class(internal->GetValue());
1585
1586 CYPool pool;
aabea98c 1587 const char *name(CYPoolCString(pool, context, property));
dc68b74c
JF
1588
1589 if (SEL sel = sel_getUid(name))
39bb4b6a 1590 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
dc68b74c
JF
1591 objc_method_list list = {NULL, 1, {method}};
1592 class_removeMethods(_class, &list);
1593 return true;
1594 }
1595
1596 return false;
1597}
1598#endif
1599
365abb0a
JF
1600static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1601 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
dc68b74c
JF
1602 Class _class(internal->GetValue());
1603
7c6c5b0a 1604#if OBJC_API_VERSION >= 2
dc68b74c 1605 unsigned int size;
39bb4b6a 1606 objc_method **data(class_copyMethodList(_class, &size));
dc68b74c
JF
1607 for (size_t i(0); i != size; ++i)
1608 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1609 free(data);
aabea98c
JF
1610#else
1611 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1612 for (int i(0); i != methods->method_count; ++i)
1613 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1614#endif
dc68b74c
JF
1615}
1616
3e264692
JF
1617static bool CYHasImplicitProperties(Class _class) {
1618 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1619 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1620 return true;
1621 return [_class cy$hasImplicitProperties];
1622}
1623
7b184c00
JF
1624static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1625 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1626 id self(internal->GetValue());
1627
1628 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1629 return true;
1630
c239b9f8 1631 CYPool pool;
aabea98c 1632 NSString *name(CYCastNSString(pool, context, property));
7b184c00
JF
1633
1634 if (CYInternal *internal = CYInternal::Get(self))
1635 if (internal->HasProperty(context, property))
1636 return true;
1637
365abb0a
JF
1638 Class _class(object_getClass(self));
1639
7b184c00 1640 CYPoolTry {
365abb0a
JF
1641 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1642 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1643 if ([self cy$hasProperty:name])
1644 return true;
7b184c00
JF
1645 } CYPoolCatch(false)
1646
3c1c3635 1647 const char *string(CYPoolCString(pool, context, name));
7b184c00 1648
aabea98c 1649#ifdef __APPLE__
7b184c00
JF
1650 if (class_getProperty(_class, string) != NULL)
1651 return true;
aabea98c 1652#endif
7b184c00 1653
3e264692
JF
1654 if (CYHasImplicitProperties(_class))
1655 if (SEL sel = sel_getUid(string))
1656 if (CYImplements(self, _class, sel, true))
1657 return true;
7b184c00
JF
1658
1659 return false;
1660}
1661
3c1c3635 1662static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
7b184c00
JF
1663 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1664 id self(internal->GetValue());
1665
1666 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1667 return Internal::Make(context, self, object);
c239b9f8 1668
3c1c3635 1669 CYPool pool;
aabea98c 1670 NSString *name(CYCastNSString(pool, context, property));
c239b9f8 1671
3c1c3635
JF
1672 if (CYInternal *internal = CYInternal::Get(self))
1673 if (JSValueRef value = internal->GetProperty(context, property))
1674 return value;
c239b9f8 1675
3c1c3635
JF
1676 CYPoolTry {
1677 if (NSObject *data = [self cy$getProperty:name])
1678 return CYCastJSValue(context, data);
1679 } CYPoolCatch(NULL)
c239b9f8 1680
3c1c3635
JF
1681 const char *string(CYPoolCString(pool, context, name));
1682 Class _class(object_getClass(self));
c239b9f8 1683
cbaa5f0f 1684#ifdef __APPLE__
3c1c3635
JF
1685 if (objc_property_t property = class_getProperty(_class, string)) {
1686 PropertyAttributes attributes(property);
1687 SEL sel(sel_registerName(attributes.Getter()));
1688 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1689 }
cbaa5f0f 1690#endif
c239b9f8 1691
3e264692
JF
1692 if (CYHasImplicitProperties(_class))
1693 if (SEL sel = sel_getUid(string))
1694 if (CYImplements(self, _class, sel, true))
1695 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
8953777c 1696
3c1c3635
JF
1697 return NULL;
1698} CYCatch }
c239b9f8 1699
3c1c3635 1700static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
dc68b74c
JF
1701 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1702 id self(internal->GetValue());
1703
c239b9f8
JF
1704 CYPool pool;
1705
aabea98c 1706 NSString *name(CYCastNSString(pool, context, property));
3c1c3635 1707 NSObject *data(CYCastNSObject(pool, context, value));
8953777c 1708
3c1c3635
JF
1709 CYPoolTry {
1710 if ([self cy$setProperty:name to:data])
c239b9f8 1711 return true;
3c1c3635 1712 } CYPoolCatch(NULL)
dc68b74c 1713
3c1c3635 1714 const char *string(CYPoolCString(pool, context, name));
c239b9f8
JF
1715 Class _class(object_getClass(self));
1716
8aa3e970 1717#ifdef __APPLE__
3c1c3635
JF
1718 if (objc_property_t property = class_getProperty(_class, string)) {
1719 PropertyAttributes attributes(property);
1720 if (const char *setter = attributes.Setter()) {
1721 SEL sel(sel_registerName(setter));
1722 JSValueRef arguments[1] = {value};
1723 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
9b5527f0
JF
1724 return true;
1725 }
3c1c3635 1726 }
b24eb750 1727#endif
c239b9f8 1728
3c1c3635 1729 size_t length(strlen(string));
9e20b0b7 1730
3c1c3635 1731 char set[length + 5];
f33b048a 1732
3c1c3635
JF
1733 set[0] = 's';
1734 set[1] = 'e';
1735 set[2] = 't';
f33b048a 1736
3c1c3635
JF
1737 if (string[0] != '\0') {
1738 set[3] = toupper(string[0]);
1739 memcpy(set + 4, string + 1, length - 1);
e0dc20ec 1740 }
bd17e6f3 1741
3c1c3635
JF
1742 set[length + 3] = ':';
1743 set[length + 4] = '\0';
9b5527f0 1744
3c1c3635
JF
1745 if (SEL sel = sel_getUid(set))
1746 if (CYImplements(self, _class, sel, false)) {
1747 JSValueRef arguments[1] = {value};
1748 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1749 }
f37b3d2b 1750
3c1c3635
JF
1751 if (CYInternal *internal = CYInternal::Set(self)) {
1752 internal->SetProperty(context, property, value);
f37b3d2b 1753 return true;
3c1c3635 1754 }
f37b3d2b 1755
3c1c3635
JF
1756 return false;
1757} CYCatch }
9b5527f0 1758
3c1c3635
JF
1759static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1760 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1761 id self(internal->GetValue());
9b5527f0 1762
3c1c3635 1763 CYPoolTry {
aabea98c 1764 NSString *name(CYCastNSString(NULL, context, property));
3c1c3635
JF
1765 return [self cy$deleteProperty:name];
1766 } CYPoolCatch(NULL)
7c6c5b0a 1767} CYCatch return /*XXX*/ NULL; }
9b5527f0 1768
ec18fc0e
JF
1769static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1770 const char *name(sel_getName(method_getName(method)));
1771 if (strchr(name, ':') != NULL)
1772 return;
1773
1774 const char *type(method_getTypeEncoding(method));
1775 if (type == NULL || *type == '\0' || *type == 'v')
1776 return;
1777
1778 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1779}
1780
3c1c3635
JF
1781static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1782 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1783 id self(internal->GetValue());
9b5527f0 1784
3c1c3635
JF
1785 CYPool pool;
1786 Class _class(object_getClass(self));
9b5527f0 1787
3c1c3635
JF
1788#ifdef __APPLE__
1789 {
1790 unsigned int size;
1791 objc_property_t *data(class_copyPropertyList(_class, &size));
1792 for (size_t i(0); i != size; ++i)
1793 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1794 free(data);
1795 }
1796#endif
d3760804 1797
326a9dba
JF
1798 if (CYHasImplicitProperties(_class))
1799 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
ec18fc0e 1800#if OBJC_API_VERSION >= 2
326a9dba
JF
1801 unsigned int size;
1802 objc_method **data(class_copyMethodList(current, &size));
1803 for (size_t i(0); i != size; ++i)
1804 Instance_getPropertyNames_message(names, data[i]);
1805 free(data);
ec18fc0e 1806#else
326a9dba
JF
1807 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1808 for (int i(0); i != methods->method_count; ++i)
1809 Instance_getPropertyNames_message(names, &methods->method_list[i]);
ec18fc0e 1810#endif
326a9dba 1811 }
ec18fc0e 1812
d3760804
JF
1813 CYPoolTry {
1814 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
8665da0c
JF
1815 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1816 [self cy$getPropertyNames:names inContext:context];
d3760804 1817 } CYPoolCatch()
9b5527f0
JF
1818}
1819
3c1c3635
JF
1820static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1821 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1822 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1823 return value;
1824} CYCatch }
bd17e6f3 1825
3c1c3635
JF
1826static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1827 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1828 Class _class(internal->GetValue());
1829 if (!CYIsClass(_class))
1830 return false;
bd17e6f3 1831
3c1c3635
JF
1832 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1833 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1834 // XXX: this isn't always safe
1835 return [linternal->GetValue() isKindOfClass:_class];
1836 }
ff783f8c 1837
3c1c3635
JF
1838 return false;
1839} CYCatch }
bd17e6f3 1840
f2f0d1d1
JF
1841static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1842 if (count == 0)
1843 throw CYJSError(context, "incorrect number of arguments to Instance");
1844 CYPool pool;
1845 id value(CYCastNSObject(pool, context, arguments[0]));
1846 if (value == nil)
1847 value = [NSNull null];
1848 return CYCastJSValue(context, [value cy$box]);
1849} CYCatch }
1850
3c1c3635
JF
1851static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1852 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
f33b048a 1853 CYPool pool;
bd17e6f3 1854
3c1c3635
JF
1855 id self(internal->GetValue());
1856 const char *name(CYPoolCString(pool, context, property));
520c130f 1857
3c1c3635 1858 if (object_getInstanceVariable(self, name, NULL) != NULL)
bd17e6f3 1859 return true;
3c1c3635
JF
1860
1861 return false;
bd17e6f3
JF
1862}
1863
3c1c3635
JF
1864static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1865 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1866 CYPool pool;
930aa21b 1867
3c1c3635
JF
1868 id self(internal->GetValue());
1869 const char *name(CYPoolCString(pool, context, property));
f33b048a 1870
aabea98c 1871 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
3c1c3635 1872 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
b81e7fb6 1873 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
3c1c3635
JF
1874 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1875 }
f33b048a 1876
3c1c3635
JF
1877 return NULL;
1878} CYCatch }
283e7e33 1879
3c1c3635
JF
1880static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1881 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1882 CYPool pool;
283e7e33 1883
3c1c3635
JF
1884 id self(internal->GetValue());
1885 const char *name(CYPoolCString(pool, context, property));
283e7e33 1886
aabea98c 1887 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
3c1c3635
JF
1888 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1889 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1890 return true;
283e7e33 1891 }
f33b048a 1892
3c1c3635
JF
1893 return false;
1894} CYCatch }
85a33bf5 1895
3c1c3635
JF
1896static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1897 if (Class super = class_getSuperclass(_class))
1898 Internal_getPropertyNames_(super, names);
ea2d184c 1899
7c6c5b0a 1900#if OBJC_API_VERSION >= 2
3c1c3635 1901 unsigned int size;
aabea98c 1902 objc_ivar **data(class_copyIvarList(_class, &size));
3c1c3635
JF
1903 for (size_t i(0); i != size; ++i)
1904 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1905 free(data);
b5dd57dc
JF
1906#else
1907 if (objc_ivar_list *ivars = _class->ivars)
1908 for (int i(0); i != ivars->ivar_count; ++i)
1909 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1910#endif
3c1c3635
JF
1911}
1912
1913static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1914 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1915 CYPool pool;
ea2d184c 1916
3c1c3635
JF
1917 id self(internal->GetValue());
1918 Class _class(object_getClass(self));
7ba62cfd 1919
3c1c3635 1920 Internal_getPropertyNames_(_class, names);
7ba62cfd 1921}
ea2d184c 1922
3c1c3635
JF
1923static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1924 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1925 return internal->GetOwner();
c239b9f8
JF
1926}
1927
3c1c3635
JF
1928static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1929 CYPool pool;
aabea98c 1930 NSString *name(CYCastNSString(pool, context, property));
3c1c3635
JF
1931 if (Class _class = NSClassFromString(name))
1932 return CYMakeInstance(context, _class, true);
1933 return NULL;
1934} CYCatch }
1935
c239b9f8 1936static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
aabea98c 1937#ifdef __APPLE__
c239b9f8
JF
1938 size_t size(objc_getClassList(NULL, 0));
1939 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1940
1941 get:
1942 size_t writ(objc_getClassList(data, size));
1943 if (size < writ) {
1944 size = writ;
1945 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1946 data = copy;
1947 goto get;
1948 } else goto done;
1949 }
1950
1951 for (size_t i(0); i != writ; ++i)
1952 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1953
1954 done:
1955 free(data);
aabea98c
JF
1956#else
1957 void *state(NULL);
1958 while (Class _class = objc_next_class(&state))
1959 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1960#endif
c239b9f8
JF
1961}
1962
7c6c5b0a 1963#if OBJC_API_VERSION >= 2
3c1c3635 1964static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
c239b9f8
JF
1965 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1966
3c1c3635
JF
1967 CYPool pool;
1968 const char *name(CYPoolCString(pool, context, property));
1969 unsigned int size;
1970 const char **data(objc_copyClassNamesForImage(internal, &size));
1971 JSValueRef value;
1972 for (size_t i(0); i != size; ++i)
1973 if (strcmp(name, data[i]) == 0) {
1974 if (Class _class = objc_getClass(name)) {
1975 value = CYMakeInstance(context, _class, true);
1976 goto free;
1977 } else
1978 break;
1979 }
1980 value = NULL;
1981 free:
1982 free(data);
1983 return value;
1984} CYCatch }
c239b9f8
JF
1985
1986static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1987 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1988 unsigned int size;
1989 const char **data(objc_copyClassNamesForImage(internal, &size));
1990 for (size_t i(0); i != size; ++i)
1991 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1992 free(data);
1993}
1994
3c1c3635
JF
1995static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1996 CYPool pool;
1997 const char *name(CYPoolCString(pool, context, property));
1998 unsigned int size;
1999 const char **data(objc_copyImageNames(&size));
2000 for (size_t i(0); i != size; ++i)
2001 if (strcmp(name, data[i]) == 0) {
2002 name = data[i];
2003 goto free;
2004 }
2005 name = NULL;
2006 free:
2007 free(data);
2008 if (name == NULL)
2009 return NULL;
2010 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2011 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2012 return value;
2013} CYCatch }
c239b9f8
JF
2014
2015static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2016 unsigned int size;
2017 const char **data(objc_copyImageNames(&size));
2018 for (size_t i(0); i != size; ++i)
2019 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2020 free(data);
2021}
aabea98c 2022#endif
c239b9f8 2023
3c1c3635
JF
2024static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2025 CYPool pool;
aabea98c
JF
2026 const char *name(CYPoolCString(pool, context, property));
2027 if (Protocol *protocol = objc_getProtocol(name))
3c1c3635
JF
2028 return CYMakeInstance(context, protocol, true);
2029 return NULL;
2030} CYCatch }
c239b9f8
JF
2031
2032static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
7c6c5b0a 2033#if OBJC_API_VERSION >= 2
c239b9f8
JF
2034 unsigned int size;
2035 Protocol **data(objc_copyProtocolList(&size));
2036 for (size_t i(0); i != size; ++i)
2037 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2038 free(data);
aabea98c
JF
2039#else
2040 // XXX: fix this!
2041#endif
c239b9f8 2042}
707bcb93 2043
26ef7a82
JF
2044static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2045 CYPool pool;
2046 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2047 if (name == "nil")
2048 return Instance::Make(context, nil);
2049 return NULL;
2050} CYCatch }
2051
2052static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2053 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2054}
2055
aabea98c 2056#ifdef __APPLE__
534fb6da 2057static bool stret(ffi_type *ffi_type) {
04450da0
JF
2058 return ffi_type->type == FFI_TYPE_STRUCT && (
2059 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2060 struct_forward_array[ffi_type->size] != 0
2061 );
2062}
aabea98c 2063#endif
b09da87b 2064
3c1c3635 2065JSValueRef 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 2066 const char *type;
ea2d184c 2067
cacd1a88
JF
2068 if (_class == NULL)
2069 _class = object_getClass(self);
2070
aabea98c
JF
2071 IMP imp;
2072
2073 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2074 imp = method_getImplementation(method);
4afefdd9 2075 type = method_getTypeEncoding(method);
aabea98c
JF
2076 } else {
2077 imp = NULL;
2078
3c1c3635
JF
2079 CYPoolTry {
2080 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2081 if (method == nil)
37954781 2082 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3c1c3635
JF
2083 type = CYPoolCString(pool, context, [method _typeString]);
2084 } CYPoolCatch(NULL)
4afefdd9
JF
2085 }
2086
2087 void *setup[2];
f623c5d8 2088 setup[0] = &self;
4afefdd9
JF
2089 setup[1] = &_cmd;
2090
2091 sig::Signature signature;
f33b048a 2092 sig::Parse(pool, &signature, type, &Structor_);
4afefdd9
JF
2093
2094 ffi_cif cif;
2095 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2096
f623c5d8 2097 if (imp == NULL) {
aabea98c
JF
2098#ifdef __APPLE__
2099 if (stret(cif.rtype))
2100 imp = class_getMethodImplementation_stret(_class, _cmd);
2101 else
2102 imp = class_getMethodImplementation(_class, _cmd);
2103#else
f623c5d8 2104 objc_super super = {self, _class};
aabea98c
JF
2105 imp = objc_msg_lookup_super(&super, _cmd);
2106#endif
f623c5d8 2107 }
aabea98c
JF
2108
2109 void (*function)() = reinterpret_cast<void (*)()>(imp);
2b52f27e 2110 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3c1c3635 2111} CYCatch }
367eebb1 2112
3c1c3635
JF
2113static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2114 if (count < 2)
37954781 2115 throw CYJSError(context, "too few arguments to objc_msgSend");
367eebb1 2116
478d4ed0
JF
2117 CYPool pool;
2118
2b52f27e
JF
2119 bool uninitialized;
2120
4afefdd9
JF
2121 id self;
2122 SEL _cmd;
cacd1a88 2123 Class _class;
4afefdd9 2124
3c1c3635
JF
2125 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2126 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2127 self = internal->GetValue();
2128 _class = internal->class_;;
2129 uninitialized = false;
2130 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2131 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2132 self = internal->GetValue();
2133 _class = nil;
2134 uninitialized = internal->IsUninitialized();
2135 if (uninitialized)
2136 internal->value_ = nil;
2137 } else {
2138 self = CYCastNSObject(pool, context, arguments[0]);
2139 _class = nil;
2140 uninitialized = false;
2141 }
2b52f27e 2142
3c1c3635
JF
2143 if (self == nil)
2144 return CYJSNull(context);
7ba62cfd 2145
3c1c3635 2146 _cmd = CYCastSEL(context, arguments[1]);
ea2d184c 2147
cacd1a88 2148 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
3c1c3635 2149} CYCatch }
7ba62cfd 2150
365abb0a 2151/* Hook: objc_registerClassPair {{{ */
8ad1528b 2152#if defined(__APPLE__) && defined(__arm__) && 0
365abb0a
JF
2153// XXX: replace this with associated objects
2154
272c3da3 2155MSHook(void, CYDealloc, id self, SEL sel) {
61933e16
JF
2156 CYInternal *internal;
2157 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2158 if (internal != NULL)
2159 delete internal;
272c3da3 2160 _CYDealloc(self, sel);
61933e16 2161}
f7c38a29 2162
61933e16
JF
2163MSHook(void, objc_registerClassPair, Class _class) {
2164 Class super(class_getSuperclass(_class));
2165 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2166 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
272c3da3 2167 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
f7c38a29
JF
2168 }
2169
61933e16 2170 _objc_registerClassPair(_class);
f7c38a29
JF
2171}
2172
3c1c3635
JF
2173static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2174 if (count != 1)
37954781 2175 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
3c1c3635
JF
2176 CYPool pool;
2177 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2178 if (value == NULL || !CYIsClass(value))
37954781 2179 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
3c1c3635
JF
2180 Class _class((Class) value);
2181 $objc_registerClassPair(_class);
d447cc5e 2182 return CYJSUndefined(context);
3c1c3635 2183} CYCatch }
b5dd57dc 2184#endif
3c1c3635 2185/* }}} */
d447cc5e 2186
dea834b0
JF
2187static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2188 JSValueRef setup[count + 2];
2189 setup[0] = _this;
2190 setup[1] = object;
4afefdd9 2191 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
dea834b0
JF
2192 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2193}
2194
dc68b74c
JF
2195static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2196 CYPool pool;
2197 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2198
2199 // XXX: handle Instance::Uninitialized?
2200 id self(CYCastNSObject(pool, context, _this));
2201
2202 void *setup[2];
2203 setup[0] = &self;
2204 setup[1] = &internal->sel_;
2205
2206 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2207}
2208
3c1c3635
JF
2209static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2210 if (count != 2)
37954781 2211 throw CYJSError(context, "incorrect number of arguments to Super constructor");
4afefdd9 2212 CYPool pool;
3c1c3635
JF
2213 id self(CYCastNSObject(pool, context, arguments[0]));
2214 Class _class(CYCastClass(pool, context, arguments[1]));
2215 return cy::Super::Make(context, self, _class);
2216} CYCatch }
bce8339b 2217
3c1c3635
JF
2218static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2219 if (count != 1)
37954781
JF
2220 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2221 CYPool pool;
2222 const char *name(CYPoolCString(pool, context, arguments[0]));
3c1c3635
JF
2223 return CYMakeSelector(context, sel_registerName(name));
2224} CYCatch }
7b184c00 2225
3c1c3635
JF
2226static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2227 if (count > 1)
37954781 2228 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
3c1c3635 2229 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
15024d7e 2230 return CYMakeInstance(context, self, false);
3c1c3635 2231} CYCatch }
ea2d184c 2232
534fb6da 2233static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
61933e16
JF
2234 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2235 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
04450da0
JF
2236}
2237
7b184c00
JF
2238static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2239 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2240 Type_privateData *typical(internal->GetType());
2241
2242 sig::Type *type;
2243 ffi_type *ffi;
2244
2245 if (typical == NULL) {
2246 type = NULL;
2247 ffi = NULL;
2248 } else {
2249 type = typical->type_;
2250 ffi = typical->ffi_;
2251 }
2252
53ba31e9 2253 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
7b184c00 2254}
4afefdd9 2255
dc68b74c
JF
2256static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2257 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
ec599edf 2258 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
dc68b74c
JF
2259}
2260
2f1295ff 2261static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
365abb0a
JF
2262 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2263 id self(internal->GetValue());
2264 if (!CYIsClass(self))
2265 return CYJSUndefined(context);
3c1c3635
JF
2266 return CYGetClassPrototype(context, self);
2267} CYCatch }
365abb0a
JF
2268
2269static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
dc68b74c
JF
2270 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2271 id self(internal->GetValue());
b5dd57dc 2272 if (!CYIsClass(self))
dc68b74c 2273 return CYJSUndefined(context);
b5dd57dc 2274 return Messages::Make(context, (Class) self);
dc68b74c
JF
2275}
2276
3c1c3635 2277static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
365abb0a
JF
2278 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2279 return NULL;
2280
7b184c00 2281 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
8665da0c 2282 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
3c1c3635 2283} CYCatch }
7b184c00 2284
3c1c3635 2285static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
365abb0a
JF
2286 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2287 return NULL;
2288
7b184c00
JF
2289 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2290
3c1c3635 2291 CYPoolTry {
b5dd57dc
JF
2292 NSString *key;
2293 if (count == 0)
2294 key = nil;
2295 else
2296 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
3c1c3635 2297 // XXX: check for support of cy$toJSON?
8665da0c 2298 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
3c1c3635 2299 } CYPoolCatch(NULL)
7c6c5b0a 2300} CYCatch return /*XXX*/ NULL; }
b4aa79af 2301
c30687a7
JF
2302static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2303 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2304 return NULL;
2305
2306 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
95221eed
JF
2307 id value(internal->GetValue());
2308
2309 if (![value respondsToSelector:@selector(cy$JSValueInContext:)])
2310 return _this;
2311
2312 if (JSValueRef result = [value cy$JSValueInContext:context])
2313 return result;
2314
2315 return _this;
c30687a7 2316} CYCatch return /*XXX*/ NULL; }
20ded97a
JF
2317
2318static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2319 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2320 return NULL;
2321
2322 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2323 // XXX: but... but... THIS ISN'T A POINTER! :(
2324 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2325} CYCatch return /*XXX*/ NULL; }
c30687a7 2326
3c1c3635 2327static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
365abb0a
JF
2328 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2329 return NULL;
2330
9e562cfc 2331 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
7db9993a 2332 id value(internal->GetValue());
6d056e33 2333
7db9993a
JF
2334 if (value == nil)
2335 return CYCastJSValue(context, "nil");
2336
3c1c3635
JF
2337 CYPoolTry {
2338 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
6d056e33 2339 return CYCastJSValue(context, CYJSString(context, [value description]));
3c1c3635 2340 } CYPoolCatch(NULL)
7c6c5b0a 2341} CYCatch return /*XXX*/ NULL; }
478d4ed0 2342
3c1c3635 2343static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
9e562cfc 2344 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3c1c3635
JF
2345 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2346} CYCatch }
478d4ed0 2347
b4aa79af
JF
2348static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2349 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2350}
2351
3c1c3635 2352static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
7b184c00
JF
2353 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2354 const char *name(sel_getName(internal->GetValue()));
2355
3c1c3635 2356 CYPoolTry {
95678376
JF
2357 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2358 return CYCastJSValue(context, CYJSString(context, string));
3c1c3635 2359 } CYPoolCatch(NULL)
7c6c5b0a 2360} CYCatch return /*XXX*/ NULL; }
e5bc40db 2361
3c1c3635
JF
2362static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2363 if (count != 1)
37954781
JF
2364 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2365
3c1c3635
JF
2366 CYPool pool;
2367 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
37954781
JF
2368 SEL sel(internal->GetValue());
2369
2370 objc_method *method;
2371 if (Class _class = CYCastClass(pool, context, arguments[0]))
2372 method = class_getInstanceMethod(_class, sel);
2373 else
2374 method = NULL;
2375
2376 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2377 return CYCastJSValue(context, CYJSString(type));
e5bc40db 2378
3c1c3635
JF
2379 return CYJSNull(context);
2380} CYCatch }
e5bc40db 2381
856b8cd0 2382static JSStaticValue Selector_staticValues[2] = {
61933e16 2383 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
04450da0
JF
2384 {NULL, NULL, NULL, 0}
2385};
953647c1 2386
365abb0a 2387static JSStaticValue Instance_staticValues[5] = {
9e562cfc 2388 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
365abb0a 2389 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2f1295ff 2390 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
9e562cfc 2391 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
9b5527f0
JF
2392 {NULL, NULL, NULL, 0}
2393};
2394
95221eed 2395static JSStaticFunction Instance_staticFunctions[7] = {
7b184c00 2396 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b4aa79af
JF
2397 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2398 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
95221eed 2399 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
20ded97a 2400 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0
JF
2401 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2402 {NULL, NULL, 0}
2403};
2404
9b5527f0
JF
2405static JSStaticFunction Internal_staticFunctions[2] = {
2406 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2407 {NULL, NULL, 0}
2408};
2409
b4aa79af
JF
2410static JSStaticFunction Selector_staticFunctions[5] = {
2411 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2412 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0 2413 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b09da87b
JF
2414 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2415 {NULL, NULL, 0}
2416};
ea2d184c 2417
3c9f7e22 2418void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
37954781
JF
2419 apr_pool_t *pool(CYGetGlobalPool());
2420
807a88be
JF
2421 Object_type = new(pool) Type_privateData("@");
2422 Selector_type = new(pool) Type_privateData(":");
7b184c00 2423
b53b30c1 2424#ifdef __APPLE__
c1582939 2425 NSCFBoolean_ = objc_getClass("NSCFBoolean");
c239b9f8 2426 NSCFType_ = objc_getClass("NSCFType");
aaa4a269 2427 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
b5dd57dc
JF
2428 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2429 NSZombie_ = objc_getClass("_NSZombie_");
c074e774
JF
2430#else
2431 NSBoolNumber_ = objc_getClass("NSBoolNumber");
b53b30c1
JF
2432#endif
2433
2434 NSArray_ = objc_getClass("NSArray");
b5dd57dc 2435 NSDictionary_ = objc_getClass("NSDictionary");
4cb8aa43 2436 NSString_ = objc_getClass("NSString");
c239b9f8 2437 Object_ = objc_getClass("Object");
3c1c3635
JF
2438
2439 JSClassDefinition definition;
2440
2441 definition = kJSClassDefinitionEmpty;
2442 definition.className = "Instance";
2443 definition.staticValues = Instance_staticValues;
2444 definition.staticFunctions = Instance_staticFunctions;
2445 definition.hasProperty = &Instance_hasProperty;
2446 definition.getProperty = &Instance_getProperty;
2447 definition.setProperty = &Instance_setProperty;
2448 definition.deleteProperty = &Instance_deleteProperty;
2449 definition.getPropertyNames = &Instance_getPropertyNames;
2450 definition.callAsConstructor = &Instance_callAsConstructor;
2451 definition.hasInstance = &Instance_hasInstance;
37954781 2452 definition.finalize = &CYFinalize;
3c1c3635
JF
2453 Instance_ = JSClassCreate(&definition);
2454
2455 definition = kJSClassDefinitionEmpty;
2456 definition.className = "Internal";
2457 definition.staticFunctions = Internal_staticFunctions;
2458 definition.hasProperty = &Internal_hasProperty;
2459 definition.getProperty = &Internal_getProperty;
2460 definition.setProperty = &Internal_setProperty;
2461 definition.getPropertyNames = &Internal_getPropertyNames;
37954781 2462 definition.finalize = &CYFinalize;
3c1c3635
JF
2463 Internal_ = JSClassCreate(&definition);
2464
2465 definition = kJSClassDefinitionEmpty;
2466 definition.className = "Message";
37954781 2467 definition.staticFunctions = cy::Functor::StaticFunctions;
3c1c3635 2468 definition.callAsFunction = &Message_callAsFunction;
37954781 2469 definition.finalize = &CYFinalize;
3c1c3635
JF
2470 Message_ = JSClassCreate(&definition);
2471
2472 definition = kJSClassDefinitionEmpty;
2473 definition.className = "Messages";
2474 definition.hasProperty = &Messages_hasProperty;
2475 definition.getProperty = &Messages_getProperty;
2476 definition.setProperty = &Messages_setProperty;
7c6c5b0a 2477#if 0 && OBJC_API_VERSION < 2
3c1c3635
JF
2478 definition.deleteProperty = &Messages_deleteProperty;
2479#endif
2480 definition.getPropertyNames = &Messages_getPropertyNames;
37954781 2481 definition.finalize = &CYFinalize;
3c1c3635
JF
2482 Messages_ = JSClassCreate(&definition);
2483
2484 definition = kJSClassDefinitionEmpty;
2485 definition.className = "Selector";
2486 definition.staticValues = Selector_staticValues;
2487 definition.staticFunctions = Selector_staticFunctions;
2488 definition.callAsFunction = &Selector_callAsFunction;
37954781 2489 definition.finalize = &CYFinalize;
3c1c3635
JF
2490 Selector_ = JSClassCreate(&definition);
2491
2492 definition = kJSClassDefinitionEmpty;
2493 definition.className = "Super";
2494 definition.staticFunctions = Internal_staticFunctions;
37954781 2495 definition.finalize = &CYFinalize;
3c1c3635
JF
2496 Super_ = JSClassCreate(&definition);
2497
2498 definition = kJSClassDefinitionEmpty;
2499 definition.className = "ObjectiveC::Classes";
2500 definition.getProperty = &ObjectiveC_Classes_getProperty;
2501 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2502 ObjectiveC_Classes_ = JSClassCreate(&definition);
2503
26ef7a82
JF
2504 definition = kJSClassDefinitionEmpty;
2505 definition.className = "ObjectiveC::Constants";
2506 definition.getProperty = &ObjectiveC_Constants_getProperty;
2507 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2508 ObjectiveC_Constants_ = JSClassCreate(&definition);
2509
7c6c5b0a 2510#if OBJC_API_VERSION >= 2
3c1c3635
JF
2511 definition = kJSClassDefinitionEmpty;
2512 definition.className = "ObjectiveC::Images";
2513 definition.getProperty = &ObjectiveC_Images_getProperty;
2514 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2515 ObjectiveC_Images_ = JSClassCreate(&definition);
2516
2517 definition = kJSClassDefinitionEmpty;
2518 definition.className = "ObjectiveC::Image::Classes";
2519 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2520 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2521 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3c9f7e22 2522#endif
3c1c3635 2523
3c9f7e22
JF
2524 definition = kJSClassDefinitionEmpty;
2525 definition.className = "ObjectiveC::Protocols";
2526 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2527 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2528 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2529
8ad1528b 2530#if defined(__APPLE__) && defined(__arm__) && 0
3c9f7e22
JF
2531 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2532#endif
2533
2534#ifdef __APPLE__
2535 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2536#endif
2537} CYPoolCatch() }
2538
2539void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2540 JSObjectRef global(CYGetGlobalObject(context));
498c3570 2541 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2385c806
JF
2542 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2543 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
26ef7a82 2544 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
3c9f7e22
JF
2545
2546 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2385c806 2547 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
3c9f7e22 2548
26ef7a82
JF
2549 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2550 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2551 CYArrayPush(context, alls, protocols);
2552
2553 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2554 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2555 CYArrayPush(context, alls, classes);
2556
2557 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2558 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2559 CYArrayPush(context, alls, constants);
3c9f7e22
JF
2560
2561#if OBJC_API_VERSION >= 2
3c1c3635 2562 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
aabea98c 2563#endif
3c1c3635
JF
2564
2565 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2566 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2567 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2568 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2569
498c3570
JF
2570 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2571 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3c1c3635 2572
4a2eef6c
JF
2573 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, Instance_, NULL));
2574 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2575 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2576 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2577 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2578
11f3e89e
JF
2579 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, Instance_, NULL));
2580 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2581 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2582 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2583 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2584
4a2eef6c 2585 JSObjectRef StringInstance(JSObjectMakeConstructor(context, Instance_, NULL));
6732f195
JF
2586 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2587 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
6732f195
JF
2588 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2589 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2590
2385c806
JF
2591 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2592 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2593 CYSetProperty(context, cycript, CYJSString("Super"), Super);
3c1c3635 2594
f2f0d1d1
JF
2595 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2596 CYSetProperty(context, Instance, CYJSString("box"), box);
2597
8ad1528b 2598#if defined(__APPLE__) && defined(__arm__) && 0
98ea05a3 2599 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
b5dd57dc
JF
2600#endif
2601
98ea05a3 2602 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3c1c3635 2603
498c3570
JF
2604 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2605 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2606 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3c9f7e22 2607} CYPoolCatch() }
b5dd57dc
JF
2608
2609static CYHooks CYObjectiveCHooks = {
2610 &CYObjectiveC_ExecuteStart,
2611 &CYObjectiveC_ExecuteEnd,
b5dd57dc 2612 &CYObjectiveC_CallFunction,
3c9f7e22 2613 &CYObjectiveC_Initialize,
b5dd57dc
JF
2614 &CYObjectiveC_SetupContext,
2615 &CYObjectiveC_PoolFFI,
2616 &CYObjectiveC_FromFFI,
2617};
2618
2619struct CYObjectiveC {
2620 CYObjectiveC() {
2621 hooks_ = &CYObjectiveCHooks;
6faa533c
DWT
2622 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2623 _assert(hooks_ != NULL);
b5dd57dc
JF
2624 }
2625} CYObjectiveC;