]> git.saurik.com Git - cycript.git/blob - ObjectiveC/Library.mm
Use the base JavaScript CYONifier for CYJSArray.
[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 - (NSString *) cy$toCYON {
1235 CYPool pool;
1236 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context_, object_)];
1237 }
1238
1239 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1240 if ((self = [super init]) != nil) {
1241 object_ = object;
1242 context_ = CYGetJSContext(context);
1243 //XXX:JSGlobalContextRetain(context_);
1244 JSValueProtect(context_, object_);
1245 } return self;
1246 } CYObjectiveCatch }
1247
1248 - (void) dealloc { CYObjectiveTry {
1249 JSValueUnprotect(context_, object_);
1250 //XXX:JSGlobalContextRelease(context_);
1251 [super dealloc];
1252 } CYObjectiveCatch }
1253
1254 - (NSUInteger) count { CYObjectiveTry {
1255 return CYArrayLength(context_, object_);
1256 } CYObjectiveCatch }
1257
1258 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1259 size_t bounds([self count]);
1260 if (index >= bounds)
1261 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1262 JSValueRef exception(NULL);
1263 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1264 CYThrow(context_, exception);
1265 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1266 } CYObjectiveCatch }
1267
1268 - (void) addObject:(id)object { CYObjectiveTry {
1269 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1270 } CYObjectiveCatch }
1271
1272 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1273 size_t bounds([self count] + 1);
1274 if (index >= bounds)
1275 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1276 JSValueRef exception(NULL);
1277 JSValueRef arguments[3];
1278 arguments[0] = CYCastJSValue(context_, index);
1279 arguments[1] = CYCastJSValue(context_, 0);
1280 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1281 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1282 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1283 CYThrow(context_, exception);
1284 } CYObjectiveCatch }
1285
1286 - (void) removeLastObject { CYObjectiveTry {
1287 JSValueRef exception(NULL);
1288 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1289 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1290 CYThrow(context_, exception);
1291 } CYObjectiveCatch }
1292
1293 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1294 size_t bounds([self count]);
1295 if (index >= bounds)
1296 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1297 JSValueRef exception(NULL);
1298 JSValueRef arguments[2];
1299 arguments[0] = CYCastJSValue(context_, index);
1300 arguments[1] = CYCastJSValue(context_, 1);
1301 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1302 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1303 CYThrow(context_, exception);
1304 } CYObjectiveCatch }
1305
1306 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1307 size_t bounds([self count]);
1308 if (index >= bounds)
1309 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1310 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1311 } CYObjectiveCatch }
1312
1313 @end
1314
1315 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1316 struct CYInternal :
1317 CYData
1318 {
1319 JSObjectRef object_;
1320
1321 CYInternal() :
1322 object_(NULL)
1323 {
1324 }
1325
1326 ~CYInternal() {
1327 // XXX: delete object_? ;(
1328 }
1329
1330 static CYInternal *Get(id self) {
1331 CYInternal *internal(NULL);
1332 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1333 // XXX: do something epic? ;P
1334 }
1335
1336 return internal;
1337 }
1338
1339 static CYInternal *Set(id self) {
1340 CYInternal *internal(NULL);
1341 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1342 if (internal == NULL) {
1343 internal = new CYInternal();
1344 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1345 }
1346 } else {
1347 // XXX: do something epic? ;P
1348 }
1349
1350 return internal;
1351 }
1352
1353 bool HasProperty(JSContextRef context, JSStringRef name) {
1354 if (object_ == NULL)
1355 return false;
1356 return JSObjectHasProperty(context, object_, name);
1357 }
1358
1359 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1360 if (object_ == NULL)
1361 return NULL;
1362 return CYGetProperty(context, object_, name);
1363 }
1364
1365 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1366 if (object_ == NULL)
1367 object_ = JSObjectMake(context, NULL, NULL);
1368 CYSetProperty(context, object_, name, value);
1369 }
1370 };
1371
1372 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1373 Selector_privateData *internal(new Selector_privateData(sel));
1374 return JSObjectMake(context, Selector_, internal);
1375 }
1376
1377 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1378 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1379 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1380 return reinterpret_cast<SEL>(internal->value_);
1381 } else
1382 return CYCastPointer<SEL>(context, value);
1383 }
1384
1385 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1386 return (void *) [[NSAutoreleasePool alloc] init];
1387 } CYSadCatch(NULL) }
1388
1389 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1390 return [(NSAutoreleasePool *) handle release];
1391 } CYSadCatch() }
1392
1393 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1394 if (name == "nil")
1395 return Instance::Make(context, nil);
1396 if (Class _class = objc_getClass(name.data))
1397 return CYMakeInstance(context, _class, true);
1398 if (Protocol *protocol = objc_getProtocol(name.data))
1399 return CYMakeInstance(context, protocol, true);
1400 return NULL;
1401 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1402
1403 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1404 ffi_call(cif, function, value, values);
1405 } CYSadCatch() }
1406
1407 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1408 switch (type->primitive) {
1409 // XXX: do something epic about blocks
1410 case sig::block_P:
1411 case sig::object_P:
1412 case sig::typename_P:
1413 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1414 break;
1415
1416 case sig::selector_P:
1417 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1418 break;
1419
1420 default:
1421 return false;
1422 }
1423
1424 return true;
1425 } CYSadCatch(false) }
1426
1427 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1428 switch (type->primitive) {
1429 // XXX: do something epic about blocks
1430 case sig::block_P:
1431 case sig::object_P:
1432 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1433 JSValueRef value(CYCastJSValue(context, object));
1434 if (initialize)
1435 [object release];
1436 return value;
1437 } else goto null;
1438
1439 case sig::typename_P:
1440 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1441
1442 case sig::selector_P:
1443 if (SEL sel = *reinterpret_cast<SEL *>(data))
1444 return CYMakeSelector(context, sel);
1445 else goto null;
1446
1447 null:
1448 return CYJSNull(context);
1449 default:
1450 return NULL;
1451 }
1452 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1453
1454 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1455 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1456 if (!devoid)
1457 return true;
1458 #if OBJC_API_VERSION >= 2
1459 char type[16];
1460 method_getReturnType(method, type, sizeof(type));
1461 #else
1462 const char *type(method_getTypeEncoding(method));
1463 #endif
1464 if (type[0] != 'v')
1465 return true;
1466 }
1467
1468 // XXX: possibly use a more "awesome" check?
1469 return false;
1470 }
1471
1472 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1473 if (method != NULL)
1474 return method_getTypeEncoding(method);
1475
1476 const char *name(sel_getName(sel));
1477 size_t length(strlen(name));
1478
1479 char keyed[length + 2];
1480 keyed[0] = '6';
1481 keyed[length + 1] = '\0';
1482 memcpy(keyed + 1, name, length);
1483
1484 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1485 return entry->value_;
1486
1487 return NULL;
1488 }
1489
1490 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1491 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1492
1493 JSContextRef context(internal->context_);
1494
1495 size_t count(internal->cif_.nargs);
1496 JSValueRef values[count];
1497
1498 for (size_t index(0); index != count; ++index)
1499 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1500
1501 JSObjectRef _this(CYCastJSObject(context, values[0]));
1502
1503 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1504 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1505 }
1506
1507 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1508 Message_privateData *internal(new Message_privateData(sel, type, imp));
1509 return JSObjectMake(context, Message_, internal);
1510 }
1511
1512 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1513 JSObjectRef function(CYCastJSObject(context, value));
1514 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1515 // XXX: see notes in Library.cpp about needing to leak
1516 return reinterpret_cast<IMP>(internal->GetValue());
1517 }
1518
1519 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1520 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1521 Class _class(internal->GetValue());
1522
1523 CYPool pool;
1524 const char *name(CYPoolCString(pool, context, property));
1525
1526 if (SEL sel = sel_getUid(name))
1527 if (class_getInstanceMethod(_class, sel) != NULL)
1528 return true;
1529
1530 return false;
1531 }
1532
1533 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1534 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1535 Class _class(internal->GetValue());
1536
1537 CYPool pool;
1538 const char *name(CYPoolCString(pool, context, property));
1539
1540 if (SEL sel = sel_getUid(name))
1541 if (objc_method *method = class_getInstanceMethod(_class, sel))
1542 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1543
1544 return NULL;
1545 }
1546
1547 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1548 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1549 Class _class(internal->GetValue());
1550
1551 CYPool pool;
1552 const char *name(CYPoolCString(pool, context, property));
1553
1554 SEL sel(sel_registerName(name));
1555
1556 objc_method *method(class_getInstanceMethod(_class, sel));
1557
1558 const char *type;
1559 IMP imp;
1560
1561 if (JSValueIsObjectOfClass(context, value, Message_)) {
1562 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1563 type = sig::Unparse(pool, &message->signature_);
1564 imp = reinterpret_cast<IMP>(message->GetValue());
1565 } else {
1566 type = CYPoolTypeEncoding(pool, context, sel, method);
1567 imp = CYMakeMessage(context, value, type);
1568 }
1569
1570 if (method != NULL)
1571 method_setImplementation(method, imp);
1572 else {
1573 #ifdef GNU_RUNTIME
1574 GSMethodList list(GSAllocMethodList(1));
1575 GSAppendMethodToList(list, sel, type, imp, YES);
1576 GSAddMethodList(_class, list, YES);
1577 GSFlushMethodCacheForClass(_class);
1578 #else
1579 class_addMethod(_class, sel, imp, type);
1580 #endif
1581 }
1582
1583 return true;
1584 }
1585
1586 #if 0 && OBJC_API_VERSION < 2
1587 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1588 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1589 Class _class(internal->GetValue());
1590
1591 CYPool pool;
1592 const char *name(CYPoolCString(pool, context, property));
1593
1594 if (SEL sel = sel_getUid(name))
1595 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1596 objc_method_list list = {NULL, 1, {method}};
1597 class_removeMethods(_class, &list);
1598 return true;
1599 }
1600
1601 return false;
1602 }
1603 #endif
1604
1605 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1606 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1607 Class _class(internal->GetValue());
1608
1609 #if OBJC_API_VERSION >= 2
1610 unsigned int size;
1611 objc_method **data(class_copyMethodList(_class, &size));
1612 for (size_t i(0); i != size; ++i)
1613 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1614 free(data);
1615 #else
1616 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1617 for (int i(0); i != methods->method_count; ++i)
1618 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1619 #endif
1620 }
1621
1622 static bool CYHasImplicitProperties(Class _class) {
1623 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1624 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1625 return true;
1626 return [_class cy$hasImplicitProperties];
1627 }
1628
1629 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1630 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1631 id self(internal->GetValue());
1632
1633 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1634 return true;
1635
1636 CYPool pool;
1637 NSString *name(CYCastNSString(pool, context, property));
1638
1639 if (CYInternal *internal = CYInternal::Get(self))
1640 if (internal->HasProperty(context, property))
1641 return true;
1642
1643 Class _class(object_getClass(self));
1644
1645 CYPoolTry {
1646 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1647 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1648 if ([self cy$hasProperty:name])
1649 return true;
1650 } CYPoolCatch(false)
1651
1652 const char *string(CYPoolCString(pool, context, name));
1653
1654 #ifdef __APPLE__
1655 if (class_getProperty(_class, string) != NULL)
1656 return true;
1657 #endif
1658
1659 if (CYHasImplicitProperties(_class))
1660 if (SEL sel = sel_getUid(string))
1661 if (CYImplements(self, _class, sel, true))
1662 return true;
1663
1664 return false;
1665 }
1666
1667 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1668 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1669 id self(internal->GetValue());
1670
1671 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1672 return Internal::Make(context, self, object);
1673
1674 CYPool pool;
1675 NSString *name(CYCastNSString(pool, context, property));
1676
1677 if (CYInternal *internal = CYInternal::Get(self))
1678 if (JSValueRef value = internal->GetProperty(context, property))
1679 return value;
1680
1681 CYPoolTry {
1682 if (NSObject *data = [self cy$getProperty:name])
1683 return CYCastJSValue(context, data);
1684 } CYPoolCatch(NULL)
1685
1686 const char *string(CYPoolCString(pool, context, name));
1687 Class _class(object_getClass(self));
1688
1689 #ifdef __APPLE__
1690 if (objc_property_t property = class_getProperty(_class, string)) {
1691 PropertyAttributes attributes(property);
1692 SEL sel(sel_registerName(attributes.Getter()));
1693 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1694 }
1695 #endif
1696
1697 if (CYHasImplicitProperties(_class))
1698 if (SEL sel = sel_getUid(string))
1699 if (CYImplements(self, _class, sel, true))
1700 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1701
1702 return NULL;
1703 } CYCatch }
1704
1705 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1706 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1707 id self(internal->GetValue());
1708
1709 CYPool pool;
1710
1711 NSString *name(CYCastNSString(pool, context, property));
1712 NSObject *data(CYCastNSObject(pool, context, value));
1713
1714 CYPoolTry {
1715 if ([self cy$setProperty:name to:data])
1716 return true;
1717 } CYPoolCatch(NULL)
1718
1719 const char *string(CYPoolCString(pool, context, name));
1720 Class _class(object_getClass(self));
1721
1722 #ifdef __APPLE__
1723 if (objc_property_t property = class_getProperty(_class, string)) {
1724 PropertyAttributes attributes(property);
1725 if (const char *setter = attributes.Setter()) {
1726 SEL sel(sel_registerName(setter));
1727 JSValueRef arguments[1] = {value};
1728 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1729 return true;
1730 }
1731 }
1732 #endif
1733
1734 size_t length(strlen(string));
1735
1736 char set[length + 5];
1737
1738 set[0] = 's';
1739 set[1] = 'e';
1740 set[2] = 't';
1741
1742 if (string[0] != '\0') {
1743 set[3] = toupper(string[0]);
1744 memcpy(set + 4, string + 1, length - 1);
1745 }
1746
1747 set[length + 3] = ':';
1748 set[length + 4] = '\0';
1749
1750 if (SEL sel = sel_getUid(set))
1751 if (CYImplements(self, _class, sel, false)) {
1752 JSValueRef arguments[1] = {value};
1753 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1754 }
1755
1756 if (CYInternal *internal = CYInternal::Set(self)) {
1757 internal->SetProperty(context, property, value);
1758 return true;
1759 }
1760
1761 return false;
1762 } CYCatch }
1763
1764 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1765 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1766 id self(internal->GetValue());
1767
1768 CYPoolTry {
1769 NSString *name(CYCastNSString(NULL, context, property));
1770 return [self cy$deleteProperty:name];
1771 } CYPoolCatch(NULL)
1772 } CYCatch return /*XXX*/ NULL; }
1773
1774 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1775 const char *name(sel_getName(method_getName(method)));
1776 if (strchr(name, ':') != NULL)
1777 return;
1778
1779 const char *type(method_getTypeEncoding(method));
1780 if (type == NULL || *type == '\0' || *type == 'v')
1781 return;
1782
1783 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1784 }
1785
1786 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1787 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1788 id self(internal->GetValue());
1789
1790 CYPool pool;
1791 Class _class(object_getClass(self));
1792
1793 #ifdef __APPLE__
1794 {
1795 unsigned int size;
1796 objc_property_t *data(class_copyPropertyList(_class, &size));
1797 for (size_t i(0); i != size; ++i)
1798 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1799 free(data);
1800 }
1801 #endif
1802
1803 if (CYHasImplicitProperties(_class))
1804 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1805 #if OBJC_API_VERSION >= 2
1806 unsigned int size;
1807 objc_method **data(class_copyMethodList(current, &size));
1808 for (size_t i(0); i != size; ++i)
1809 Instance_getPropertyNames_message(names, data[i]);
1810 free(data);
1811 #else
1812 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1813 for (int i(0); i != methods->method_count; ++i)
1814 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1815 #endif
1816 }
1817
1818 CYPoolTry {
1819 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1820 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1821 [self cy$getPropertyNames:names inContext:context];
1822 } CYPoolCatch()
1823 }
1824
1825 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1826 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1827 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1828 return value;
1829 } CYCatch }
1830
1831 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1832 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1833 Class _class(internal->GetValue());
1834 if (!CYIsClass(_class))
1835 return false;
1836
1837 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1838 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1839 // XXX: this isn't always safe
1840 return [linternal->GetValue() isKindOfClass:_class];
1841 }
1842
1843 return false;
1844 } CYCatch }
1845
1846 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1847 if (count == 0)
1848 throw CYJSError(context, "incorrect number of arguments to Instance");
1849 CYPool pool;
1850 id value(CYCastNSObject(pool, context, arguments[0]));
1851 if (value == nil)
1852 value = [NSNull null];
1853 return CYCastJSValue(context, [value cy$box]);
1854 } CYCatch }
1855
1856 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1857 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1858 CYPool pool;
1859
1860 id self(internal->GetValue());
1861 const char *name(CYPoolCString(pool, context, property));
1862
1863 if (object_getInstanceVariable(self, name, NULL) != NULL)
1864 return true;
1865
1866 return false;
1867 }
1868
1869 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1870 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1871 CYPool pool;
1872
1873 id self(internal->GetValue());
1874 const char *name(CYPoolCString(pool, context, property));
1875
1876 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1877 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1878 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1879 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1880 }
1881
1882 return NULL;
1883 } CYCatch }
1884
1885 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1886 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1887 CYPool pool;
1888
1889 id self(internal->GetValue());
1890 const char *name(CYPoolCString(pool, context, property));
1891
1892 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1893 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1894 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1895 return true;
1896 }
1897
1898 return false;
1899 } CYCatch }
1900
1901 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1902 if (Class super = class_getSuperclass(_class))
1903 Internal_getPropertyNames_(super, names);
1904
1905 #if OBJC_API_VERSION >= 2
1906 unsigned int size;
1907 objc_ivar **data(class_copyIvarList(_class, &size));
1908 for (size_t i(0); i != size; ++i)
1909 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1910 free(data);
1911 #else
1912 if (objc_ivar_list *ivars = _class->ivars)
1913 for (int i(0); i != ivars->ivar_count; ++i)
1914 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1915 #endif
1916 }
1917
1918 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1919 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1920 CYPool pool;
1921
1922 id self(internal->GetValue());
1923 Class _class(object_getClass(self));
1924
1925 Internal_getPropertyNames_(_class, names);
1926 }
1927
1928 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1929 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1930 return internal->GetOwner();
1931 }
1932
1933 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1934 CYPool pool;
1935 NSString *name(CYCastNSString(pool, context, property));
1936 if (Class _class = NSClassFromString(name))
1937 return CYMakeInstance(context, _class, true);
1938 return NULL;
1939 } CYCatch }
1940
1941 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1942 #ifdef __APPLE__
1943 size_t size(objc_getClassList(NULL, 0));
1944 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1945
1946 get:
1947 size_t writ(objc_getClassList(data, size));
1948 if (size < writ) {
1949 size = writ;
1950 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1951 data = copy;
1952 goto get;
1953 } else goto done;
1954 }
1955
1956 for (size_t i(0); i != writ; ++i)
1957 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1958
1959 done:
1960 free(data);
1961 #else
1962 void *state(NULL);
1963 while (Class _class = objc_next_class(&state))
1964 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1965 #endif
1966 }
1967
1968 #if OBJC_API_VERSION >= 2
1969 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1970 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1971
1972 CYPool pool;
1973 const char *name(CYPoolCString(pool, context, property));
1974 unsigned int size;
1975 const char **data(objc_copyClassNamesForImage(internal, &size));
1976 JSValueRef value;
1977 for (size_t i(0); i != size; ++i)
1978 if (strcmp(name, data[i]) == 0) {
1979 if (Class _class = objc_getClass(name)) {
1980 value = CYMakeInstance(context, _class, true);
1981 goto free;
1982 } else
1983 break;
1984 }
1985 value = NULL;
1986 free:
1987 free(data);
1988 return value;
1989 } CYCatch }
1990
1991 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1992 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1993 unsigned int size;
1994 const char **data(objc_copyClassNamesForImage(internal, &size));
1995 for (size_t i(0); i != size; ++i)
1996 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1997 free(data);
1998 }
1999
2000 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2001 CYPool pool;
2002 const char *name(CYPoolCString(pool, context, property));
2003 unsigned int size;
2004 const char **data(objc_copyImageNames(&size));
2005 for (size_t i(0); i != size; ++i)
2006 if (strcmp(name, data[i]) == 0) {
2007 name = data[i];
2008 goto free;
2009 }
2010 name = NULL;
2011 free:
2012 free(data);
2013 if (name == NULL)
2014 return NULL;
2015 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2016 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2017 return value;
2018 } CYCatch }
2019
2020 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2021 unsigned int size;
2022 const char **data(objc_copyImageNames(&size));
2023 for (size_t i(0); i != size; ++i)
2024 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2025 free(data);
2026 }
2027 #endif
2028
2029 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2030 CYPool pool;
2031 const char *name(CYPoolCString(pool, context, property));
2032 if (Protocol *protocol = objc_getProtocol(name))
2033 return CYMakeInstance(context, protocol, true);
2034 return NULL;
2035 } CYCatch }
2036
2037 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2038 #if OBJC_API_VERSION >= 2
2039 unsigned int size;
2040 Protocol **data(objc_copyProtocolList(&size));
2041 for (size_t i(0); i != size; ++i)
2042 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2043 free(data);
2044 #else
2045 // XXX: fix this!
2046 #endif
2047 }
2048
2049 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2050 CYPool pool;
2051 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2052 if (name == "nil")
2053 return Instance::Make(context, nil);
2054 return NULL;
2055 } CYCatch }
2056
2057 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2058 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2059 }
2060
2061 #ifdef __APPLE__
2062 static bool stret(ffi_type *ffi_type) {
2063 return ffi_type->type == FFI_TYPE_STRUCT && (
2064 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2065 struct_forward_array[ffi_type->size] != 0
2066 );
2067 }
2068 #endif
2069
2070 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 {
2071 const char *type;
2072
2073 if (_class == NULL)
2074 _class = object_getClass(self);
2075
2076 IMP imp;
2077
2078 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2079 imp = method_getImplementation(method);
2080 type = method_getTypeEncoding(method);
2081 } else {
2082 imp = NULL;
2083
2084 CYPoolTry {
2085 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2086 if (method == nil)
2087 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2088 type = CYPoolCString(pool, context, [method _typeString]);
2089 } CYPoolCatch(NULL)
2090 }
2091
2092 void *setup[2];
2093 setup[0] = &self;
2094 setup[1] = &_cmd;
2095
2096 sig::Signature signature;
2097 sig::Parse(pool, &signature, type, &Structor_);
2098
2099 size_t used(count + 3);
2100 if (used > signature.count) {
2101 sig::Element *elements(new (pool) sig::Element[used]);
2102 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2103
2104 for (size_t index(signature.count); index != used; ++index) {
2105 sig::Element *element(&elements[index]);
2106 element->name = NULL;
2107 element->offset = _not(size_t);
2108
2109 sig::Type *type(new (pool) sig::Type);
2110 memset(type, 0, sizeof(*type));
2111 type->primitive = sig::object_P;
2112 element->type = type;
2113 }
2114
2115 signature.elements = elements;
2116 signature.count = used;
2117 }
2118
2119 ffi_cif cif;
2120 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2121
2122 if (imp == NULL) {
2123 #ifdef __APPLE__
2124 if (stret(cif.rtype))
2125 imp = class_getMethodImplementation_stret(_class, _cmd);
2126 else
2127 imp = class_getMethodImplementation(_class, _cmd);
2128 #else
2129 objc_super super = {self, _class};
2130 imp = objc_msg_lookup_super(&super, _cmd);
2131 #endif
2132 }
2133
2134 void (*function)() = reinterpret_cast<void (*)()>(imp);
2135 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2136 } CYCatch }
2137
2138 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2139 if (count < 2)
2140 throw CYJSError(context, "too few arguments to objc_msgSend");
2141
2142 CYPool pool;
2143
2144 bool uninitialized;
2145
2146 id self;
2147 SEL _cmd;
2148 Class _class;
2149
2150 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2151 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2152 self = internal->GetValue();
2153 _class = internal->class_;;
2154 uninitialized = false;
2155 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2156 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2157 self = internal->GetValue();
2158 _class = nil;
2159 uninitialized = internal->IsUninitialized();
2160 if (uninitialized)
2161 internal->value_ = nil;
2162 } else {
2163 self = CYCastNSObject(pool, context, arguments[0]);
2164 _class = nil;
2165 uninitialized = false;
2166 }
2167
2168 if (self == nil)
2169 return CYJSNull(context);
2170
2171 _cmd = CYCastSEL(context, arguments[1]);
2172
2173 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2174 } CYCatch }
2175
2176 /* Hook: objc_registerClassPair {{{ */
2177 #if defined(__APPLE__) && defined(__arm__) && 0
2178 // XXX: replace this with associated objects
2179
2180 MSHook(void, CYDealloc, id self, SEL sel) {
2181 CYInternal *internal;
2182 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2183 if (internal != NULL)
2184 delete internal;
2185 _CYDealloc(self, sel);
2186 }
2187
2188 MSHook(void, objc_registerClassPair, Class _class) {
2189 Class super(class_getSuperclass(_class));
2190 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2191 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2192 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2193 }
2194
2195 _objc_registerClassPair(_class);
2196 }
2197
2198 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2199 if (count != 1)
2200 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2201 CYPool pool;
2202 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2203 if (value == NULL || !CYIsClass(value))
2204 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2205 Class _class((Class) value);
2206 $objc_registerClassPair(_class);
2207 return CYJSUndefined(context);
2208 } CYCatch }
2209 #endif
2210 /* }}} */
2211
2212 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2213 JSValueRef setup[count + 2];
2214 setup[0] = _this;
2215 setup[1] = object;
2216 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2217 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2218 }
2219
2220 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2221 CYPool pool;
2222 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2223
2224 // XXX: handle Instance::Uninitialized?
2225 id self(CYCastNSObject(pool, context, _this));
2226
2227 void *setup[2];
2228 setup[0] = &self;
2229 setup[1] = &internal->sel_;
2230
2231 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2232 }
2233
2234 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2235 if (count != 2)
2236 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2237 CYPool pool;
2238 id self(CYCastNSObject(pool, context, arguments[0]));
2239 Class _class(CYCastClass(pool, context, arguments[1]));
2240 return cy::Super::Make(context, self, _class);
2241 } CYCatch }
2242
2243 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2244 if (count != 1)
2245 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2246 CYPool pool;
2247 const char *name(CYPoolCString(pool, context, arguments[0]));
2248 return CYMakeSelector(context, sel_registerName(name));
2249 } CYCatch }
2250
2251 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2252 if (count > 1)
2253 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2254 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2255 return CYMakeInstance(context, self, false);
2256 } CYCatch }
2257
2258 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2259 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2260 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2261 }
2262
2263 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2264 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2265 Type_privateData *typical(internal->GetType());
2266
2267 sig::Type *type;
2268 ffi_type *ffi;
2269
2270 if (typical == NULL) {
2271 type = NULL;
2272 ffi = NULL;
2273 } else {
2274 type = typical->type_;
2275 ffi = typical->ffi_;
2276 }
2277
2278 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2279 }
2280
2281 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2282 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2283 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2284 }
2285
2286 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2287 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2288 id self(internal->GetValue());
2289 if (!CYIsClass(self))
2290 return CYJSUndefined(context);
2291 return CYGetClassPrototype(context, self);
2292 } CYCatch }
2293
2294 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2295 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2296 id self(internal->GetValue());
2297 if (!CYIsClass(self))
2298 return CYJSUndefined(context);
2299 return Messages::Make(context, (Class) self);
2300 }
2301
2302 static JSValueRef Instance_callAsFunction_toCYON(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 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2308 } CYCatch }
2309
2310 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2311 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2312 return NULL;
2313
2314 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2315
2316 CYPoolTry {
2317 NSString *key;
2318 if (count == 0)
2319 key = nil;
2320 else
2321 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2322 // XXX: check for support of cy$toJSON?
2323 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2324 } CYPoolCatch(NULL)
2325 } CYCatch return /*XXX*/ NULL; }
2326
2327 static JSValueRef Instance_callAsFunction_valueOf(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 respondsToSelector:@selector(cy$JSValueInContext:)])
2335 return _this;
2336
2337 if (JSValueRef result = [value cy$JSValueInContext:context])
2338 return result;
2339
2340 return _this;
2341 } CYCatch return /*XXX*/ NULL; }
2342
2343 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2344 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2345 return NULL;
2346
2347 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2348 // XXX: but... but... THIS ISN'T A POINTER! :(
2349 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2350 } CYCatch return /*XXX*/ NULL; }
2351
2352 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2353 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2354 return NULL;
2355
2356 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2357 id value(internal->GetValue());
2358
2359 if (value == nil)
2360 return CYCastJSValue(context, "nil");
2361
2362 CYPoolTry {
2363 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2364 return CYCastJSValue(context, CYJSString(context, [value description]));
2365 } CYPoolCatch(NULL)
2366 } CYCatch return /*XXX*/ NULL; }
2367
2368 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2369 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2370 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2371 } CYCatch }
2372
2373 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2374 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2375 }
2376
2377 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2378 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2379 const char *name(sel_getName(internal->GetValue()));
2380
2381 CYPoolTry {
2382 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2383 return CYCastJSValue(context, CYJSString(context, string));
2384 } CYPoolCatch(NULL)
2385 } CYCatch return /*XXX*/ NULL; }
2386
2387 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2388 if (count != 1)
2389 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2390
2391 CYPool pool;
2392 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2393 SEL sel(internal->GetValue());
2394
2395 objc_method *method;
2396 if (Class _class = CYCastClass(pool, context, arguments[0]))
2397 method = class_getInstanceMethod(_class, sel);
2398 else
2399 method = NULL;
2400
2401 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2402 return CYCastJSValue(context, CYJSString(type));
2403
2404 return CYJSNull(context);
2405 } CYCatch }
2406
2407 static JSStaticValue Selector_staticValues[2] = {
2408 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2409 {NULL, NULL, NULL, 0}
2410 };
2411
2412 static JSStaticValue Instance_staticValues[5] = {
2413 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2414 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2415 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2416 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2417 {NULL, NULL, NULL, 0}
2418 };
2419
2420 static JSStaticFunction Instance_staticFunctions[7] = {
2421 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2422 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2423 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2424 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2425 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2426 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2427 {NULL, NULL, 0}
2428 };
2429
2430 static JSStaticFunction Internal_staticFunctions[2] = {
2431 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2432 {NULL, NULL, 0}
2433 };
2434
2435 static JSStaticFunction Selector_staticFunctions[5] = {
2436 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2437 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2438 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2439 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2440 {NULL, NULL, 0}
2441 };
2442
2443 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2444 apr_pool_t *pool(CYGetGlobalPool());
2445
2446 Object_type = new(pool) Type_privateData("@");
2447 Selector_type = new(pool) Type_privateData(":");
2448
2449 #ifdef __APPLE__
2450 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2451 NSCFType_ = objc_getClass("NSCFType");
2452 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2453 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2454 NSZombie_ = objc_getClass("_NSZombie_");
2455 #else
2456 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2457 #endif
2458
2459 NSArray_ = objc_getClass("NSArray");
2460 NSDictionary_ = objc_getClass("NSDictionary");
2461 NSString_ = objc_getClass("NSString");
2462 Object_ = objc_getClass("Object");
2463
2464 JSClassDefinition definition;
2465
2466 definition = kJSClassDefinitionEmpty;
2467 definition.className = "Instance";
2468 definition.staticValues = Instance_staticValues;
2469 definition.staticFunctions = Instance_staticFunctions;
2470 definition.hasProperty = &Instance_hasProperty;
2471 definition.getProperty = &Instance_getProperty;
2472 definition.setProperty = &Instance_setProperty;
2473 definition.deleteProperty = &Instance_deleteProperty;
2474 definition.getPropertyNames = &Instance_getPropertyNames;
2475 definition.callAsConstructor = &Instance_callAsConstructor;
2476 definition.hasInstance = &Instance_hasInstance;
2477 definition.finalize = &CYFinalize;
2478 Instance_ = JSClassCreate(&definition);
2479
2480 definition = kJSClassDefinitionEmpty;
2481 definition.className = "Internal";
2482 definition.staticFunctions = Internal_staticFunctions;
2483 definition.hasProperty = &Internal_hasProperty;
2484 definition.getProperty = &Internal_getProperty;
2485 definition.setProperty = &Internal_setProperty;
2486 definition.getPropertyNames = &Internal_getPropertyNames;
2487 definition.finalize = &CYFinalize;
2488 Internal_ = JSClassCreate(&definition);
2489
2490 definition = kJSClassDefinitionEmpty;
2491 definition.className = "Message";
2492 definition.staticFunctions = cy::Functor::StaticFunctions;
2493 definition.callAsFunction = &Message_callAsFunction;
2494 definition.finalize = &CYFinalize;
2495 Message_ = JSClassCreate(&definition);
2496
2497 definition = kJSClassDefinitionEmpty;
2498 definition.className = "Messages";
2499 definition.hasProperty = &Messages_hasProperty;
2500 definition.getProperty = &Messages_getProperty;
2501 definition.setProperty = &Messages_setProperty;
2502 #if 0 && OBJC_API_VERSION < 2
2503 definition.deleteProperty = &Messages_deleteProperty;
2504 #endif
2505 definition.getPropertyNames = &Messages_getPropertyNames;
2506 definition.finalize = &CYFinalize;
2507 Messages_ = JSClassCreate(&definition);
2508
2509 definition = kJSClassDefinitionEmpty;
2510 definition.className = "Selector";
2511 definition.staticValues = Selector_staticValues;
2512 definition.staticFunctions = Selector_staticFunctions;
2513 definition.callAsFunction = &Selector_callAsFunction;
2514 definition.finalize = &CYFinalize;
2515 Selector_ = JSClassCreate(&definition);
2516
2517 definition = kJSClassDefinitionEmpty;
2518 definition.className = "Super";
2519 definition.staticFunctions = Internal_staticFunctions;
2520 definition.finalize = &CYFinalize;
2521 Super_ = JSClassCreate(&definition);
2522
2523 definition = kJSClassDefinitionEmpty;
2524 definition.className = "ObjectiveC::Classes";
2525 definition.getProperty = &ObjectiveC_Classes_getProperty;
2526 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2527 ObjectiveC_Classes_ = JSClassCreate(&definition);
2528
2529 definition = kJSClassDefinitionEmpty;
2530 definition.className = "ObjectiveC::Constants";
2531 definition.getProperty = &ObjectiveC_Constants_getProperty;
2532 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2533 ObjectiveC_Constants_ = JSClassCreate(&definition);
2534
2535 #if OBJC_API_VERSION >= 2
2536 definition = kJSClassDefinitionEmpty;
2537 definition.className = "ObjectiveC::Images";
2538 definition.getProperty = &ObjectiveC_Images_getProperty;
2539 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2540 ObjectiveC_Images_ = JSClassCreate(&definition);
2541
2542 definition = kJSClassDefinitionEmpty;
2543 definition.className = "ObjectiveC::Image::Classes";
2544 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2545 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2546 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2547 #endif
2548
2549 definition = kJSClassDefinitionEmpty;
2550 definition.className = "ObjectiveC::Protocols";
2551 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2552 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2553 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2554
2555 #if defined(__APPLE__) && defined(__arm__) && 0
2556 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2557 #endif
2558
2559 #ifdef __APPLE__
2560 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2561 #endif
2562 } CYPoolCatch() }
2563
2564 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2565 JSObjectRef global(CYGetGlobalObject(context));
2566 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2567 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2568 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2569 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2570
2571 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2572 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2573
2574 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2575 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2576 CYArrayPush(context, alls, protocols);
2577
2578 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2579 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2580 CYArrayPush(context, alls, classes);
2581
2582 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2583 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2584 CYArrayPush(context, alls, constants);
2585
2586 #if OBJC_API_VERSION >= 2
2587 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2588 #endif
2589
2590 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2591 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2592 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2593 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2594
2595 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2596 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2597
2598 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, Instance_, NULL));
2599 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2600 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2601 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2602 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2603
2604 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, Instance_, NULL));
2605 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2606 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2607 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2608 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2609
2610 JSObjectRef StringInstance(JSObjectMakeConstructor(context, Instance_, NULL));
2611 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2612 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2613 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2614 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2615
2616 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2617 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2618 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2619
2620 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2621 CYSetProperty(context, Instance, CYJSString("box"), box);
2622
2623 #if defined(__APPLE__) && defined(__arm__) && 0
2624 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2625 #endif
2626
2627 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2628
2629 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2630 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2631 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2632 } CYPoolCatch() }
2633
2634 static CYHooks CYObjectiveCHooks = {
2635 &CYObjectiveC_ExecuteStart,
2636 &CYObjectiveC_ExecuteEnd,
2637 &CYObjectiveC_CallFunction,
2638 &CYObjectiveC_Initialize,
2639 &CYObjectiveC_SetupContext,
2640 &CYObjectiveC_PoolFFI,
2641 &CYObjectiveC_FromFFI,
2642 };
2643
2644 struct CYObjectiveC {
2645 CYObjectiveC() {
2646 hooks_ = &CYObjectiveCHooks;
2647 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2648 _assert(hooks_ != NULL);
2649 }
2650 } CYObjectiveC;