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