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