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