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