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