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