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