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