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