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