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