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