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