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