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