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