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