]> git.saurik.com Git - cycript.git/blob - ObjectiveC/Library.mm
1f2aea2c1fc4f32bdbf3e43d72fe6493f66b4017
[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
70 #include <cmath>
71 #include <map>
72
73 #define CYObjectiveTry_(context) { \
74 JSContextRef context_(context); \
75 try
76 #define CYObjectiveTry { \
77 try
78 #define CYObjectiveCatch \
79 catch (const CYException &error) { \
80 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
81 } \
82 }
83
84 #define CYPoolTry { \
85 id _saved(nil); \
86 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
87 @try
88 #define CYPoolCatch(value) \
89 @catch (NSException *error) { \
90 _saved = [error retain]; \
91 throw CYJSError(context, CYCastJSValue(context, error)); \
92 return value; \
93 } @finally { \
94 [_pool release]; \
95 if (_saved != nil) \
96 [_saved autorelease]; \
97 } \
98 }
99
100 #define CYSadTry { \
101 @try
102 #define CYSadCatch(value) \
103 @catch (NSException *error ) { \
104 throw CYJSError(context, CYCastJSValue(context, error)); \
105 return value; \
106 } \
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 extern sqlite3 *Bridge_;
150
151 /* Objective-C Pool Release {{{ */
152 apr_status_t CYPoolRelease_(void *data) {
153 id object(reinterpret_cast<id>(data));
154 [object release];
155 return APR_SUCCESS;
156 }
157
158 id CYPoolRelease_(apr_pool_t *pool, id object) {
159 if (object == nil)
160 return nil;
161 else if (pool == NULL)
162 return [object autorelease];
163 else {
164 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
165 return object;
166 }
167 }
168
169 template <typename Type_>
170 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
171 return (Type_) CYPoolRelease_(pool, (id) object);
172 }
173 /* }}} */
174 /* Objective-C Strings {{{ */
175 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
176 if (pool == NULL)
177 return [value UTF8String];
178 else {
179 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
180 char *string(new(pool) char[size]);
181 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
182 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
183 return string;
184 }
185 }
186
187 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
188 #ifdef __APPLE__
189 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
190 #else
191 CYPool pool;
192 return CYCopyJSString(CYPoolCString(pool, context, value));
193 #endif
194 }
195
196 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
197 if (value == nil)
198 return NULL;
199 // XXX: this definition scares me; is anyone using this?!
200 NSString *string([value description]);
201 return CYCopyJSString(context, string);
202 }
203
204 NSString *CYCopyNSString(const CYUTF8String &value) {
205 #ifdef __APPLE__
206 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
207 #else
208 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
209 #endif
210 }
211
212 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
213 #ifdef __APPLE__
214 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
215 #else
216 CYPool pool;
217 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
218 #endif
219 }
220
221 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
222 return CYCopyNSString(context, CYJSString(context, value));
223 }
224
225 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
226 return CYPoolRelease(pool, CYCopyNSString(value));
227 }
228
229 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
230 const char *name(sel_getName(sel));
231 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
232 }
233
234 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
235 return CYPoolRelease(pool, CYCopyNSString(context, value));
236 }
237
238 CYUTF8String CYCastUTF8String(NSString *value) {
239 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
240 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
241 }
242 /* }}} */
243
244 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
245
246 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
247 if (exception == NULL)
248 throw error;
249 *exception = CYCastJSValue(context, error);
250 }
251
252 size_t CYGetIndex(NSString *value) {
253 return CYGetIndex(CYCastUTF8String(value));
254 }
255
256 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
257 return CYGetOffset(CYPoolCString(pool, context, value), index);
258 }
259
260 static JSClassRef Instance_;
261 static JSClassRef Internal_;
262 static JSClassRef Message_;
263 static JSClassRef Messages_;
264 static JSClassRef Selector_;
265 static JSClassRef Super_;
266
267 static JSClassRef ObjectiveC_Classes_;
268 static JSClassRef ObjectiveC_Protocols_;
269
270 #ifdef __APPLE__
271 static JSClassRef ObjectiveC_Image_Classes_;
272 static JSClassRef ObjectiveC_Images_;
273 #endif
274
275 #ifdef __APPLE__
276 static Class NSCFBoolean_;
277 static Class NSCFType_;
278 static Class NSMessageBuilder_;
279 static Class NSZombie_;
280 #else
281 static Class NSBoolNumber_;
282 #endif
283
284 static Class NSArray_;
285 static Class NSDictionary_;
286 static Class Object_;
287
288 static Type_privateData *Object_type;
289 static Type_privateData *Selector_type;
290
291 Type_privateData *Instance::GetType() const {
292 return Object_type;
293 }
294
295 Type_privateData *Selector_privateData::GetType() const {
296 return Selector_type;
297 }
298
299 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
300 if (self == nil)
301 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
302
303 JSObjectRef global(CYGetGlobalObject(context));
304 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
305
306 char label[32];
307 sprintf(label, "i%p", self);
308 CYJSString name(label);
309
310 JSValueRef value(CYGetProperty(context, cy, name));
311 if (!JSValueIsUndefined(context, value))
312 return value;
313
314 JSClassRef _class(NULL);
315 JSValueRef prototype;
316
317 if (self == NSArray_)
318 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
319 else if (self == NSDictionary_)
320 prototype = CYGetCachedObject(context, CYJSString("Object_prototype"));
321 else
322 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
323
324 JSObjectRef object(JSObjectMake(context, _class, NULL));
325 JSObjectSetPrototype(context, object, prototype);
326 CYSetProperty(context, cy, name, object);
327 return object;
328 }
329
330 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
331 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
332 if (_class == NSArray_)
333 array = true;
334 if (Class super = class_getSuperclass(_class))
335 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
336 /*else if (array)
337 JSObjectSetPrototype(context, value, Array_prototype_);*/
338 return value;
339 }
340
341 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
342 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
343 }
344
345 namespace cy {
346 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
347 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
348 return value;
349 } }
350
351 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
352 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
353 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
354 return value;
355 }
356
357 Instance::~Instance() {
358 if ((flags_ & Transient) == 0)
359 // XXX: does this handle background threads correctly?
360 // XXX: this simply does not work on the console because I'm stupid
361 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
362 }
363
364 struct Message_privateData :
365 cy::Functor
366 {
367 SEL sel_;
368
369 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
370 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
371 sel_(sel)
372 {
373 }
374 };
375
376 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
377 Instance::Flags flags;
378
379 if (transient)
380 flags = Instance::Transient;
381 else {
382 flags = Instance::None;
383 object = [object retain];
384 }
385
386 return Instance::Make(context, object, flags);
387 }
388
389 @interface NSMethodSignature (Cycript)
390 - (NSString *) _typeString;
391 @end
392
393 @interface NSObject (Cycript)
394
395 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
396 - (JSType) cy$JSType;
397
398 - (NSObject *) cy$toJSON:(NSString *)key;
399 - (NSString *) cy$toCYON;
400 - (NSString *) cy$toKey;
401
402 - (bool) cy$hasProperty:(NSString *)name;
403 - (NSObject *) cy$getProperty:(NSString *)name;
404 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
405 - (bool) cy$deleteProperty:(NSString *)name;
406 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
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 @end
839 /* }}} */
840 /* Bridge: NSMutableArray {{{ */
841 @implementation NSMutableArray (Cycript)
842
843 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
844 if ([name isEqualToString:@"length"]) {
845 // XXX: is this not intelligent?
846 NSNumber *number(reinterpret_cast<NSNumber *>(value));
847 #ifdef __APPLE__
848 NSUInteger size([number unsignedIntegerValue]);
849 #else
850 NSUInteger size([number unsignedIntValue]);
851 #endif
852 NSUInteger count([self count]);
853 if (size < count)
854 [self removeObjectsInRange:NSMakeRange(size, count - size)];
855 else if (size != count) {
856 WebUndefined *undefined([WebUndefined undefined]);
857 for (size_t i(count); i != size; ++i)
858 [self addObject:undefined];
859 }
860 return true;
861 }
862
863 size_t index(CYGetIndex(name));
864 if (index == _not(size_t))
865 return [super cy$setProperty:name to:value];
866
867 id object(value ?: [NSNull null]);
868
869 size_t count([self count]);
870 if (index < count)
871 [self replaceObjectAtIndex:index withObject:object];
872 else {
873 if (index != count) {
874 WebUndefined *undefined([WebUndefined undefined]);
875 for (size_t i(count); i != index; ++i)
876 [self addObject:undefined];
877 }
878
879 [self addObject:object];
880 }
881
882 return true;
883 }
884
885 - (bool) cy$deleteProperty:(NSString *)name {
886 size_t index(CYGetIndex(name));
887 if (index == _not(size_t) || index >= [self count])
888 return [super cy$deleteProperty:name];
889 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
890 return true;
891 }
892
893 @end
894 /* }}} */
895 /* Bridge: NSMutableDictionary {{{ */
896 @implementation NSMutableDictionary (Cycript)
897
898 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
899 [self setObject:(value ?: [NSNull null]) forKey:name];
900 return true;
901 }
902
903 - (bool) cy$deleteProperty:(NSString *)name {
904 if ([self objectForKey:name] == nil)
905 return false;
906 else {
907 [self removeObjectForKey:name];
908 return true;
909 }
910 }
911
912 @end
913 /* }}} */
914 /* Bridge: NSNumber {{{ */
915 @implementation NSNumber (Cycript)
916
917 - (JSType) cy$JSType {
918 #ifdef __APPLE__
919 // XXX: this just seems stupid
920 if ([self class] == NSCFBoolean_)
921 return kJSTypeBoolean;
922 #endif
923 return kJSTypeNumber;
924 }
925
926 - (NSObject *) cy$toJSON:(NSString *)key {
927 return self;
928 }
929
930 - (NSString *) cy$toCYON {
931 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
932 }
933
934 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
935 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
936 } CYObjectiveCatch }
937
938 @end
939 /* }}} */
940 /* Bridge: NSNull {{{ */
941 @implementation NSNull (Cycript)
942
943 - (JSType) cy$JSType {
944 return kJSTypeNull;
945 }
946
947 - (NSObject *) cy$toJSON:(NSString *)key {
948 return self;
949 }
950
951 - (NSString *) cy$toCYON {
952 return @"null";
953 }
954
955 @end
956 /* }}} */
957 /* Bridge: NSObject {{{ */
958 @implementation NSObject (Cycript)
959
960 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
961 return CYMakeInstance(context, self, false);
962 } CYObjectiveCatch }
963
964 - (JSType) cy$JSType {
965 return kJSTypeObject;
966 }
967
968 - (NSObject *) cy$toJSON:(NSString *)key {
969 return [self description];
970 }
971
972 - (NSString *) cy$toCYON {
973 return [[self cy$toJSON:@""] cy$toCYON];
974 }
975
976 - (NSString *) cy$toKey {
977 return [self cy$toCYON];
978 }
979
980 - (bool) cy$hasProperty:(NSString *)name {
981 return false;
982 }
983
984 - (NSObject *) cy$getProperty:(NSString *)name {
985 return nil;
986 }
987
988 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
989 return false;
990 }
991
992 - (bool) cy$deleteProperty:(NSString *)name {
993 return false;
994 }
995
996 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
997 }
998
999 @end
1000 /* }}} */
1001 /* Bridge: NSProxy {{{ */
1002 @implementation NSProxy (Cycript)
1003
1004 - (NSObject *) cy$toJSON:(NSString *)key {
1005 return [self description];
1006 }
1007
1008 - (NSString *) cy$toCYON {
1009 return [[self cy$toJSON:@""] cy$toCYON];
1010 }
1011
1012 @end
1013 /* }}} */
1014 /* Bridge: NSString {{{ */
1015 @implementation NSString (Cycript)
1016
1017 - (JSType) cy$JSType {
1018 return kJSTypeString;
1019 }
1020
1021 - (NSObject *) cy$toJSON:(NSString *)key {
1022 return self;
1023 }
1024
1025 - (NSString *) cy$toCYON {
1026 std::ostringstream str;
1027 CYUTF8String string(CYCastUTF8String(self));
1028 CYStringify(str, string.data, string.size);
1029 std::string value(str.str());
1030 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1031 }
1032
1033 - (NSString *) cy$toKey {
1034 if (CYIsKey(CYCastUTF8String(self)))
1035 return self;
1036 return [self cy$toCYON];
1037 }
1038
1039 @end
1040 /* }}} */
1041 /* Bridge: WebUndefined {{{ */
1042 @implementation WebUndefined (Cycript)
1043
1044 - (JSType) cy$JSType {
1045 return kJSTypeUndefined;
1046 }
1047
1048 - (NSObject *) cy$toJSON:(NSString *)key {
1049 return self;
1050 }
1051
1052 - (NSString *) cy$toCYON {
1053 return @"undefined";
1054 }
1055
1056 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1057 return CYJSUndefined(context);
1058 } CYObjectiveCatch }
1059
1060 @end
1061 /* }}} */
1062
1063 static bool CYIsClass(id self) {
1064 #ifdef __APPLE__
1065 // XXX: this is a lame object_isClass
1066 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1067 #else
1068 return GSObjCIsClass(self);
1069 #endif
1070 }
1071
1072 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1073 id self(CYCastNSObject(pool, context, value));
1074 if (CYIsClass(self))
1075 return (Class) self;
1076 throw CYJSError(context, "got something that is not a Class");
1077 return NULL;
1078 }
1079
1080 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1081 CYPool pool;
1082 size_t size(JSPropertyNameArrayGetCount(names));
1083 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1084 for (size_t index(0); index != size; ++index)
1085 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1086 return array;
1087 }
1088
1089 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1090 if (value == nil)
1091 return CYJSNull(context);
1092 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1093 return [value cy$JSValueInContext:context];
1094 else
1095 return CYMakeInstance(context, value, false);
1096 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1097
1098 @implementation CYJSObject
1099
1100 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1101 if ((self = [super init]) != nil) {
1102 object_ = object;
1103 context_ = CYGetJSContext(context);
1104 //XXX:JSGlobalContextRetain(context_);
1105 JSValueProtect(context_, object_);
1106 } return self;
1107 } CYObjectiveCatch }
1108
1109 - (void) dealloc { CYObjectiveTry {
1110 JSValueUnprotect(context_, object_);
1111 //XXX:JSGlobalContextRelease(context_);
1112 [super dealloc];
1113 } CYObjectiveCatch }
1114
1115 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1116 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1117 if (!CYIsCallable(context_, toJSON))
1118 return [super cy$toJSON:key];
1119 else {
1120 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1121 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1122 // XXX: do I really want an NSNull here?!
1123 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1124 }
1125 } CYObjectiveCatch }
1126
1127 - (NSString *) cy$toCYON { CYObjectiveTry {
1128 CYPool pool;
1129 JSValueRef exception(NULL);
1130 const char *cyon(CYPoolCCYON(pool, context_, object_));
1131 CYThrow(context_, exception);
1132 if (cyon == NULL)
1133 return [super cy$toCYON];
1134 else
1135 return [NSString stringWithUTF8String:cyon];
1136 } CYObjectiveCatch }
1137
1138 - (NSUInteger) count { CYObjectiveTry {
1139 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1140 size_t size(JSPropertyNameArrayGetCount(names));
1141 JSPropertyNameArrayRelease(names);
1142 return size;
1143 } CYObjectiveCatch }
1144
1145 - (id) objectForKey:(id)key { CYObjectiveTry {
1146 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1147 if (JSValueIsUndefined(context_, value))
1148 return nil;
1149 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1150 } CYObjectiveCatch }
1151
1152 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1153 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1154 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1155 JSPropertyNameArrayRelease(names);
1156 return enumerator;
1157 } CYObjectiveCatch }
1158
1159 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1160 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1161 } CYObjectiveCatch }
1162
1163 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1164 JSValueRef exception(NULL);
1165 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1166 CYThrow(context_, exception);
1167 } CYObjectiveCatch }
1168
1169 @end
1170
1171 @implementation CYJSArray
1172
1173 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1174 if ((self = [super init]) != nil) {
1175 object_ = object;
1176 context_ = CYGetJSContext(context);
1177 //XXX:JSGlobalContextRetain(context_);
1178 JSValueProtect(context_, object_);
1179 } return self;
1180 } CYObjectiveCatch }
1181
1182 - (void) dealloc { CYObjectiveTry {
1183 JSValueUnprotect(context_, object_);
1184 //XXX:JSGlobalContextRelease(context_);
1185 [super dealloc];
1186 } CYObjectiveCatch }
1187
1188 - (NSUInteger) count { CYObjectiveTry {
1189 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
1190 } CYObjectiveCatch }
1191
1192 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1193 size_t bounds([self count]);
1194 if (index >= bounds)
1195 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1196 JSValueRef exception(NULL);
1197 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1198 CYThrow(context_, exception);
1199 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1200 } CYObjectiveCatch }
1201
1202 - (void) addObject:(id)object { CYObjectiveTry {
1203 JSValueRef exception(NULL);
1204 JSValueRef arguments[1];
1205 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
1206 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1207 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
1208 CYThrow(context_, exception);
1209 } CYObjectiveCatch }
1210
1211 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1212 size_t bounds([self count] + 1);
1213 if (index >= bounds)
1214 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1215 JSValueRef exception(NULL);
1216 JSValueRef arguments[3];
1217 arguments[0] = CYCastJSValue(context_, index);
1218 arguments[1] = CYCastJSValue(context_, 0);
1219 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1220 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1221 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1222 CYThrow(context_, exception);
1223 } CYObjectiveCatch }
1224
1225 - (void) removeLastObject { CYObjectiveTry {
1226 JSValueRef exception(NULL);
1227 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1228 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1229 CYThrow(context_, exception);
1230 } CYObjectiveCatch }
1231
1232 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1233 size_t bounds([self count]);
1234 if (index >= bounds)
1235 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1236 JSValueRef exception(NULL);
1237 JSValueRef arguments[2];
1238 arguments[0] = CYCastJSValue(context_, index);
1239 arguments[1] = CYCastJSValue(context_, 1);
1240 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1241 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1242 CYThrow(context_, exception);
1243 } CYObjectiveCatch }
1244
1245 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1246 size_t bounds([self count]);
1247 if (index >= bounds)
1248 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1249 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1250 } CYObjectiveCatch }
1251
1252 @end
1253
1254 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1255 struct CYInternal :
1256 CYData
1257 {
1258 JSObjectRef object_;
1259
1260 CYInternal() :
1261 object_(NULL)
1262 {
1263 }
1264
1265 ~CYInternal() {
1266 // XXX: delete object_? ;(
1267 }
1268
1269 static CYInternal *Get(id self) {
1270 CYInternal *internal(NULL);
1271 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1272 // XXX: do something epic? ;P
1273 }
1274
1275 return internal;
1276 }
1277
1278 static CYInternal *Set(id self) {
1279 CYInternal *internal(NULL);
1280 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1281 if (internal == NULL) {
1282 internal = new CYInternal();
1283 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1284 }
1285 } else {
1286 // XXX: do something epic? ;P
1287 }
1288
1289 return internal;
1290 }
1291
1292 bool HasProperty(JSContextRef context, JSStringRef name) {
1293 if (object_ == NULL)
1294 return false;
1295 return JSObjectHasProperty(context, object_, name);
1296 }
1297
1298 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1299 if (object_ == NULL)
1300 return NULL;
1301 return CYGetProperty(context, object_, name);
1302 }
1303
1304 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1305 if (object_ == NULL)
1306 object_ = JSObjectMake(context, NULL, NULL);
1307 CYSetProperty(context, object_, name, value);
1308 }
1309 };
1310
1311 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1312 Selector_privateData *internal(new Selector_privateData(sel));
1313 return JSObjectMake(context, Selector_, internal);
1314 }
1315
1316 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1317 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1318 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1319 return reinterpret_cast<SEL>(internal->value_);
1320 } else
1321 return CYCastPointer<SEL>(context, value);
1322 }
1323
1324 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1325 return (void *) [[NSAutoreleasePool alloc] init];
1326 } CYSadCatch(NULL) }
1327
1328 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1329 return [(NSAutoreleasePool *) handle release];
1330 } CYSadCatch() }
1331
1332 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1333 if (name == "nil")
1334 return Instance::Make(context, nil);
1335 if (Class _class = objc_getClass(name.data))
1336 return CYMakeInstance(context, _class, 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 case sig::object_P:
1347 case sig::typename_P:
1348 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1349 break;
1350
1351 case sig::selector_P:
1352 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1353 break;
1354
1355 default:
1356 return false;
1357 }
1358
1359 return true;
1360 } CYSadCatch(false) }
1361
1362 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1363 switch (type->primitive) {
1364 case sig::object_P:
1365 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1366 JSValueRef value(CYCastJSValue(context, object));
1367 if (initialize)
1368 [object release];
1369 return value;
1370 } else goto null;
1371
1372 case sig::typename_P:
1373 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1374
1375 case sig::selector_P:
1376 if (SEL sel = *reinterpret_cast<SEL *>(data))
1377 return CYMakeSelector(context, sel);
1378 else goto null;
1379
1380 null:
1381 return CYJSNull(context);
1382 default:
1383 return NULL;
1384 }
1385 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1386
1387 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1388 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1389 if (!devoid)
1390 return true;
1391 #if OBJC_API_VERSION >= 2
1392 char type[16];
1393 method_getReturnType(method, type, sizeof(type));
1394 #else
1395 const char *type(method_getTypeEncoding(method));
1396 #endif
1397 if (type[0] != 'v')
1398 return true;
1399 }
1400
1401 // XXX: possibly use a more "awesome" check?
1402 return false;
1403 }
1404
1405 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1406 if (method != NULL)
1407 return method_getTypeEncoding(method);
1408
1409 const char *name(sel_getName(sel));
1410
1411 sqlite3_stmt *statement;
1412
1413 _sqlcall(sqlite3_prepare(Bridge_,
1414 "select "
1415 "\"bridge\".\"value\" "
1416 "from \"bridge\" "
1417 "where"
1418 " \"bridge\".\"mode\" = -1 and"
1419 " \"bridge\".\"name\" = ?"
1420 " limit 1"
1421 , -1, &statement, NULL));
1422
1423 _trace();
1424 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
1425
1426 const char *value;
1427 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
1428 _trace();
1429 value = NULL;}
1430 else {
1431 _trace();
1432 value = sqlite3_column_pooled(pool, statement, 0);
1433 }
1434
1435 _sqlcall(sqlite3_finalize(statement));
1436
1437 if (value != NULL)
1438 return value;
1439 _trace();
1440 return NULL;
1441 }
1442
1443 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1444 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1445
1446 JSContextRef context(internal->context_);
1447
1448 size_t count(internal->cif_.nargs);
1449 JSValueRef values[count];
1450
1451 for (size_t index(0); index != count; ++index)
1452 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1453
1454 JSObjectRef _this(CYCastJSObject(context, values[0]));
1455
1456 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1457 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1458 }
1459
1460 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1461 Message_privateData *internal(new Message_privateData(sel, type, imp));
1462 return JSObjectMake(context, Message_, internal);
1463 }
1464
1465 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1466 JSObjectRef function(CYCastJSObject(context, value));
1467 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1468 // XXX: see notes in Library.cpp about needing to leak
1469 return reinterpret_cast<IMP>(internal->GetValue());
1470 }
1471
1472 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1473 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1474 Class _class(internal->GetValue());
1475
1476 CYPool pool;
1477 const char *name(CYPoolCString(pool, context, property));
1478
1479 if (SEL sel = sel_getUid(name))
1480 if (class_getInstanceMethod(_class, sel) != NULL)
1481 return true;
1482
1483 return false;
1484 }
1485
1486 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1487 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1488 Class _class(internal->GetValue());
1489
1490 CYPool pool;
1491 const char *name(CYPoolCString(pool, context, property));
1492
1493 if (SEL sel = sel_getUid(name))
1494 if (objc_method *method = class_getInstanceMethod(_class, sel))
1495 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1496
1497 return NULL;
1498 }
1499
1500 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1501 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1502 Class _class(internal->GetValue());
1503
1504 CYPool pool;
1505 const char *name(CYPoolCString(pool, context, property));
1506
1507 SEL sel(sel_registerName(name));
1508
1509 objc_method *method(class_getInstanceMethod(_class, sel));
1510
1511 const char *type;
1512 IMP imp;
1513
1514 if (JSValueIsObjectOfClass(context, value, Message_)) {
1515 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1516 type = sig::Unparse(pool, &message->signature_);
1517 imp = reinterpret_cast<IMP>(message->GetValue());
1518 } else {
1519 type = CYPoolTypeEncoding(pool, context, sel, method);
1520 imp = CYMakeMessage(context, value, type);
1521 }
1522
1523 if (method != NULL)
1524 method_setImplementation(method, imp);
1525 else {
1526 #ifdef GNU_RUNTIME
1527 GSMethodList list(GSAllocMethodList(1));
1528 GSAppendMethodToList(list, sel, type, imp, YES);
1529 GSAddMethodList(_class, list, YES);
1530 GSFlushMethodCacheForClass(_class);
1531 #else
1532 class_addMethod(_class, sel, imp, type);
1533 #endif
1534 }
1535
1536 return true;
1537 }
1538
1539 #if 0 && OBJC_API_VERSION < 2
1540 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1541 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1542 Class _class(internal->GetValue());
1543
1544 CYPool pool;
1545 const char *name(CYPoolCString(pool, context, property));
1546
1547 if (SEL sel = sel_getUid(name))
1548 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1549 objc_method_list list = {NULL, 1, {method}};
1550 class_removeMethods(_class, &list);
1551 return true;
1552 }
1553
1554 return false;
1555 }
1556 #endif
1557
1558 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1559 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1560 Class _class(internal->GetValue());
1561
1562 #if OBJC_API_VERSION >= 2
1563 unsigned int size;
1564 objc_method **data(class_copyMethodList(_class, &size));
1565 for (size_t i(0); i != size; ++i)
1566 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1567 free(data);
1568 #else
1569 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1570 for (int i(0); i != methods->method_count; ++i)
1571 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1572 #endif
1573 }
1574
1575 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1576 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1577 id self(internal->GetValue());
1578
1579 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1580 return true;
1581
1582 CYPool pool;
1583 NSString *name(CYCastNSString(pool, context, property));
1584
1585 if (CYInternal *internal = CYInternal::Get(self))
1586 if (internal->HasProperty(context, property))
1587 return true;
1588
1589 Class _class(object_getClass(self));
1590
1591 CYPoolTry {
1592 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1593 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1594 if ([self cy$hasProperty:name])
1595 return true;
1596 } CYPoolCatch(false)
1597
1598 const char *string(CYPoolCString(pool, context, name));
1599
1600 #ifdef __APPLE__
1601 if (class_getProperty(_class, string) != NULL)
1602 return true;
1603 #endif
1604
1605 if (SEL sel = sel_getUid(string))
1606 if (CYImplements(self, _class, sel, true))
1607 return true;
1608
1609 return false;
1610 }
1611
1612 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1613 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1614 id self(internal->GetValue());
1615
1616 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1617 return Internal::Make(context, self, object);
1618
1619 CYPool pool;
1620 NSString *name(CYCastNSString(pool, context, property));
1621
1622 if (CYInternal *internal = CYInternal::Get(self))
1623 if (JSValueRef value = internal->GetProperty(context, property))
1624 return value;
1625
1626 CYPoolTry {
1627 if (NSObject *data = [self cy$getProperty:name])
1628 return CYCastJSValue(context, data);
1629 } CYPoolCatch(NULL)
1630
1631 const char *string(CYPoolCString(pool, context, name));
1632 Class _class(object_getClass(self));
1633
1634 #ifdef __APPLE__
1635 if (objc_property_t property = class_getProperty(_class, string)) {
1636 PropertyAttributes attributes(property);
1637 SEL sel(sel_registerName(attributes.Getter()));
1638 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1639 }
1640 #endif
1641
1642 if (SEL sel = sel_getUid(string))
1643 if (CYImplements(self, _class, sel, true))
1644 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1645
1646 return NULL;
1647 } CYCatch }
1648
1649 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1650 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1651 id self(internal->GetValue());
1652
1653 CYPool pool;
1654
1655 NSString *name(CYCastNSString(pool, context, property));
1656 NSObject *data(CYCastNSObject(pool, context, value));
1657
1658 CYPoolTry {
1659 if ([self cy$setProperty:name to:data])
1660 return true;
1661 } CYPoolCatch(NULL)
1662
1663 const char *string(CYPoolCString(pool, context, name));
1664 Class _class(object_getClass(self));
1665
1666 #ifdef __APPLE__
1667 if (objc_property_t property = class_getProperty(_class, string)) {
1668 PropertyAttributes attributes(property);
1669 if (const char *setter = attributes.Setter()) {
1670 SEL sel(sel_registerName(setter));
1671 JSValueRef arguments[1] = {value};
1672 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1673 return true;
1674 }
1675 }
1676 #endif
1677
1678 size_t length(strlen(string));
1679
1680 char set[length + 5];
1681
1682 set[0] = 's';
1683 set[1] = 'e';
1684 set[2] = 't';
1685
1686 if (string[0] != '\0') {
1687 set[3] = toupper(string[0]);
1688 memcpy(set + 4, string + 1, length - 1);
1689 }
1690
1691 set[length + 3] = ':';
1692 set[length + 4] = '\0';
1693
1694 if (SEL sel = sel_getUid(set))
1695 if (CYImplements(self, _class, sel, false)) {
1696 JSValueRef arguments[1] = {value};
1697 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1698 }
1699
1700 if (CYInternal *internal = CYInternal::Set(self)) {
1701 internal->SetProperty(context, property, value);
1702 return true;
1703 }
1704
1705 return false;
1706 } CYCatch }
1707
1708 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1709 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1710 id self(internal->GetValue());
1711
1712 CYPoolTry {
1713 NSString *name(CYCastNSString(NULL, context, property));
1714 return [self cy$deleteProperty:name];
1715 } CYPoolCatch(NULL)
1716 } CYCatch return /*XXX*/ NULL; }
1717
1718 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1719 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1720 id self(internal->GetValue());
1721
1722 CYPool pool;
1723 Class _class(object_getClass(self));
1724
1725 #ifdef __APPLE__
1726 {
1727 unsigned int size;
1728 objc_property_t *data(class_copyPropertyList(_class, &size));
1729 for (size_t i(0); i != size; ++i)
1730 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1731 free(data);
1732 }
1733 #endif
1734
1735 CYPoolTry {
1736 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1737 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1738 [self cy$getPropertyNames:names inContext:context];
1739 } CYPoolCatch()
1740 }
1741
1742 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1743 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1744 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1745 return value;
1746 } CYCatch }
1747
1748 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1749 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1750 Class _class(internal->GetValue());
1751 if (!CYIsClass(_class))
1752 return false;
1753
1754 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1755 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1756 // XXX: this isn't always safe
1757 return [linternal->GetValue() isKindOfClass:_class];
1758 }
1759
1760 return false;
1761 } CYCatch }
1762
1763 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1764 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1765 CYPool pool;
1766
1767 id self(internal->GetValue());
1768 const char *name(CYPoolCString(pool, context, property));
1769
1770 if (object_getInstanceVariable(self, name, NULL) != NULL)
1771 return true;
1772
1773 return false;
1774 }
1775
1776 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, 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 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1786 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1787 }
1788
1789 return NULL;
1790 } CYCatch }
1791
1792 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
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 (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1800 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1801 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1802 return true;
1803 }
1804
1805 return false;
1806 } CYCatch }
1807
1808 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1809 if (Class super = class_getSuperclass(_class))
1810 Internal_getPropertyNames_(super, names);
1811
1812 #if OBJC_API_VERSION >= 2
1813 unsigned int size;
1814 objc_ivar **data(class_copyIvarList(_class, &size));
1815 for (size_t i(0); i != size; ++i)
1816 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1817 free(data);
1818 #else
1819 if (objc_ivar_list *ivars = _class->ivars)
1820 for (int i(0); i != ivars->ivar_count; ++i)
1821 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1822 #endif
1823 }
1824
1825 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1826 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1827 CYPool pool;
1828
1829 id self(internal->GetValue());
1830 Class _class(object_getClass(self));
1831
1832 Internal_getPropertyNames_(_class, names);
1833 }
1834
1835 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1836 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1837 return internal->GetOwner();
1838 }
1839
1840 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1841 CYPool pool;
1842 NSString *name(CYCastNSString(pool, context, property));
1843 if (Class _class = NSClassFromString(name))
1844 return CYMakeInstance(context, _class, true);
1845 return NULL;
1846 } CYCatch }
1847
1848 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1849 #ifdef __APPLE__
1850 size_t size(objc_getClassList(NULL, 0));
1851 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1852
1853 get:
1854 size_t writ(objc_getClassList(data, size));
1855 if (size < writ) {
1856 size = writ;
1857 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1858 data = copy;
1859 goto get;
1860 } else goto done;
1861 }
1862
1863 for (size_t i(0); i != writ; ++i)
1864 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1865
1866 done:
1867 free(data);
1868 #else
1869 void *state(NULL);
1870 while (Class _class = objc_next_class(&state))
1871 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1872 #endif
1873 }
1874
1875 #if OBJC_API_VERSION >= 2
1876 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1877 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1878
1879 CYPool pool;
1880 const char *name(CYPoolCString(pool, context, property));
1881 unsigned int size;
1882 const char **data(objc_copyClassNamesForImage(internal, &size));
1883 JSValueRef value;
1884 for (size_t i(0); i != size; ++i)
1885 if (strcmp(name, data[i]) == 0) {
1886 if (Class _class = objc_getClass(name)) {
1887 value = CYMakeInstance(context, _class, true);
1888 goto free;
1889 } else
1890 break;
1891 }
1892 value = NULL;
1893 free:
1894 free(data);
1895 return value;
1896 } CYCatch }
1897
1898 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1899 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1900 unsigned int size;
1901 const char **data(objc_copyClassNamesForImage(internal, &size));
1902 for (size_t i(0); i != size; ++i)
1903 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1904 free(data);
1905 }
1906
1907 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1908 CYPool pool;
1909 const char *name(CYPoolCString(pool, context, property));
1910 unsigned int size;
1911 const char **data(objc_copyImageNames(&size));
1912 for (size_t i(0); i != size; ++i)
1913 if (strcmp(name, data[i]) == 0) {
1914 name = data[i];
1915 goto free;
1916 }
1917 name = NULL;
1918 free:
1919 free(data);
1920 if (name == NULL)
1921 return NULL;
1922 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1923 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1924 return value;
1925 } CYCatch }
1926
1927 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1928 unsigned int size;
1929 const char **data(objc_copyImageNames(&size));
1930 for (size_t i(0); i != size; ++i)
1931 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1932 free(data);
1933 }
1934 #endif
1935
1936 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1937 CYPool pool;
1938 const char *name(CYPoolCString(pool, context, property));
1939 if (Protocol *protocol = objc_getProtocol(name))
1940 return CYMakeInstance(context, protocol, true);
1941 return NULL;
1942 } CYCatch }
1943
1944 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1945 #if OBJC_API_VERSION >= 2
1946 unsigned int size;
1947 Protocol **data(objc_copyProtocolList(&size));
1948 for (size_t i(0); i != size; ++i)
1949 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
1950 free(data);
1951 #else
1952 // XXX: fix this!
1953 #endif
1954 }
1955
1956 #ifdef __APPLE__
1957 static bool stret(ffi_type *ffi_type) {
1958 return ffi_type->type == FFI_TYPE_STRUCT && (
1959 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1960 struct_forward_array[ffi_type->size] != 0
1961 );
1962 }
1963 #endif
1964
1965 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 {
1966 const char *type;
1967
1968 if (_class == NULL)
1969 _class = object_getClass(self);
1970
1971 IMP imp;
1972
1973 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
1974 imp = method_getImplementation(method);
1975 type = method_getTypeEncoding(method);
1976 } else {
1977 imp = NULL;
1978
1979 CYPoolTry {
1980 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1981 if (method == nil)
1982 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
1983 type = CYPoolCString(pool, context, [method _typeString]);
1984 } CYPoolCatch(NULL)
1985 }
1986
1987 void *setup[2];
1988 setup[0] = &self;
1989 setup[1] = &_cmd;
1990
1991 sig::Signature signature;
1992 sig::Parse(pool, &signature, type, &Structor_);
1993
1994 ffi_cif cif;
1995 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1996
1997 if (imp == NULL) {
1998 #ifdef __APPLE__
1999 if (stret(cif.rtype))
2000 imp = class_getMethodImplementation_stret(_class, _cmd);
2001 else
2002 imp = class_getMethodImplementation(_class, _cmd);
2003 #else
2004 objc_super super = {self, _class};
2005 imp = objc_msg_lookup_super(&super, _cmd);
2006 #endif
2007 }
2008
2009 void (*function)() = reinterpret_cast<void (*)()>(imp);
2010 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2011 } CYCatch }
2012
2013 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2014 if (count < 2)
2015 throw CYJSError(context, "too few arguments to objc_msgSend");
2016
2017 CYPool pool;
2018
2019 bool uninitialized;
2020
2021 id self;
2022 SEL _cmd;
2023 Class _class;
2024
2025 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2026 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2027 self = internal->GetValue();
2028 _class = internal->class_;;
2029 uninitialized = false;
2030 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2031 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2032 self = internal->GetValue();
2033 _class = nil;
2034 uninitialized = internal->IsUninitialized();
2035 if (uninitialized)
2036 internal->value_ = nil;
2037 } else {
2038 self = CYCastNSObject(pool, context, arguments[0]);
2039 _class = nil;
2040 uninitialized = false;
2041 }
2042
2043 if (self == nil)
2044 return CYJSNull(context);
2045
2046 _cmd = CYCastSEL(context, arguments[1]);
2047
2048 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2049 } CYCatch }
2050
2051 /* Hook: objc_registerClassPair {{{ */
2052 #if defined(__APPLE__) && defined(__arm__)
2053 // XXX: replace this with associated objects
2054
2055 MSHook(void, CYDealloc, id self, SEL sel) {
2056 CYInternal *internal;
2057 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2058 if (internal != NULL)
2059 delete internal;
2060 _CYDealloc(self, sel);
2061 }
2062
2063 MSHook(void, objc_registerClassPair, Class _class) {
2064 Class super(class_getSuperclass(_class));
2065 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2066 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2067 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2068 }
2069
2070 _objc_registerClassPair(_class);
2071 }
2072
2073 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2074 if (count != 1)
2075 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2076 CYPool pool;
2077 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2078 if (value == NULL || !CYIsClass(value))
2079 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2080 Class _class((Class) value);
2081 $objc_registerClassPair(_class);
2082 return CYJSUndefined(context);
2083 } CYCatch }
2084 #endif
2085 /* }}} */
2086
2087 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2088 JSValueRef setup[count + 2];
2089 setup[0] = _this;
2090 setup[1] = object;
2091 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2092 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2093 }
2094
2095 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2096 CYPool pool;
2097 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2098
2099 // XXX: handle Instance::Uninitialized?
2100 id self(CYCastNSObject(pool, context, _this));
2101
2102 void *setup[2];
2103 setup[0] = &self;
2104 setup[1] = &internal->sel_;
2105
2106 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2107 }
2108
2109 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2110 if (count != 2)
2111 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2112 CYPool pool;
2113 id self(CYCastNSObject(pool, context, arguments[0]));
2114 Class _class(CYCastClass(pool, context, arguments[1]));
2115 return cy::Super::Make(context, self, _class);
2116 } CYCatch }
2117
2118 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2119 if (count != 1)
2120 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2121 CYPool pool;
2122 const char *name(CYPoolCString(pool, context, arguments[0]));
2123 return CYMakeSelector(context, sel_registerName(name));
2124 } CYCatch }
2125
2126 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2127 if (count > 1)
2128 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2129 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2130 return Instance::Make(context, self);
2131 } CYCatch }
2132
2133 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2134 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2135 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2136 }
2137
2138 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2139 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2140 Type_privateData *typical(internal->GetType());
2141
2142 sig::Type *type;
2143 ffi_type *ffi;
2144
2145 if (typical == NULL) {
2146 type = NULL;
2147 ffi = NULL;
2148 } else {
2149 type = typical->type_;
2150 ffi = typical->ffi_;
2151 }
2152
2153 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2154 }
2155
2156 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2157 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2158 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2159 }
2160
2161 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2162 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2163 id self(internal->GetValue());
2164 if (!CYIsClass(self))
2165 return CYJSUndefined(context);
2166 return CYGetClassPrototype(context, self);
2167 } CYCatch }
2168
2169 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2170 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2171 id self(internal->GetValue());
2172 if (!CYIsClass(self))
2173 return CYJSUndefined(context);
2174 return Messages::Make(context, (Class) self);
2175 }
2176
2177 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2178 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2179 return NULL;
2180
2181 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2182 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2183 } CYCatch }
2184
2185 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2186 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2187 return NULL;
2188
2189 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2190
2191 CYPoolTry {
2192 NSString *key;
2193 if (count == 0)
2194 key = nil;
2195 else
2196 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2197 // XXX: check for support of cy$toJSON?
2198 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2199 } CYPoolCatch(NULL)
2200 } CYCatch return /*XXX*/ NULL; }
2201
2202 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2203 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2204 return NULL;
2205
2206 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2207
2208 CYPoolTry {
2209 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2210 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2211 } CYPoolCatch(NULL)
2212 } CYCatch return /*XXX*/ NULL; }
2213
2214 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2215 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2216 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2217 } CYCatch }
2218
2219 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2220 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2221 }
2222
2223 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2224 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2225 const char *name(sel_getName(internal->GetValue()));
2226
2227 CYPoolTry {
2228 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2229 return CYCastJSValue(context, CYJSString(context, string));
2230 } CYPoolCatch(NULL)
2231 } CYCatch return /*XXX*/ NULL; }
2232
2233 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2234 if (count != 1)
2235 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2236
2237 CYPool pool;
2238 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2239 SEL sel(internal->GetValue());
2240
2241 objc_method *method;
2242 if (Class _class = CYCastClass(pool, context, arguments[0]))
2243 method = class_getInstanceMethod(_class, sel);
2244 else
2245 method = NULL;
2246
2247 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2248 return CYCastJSValue(context, CYJSString(type));
2249
2250 return CYJSNull(context);
2251 } CYCatch }
2252
2253 static JSStaticValue Selector_staticValues[2] = {
2254 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2255 {NULL, NULL, NULL, 0}
2256 };
2257
2258 static JSStaticValue Instance_staticValues[5] = {
2259 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2260 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2261 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2262 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2263 {NULL, NULL, NULL, 0}
2264 };
2265
2266 static JSStaticFunction Instance_staticFunctions[5] = {
2267 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2268 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2269 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2270 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2271 {NULL, NULL, 0}
2272 };
2273
2274 static JSStaticFunction Internal_staticFunctions[2] = {
2275 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2276 {NULL, NULL, 0}
2277 };
2278
2279 static JSStaticFunction Selector_staticFunctions[5] = {
2280 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2281 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2282 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2283 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2284 {NULL, NULL, 0}
2285 };
2286
2287 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2288 apr_pool_t *pool(CYGetGlobalPool());
2289
2290 Object_type = new(pool) Type_privateData("@");
2291 Selector_type = new(pool) Type_privateData(":");
2292
2293 #ifdef __APPLE__
2294 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2295 NSCFType_ = objc_getClass("NSCFType");
2296 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2297 NSZombie_ = objc_getClass("_NSZombie_");
2298 #else
2299 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2300 #endif
2301
2302 NSArray_ = objc_getClass("NSArray");
2303 NSDictionary_ = objc_getClass("NSDictionary");
2304 Object_ = objc_getClass("Object");
2305
2306 JSClassDefinition definition;
2307
2308 definition = kJSClassDefinitionEmpty;
2309 definition.className = "Instance";
2310 definition.staticValues = Instance_staticValues;
2311 definition.staticFunctions = Instance_staticFunctions;
2312 definition.hasProperty = &Instance_hasProperty;
2313 definition.getProperty = &Instance_getProperty;
2314 definition.setProperty = &Instance_setProperty;
2315 definition.deleteProperty = &Instance_deleteProperty;
2316 definition.getPropertyNames = &Instance_getPropertyNames;
2317 definition.callAsConstructor = &Instance_callAsConstructor;
2318 definition.hasInstance = &Instance_hasInstance;
2319 definition.finalize = &CYFinalize;
2320 Instance_ = JSClassCreate(&definition);
2321
2322 definition = kJSClassDefinitionEmpty;
2323 definition.className = "Internal";
2324 definition.staticFunctions = Internal_staticFunctions;
2325 definition.hasProperty = &Internal_hasProperty;
2326 definition.getProperty = &Internal_getProperty;
2327 definition.setProperty = &Internal_setProperty;
2328 definition.getPropertyNames = &Internal_getPropertyNames;
2329 definition.finalize = &CYFinalize;
2330 Internal_ = JSClassCreate(&definition);
2331
2332 definition = kJSClassDefinitionEmpty;
2333 definition.className = "Message";
2334 definition.staticFunctions = cy::Functor::StaticFunctions;
2335 definition.callAsFunction = &Message_callAsFunction;
2336 definition.finalize = &CYFinalize;
2337 Message_ = JSClassCreate(&definition);
2338
2339 definition = kJSClassDefinitionEmpty;
2340 definition.className = "Messages";
2341 definition.hasProperty = &Messages_hasProperty;
2342 definition.getProperty = &Messages_getProperty;
2343 definition.setProperty = &Messages_setProperty;
2344 #if 0 && OBJC_API_VERSION < 2
2345 definition.deleteProperty = &Messages_deleteProperty;
2346 #endif
2347 definition.getPropertyNames = &Messages_getPropertyNames;
2348 definition.finalize = &CYFinalize;
2349 Messages_ = JSClassCreate(&definition);
2350
2351 definition = kJSClassDefinitionEmpty;
2352 definition.className = "Selector";
2353 definition.staticValues = Selector_staticValues;
2354 definition.staticFunctions = Selector_staticFunctions;
2355 definition.callAsFunction = &Selector_callAsFunction;
2356 definition.finalize = &CYFinalize;
2357 Selector_ = JSClassCreate(&definition);
2358
2359 definition = kJSClassDefinitionEmpty;
2360 definition.className = "Super";
2361 definition.staticFunctions = Internal_staticFunctions;
2362 definition.finalize = &CYFinalize;
2363 Super_ = JSClassCreate(&definition);
2364
2365 definition = kJSClassDefinitionEmpty;
2366 definition.className = "ObjectiveC::Classes";
2367 definition.getProperty = &ObjectiveC_Classes_getProperty;
2368 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2369 ObjectiveC_Classes_ = JSClassCreate(&definition);
2370
2371 #if OBJC_API_VERSION >= 2
2372 definition = kJSClassDefinitionEmpty;
2373 definition.className = "ObjectiveC::Images";
2374 definition.getProperty = &ObjectiveC_Images_getProperty;
2375 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2376 ObjectiveC_Images_ = JSClassCreate(&definition);
2377
2378 definition = kJSClassDefinitionEmpty;
2379 definition.className = "ObjectiveC::Image::Classes";
2380 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2381 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2382 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2383 #endif
2384
2385 definition = kJSClassDefinitionEmpty;
2386 definition.className = "ObjectiveC::Protocols";
2387 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2388 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2389 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2390
2391 #if defined(__APPLE__) && defined(__arm__)
2392 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2393 #endif
2394
2395 #ifdef __APPLE__
2396 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2397 #endif
2398 } CYPoolCatch() }
2399
2400 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2401 JSObjectRef global(CYGetGlobalObject(context));
2402 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2403 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2404 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2405
2406 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2407 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2408
2409 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2410 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2411
2412 #if OBJC_API_VERSION >= 2
2413 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2414 #endif
2415
2416 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2417 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2418 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2419 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2420
2421 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2422 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2423
2424 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2425 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2426 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2427
2428 #if defined(__APPLE__) && defined(__arm__)
2429 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2430 #endif
2431
2432 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2433
2434 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2435 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2436 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2437 } CYPoolCatch() }
2438
2439 static CYHooks CYObjectiveCHooks = {
2440 &CYObjectiveC_ExecuteStart,
2441 &CYObjectiveC_ExecuteEnd,
2442 &CYObjectiveC_RuntimeProperty,
2443 &CYObjectiveC_CallFunction,
2444 &CYObjectiveC_Initialize,
2445 &CYObjectiveC_SetupContext,
2446 &CYObjectiveC_PoolFFI,
2447 &CYObjectiveC_FromFFI,
2448 };
2449
2450 struct CYObjectiveC {
2451 CYObjectiveC() {
2452 hooks_ = &CYObjectiveCHooks;
2453 }
2454 } CYObjectiveC;