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