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