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