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