]> git.saurik.com Git - cycript.git/blob - ObjectiveC/Library.mm
The Axiom of Choice is obviously true.--Jerry Bona
[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 <objc/runtime.h>
36 #endif
37
38 #ifdef __APPLE__
39 #include <malloc/malloc.h>
40 #include <mach/mach.h>
41 #endif
42
43 #include "Error.hpp"
44 #include "JavaScript.hpp"
45 #include "String.hpp"
46 #include "Execute.hpp"
47
48 #include <cmath>
49 #include <map>
50 #include <set>
51
52 #include <dlfcn.h>
53
54 #define CYObjectiveTry_ { \
55 try
56 #define CYObjectiveTry { \
57 JSContextRef context(context_); \
58 try
59 #define CYObjectiveCatch \
60 catch (const CYException &error) { \
61 @throw CYCastNSObject(NULL, context, error.CastJSValue(context)); \
62 } \
63 }
64
65 #define CYPoolTry { \
66 id _saved(nil); \
67 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
68 @try
69 #define CYPoolCatch(value) \
70 @catch (NSException *error) { \
71 _saved = [error retain]; \
72 throw CYJSError(context, CYCastJSValue(context, error)); \
73 return value; \
74 } @finally { \
75 [_pool release]; \
76 if (_saved != nil) \
77 [_saved autorelease]; \
78 } \
79 }
80
81 #define CYSadTry { \
82 @try
83 #define CYSadCatch(value) \
84 @catch (NSException *error ) { \
85 throw CYJSError(context, CYCastJSValue(context, error)); \
86 } return value; \
87 }
88
89 #ifndef __APPLE__
90 #define class_getSuperclass GSObjCSuper
91 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
92 #define class_getName GSNameFromClass
93
94 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
95
96 #define ivar_getName(ivar) ((ivar)->ivar_name)
97 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
98 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
99
100 #define method_getName(method) ((method)->method_name)
101 #define method_getImplementation(method) ((method)->method_imp)
102 #define method_getTypeEncoding(method) ((method)->method_types)
103 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
104
105 #undef objc_getClass
106 #define objc_getClass GSClassFromName
107
108 #define objc_getProtocol GSProtocolFromName
109
110 #define object_getClass GSObjCClass
111
112 #define object_getInstanceVariable(object, name, value) ({ \
113 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
114 _assert(value != NULL); \
115 if (ivar != NULL) \
116 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
117 ivar; \
118 })
119
120 #define object_setIvar(object, ivar, value) ({ \
121 void *data = (value); \
122 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
123 })
124
125 #define protocol_getName(protocol) [(protocol) name]
126 #endif
127
128 static void (*$objc_setAssociatedObject)(id object, void *key, id value, objc_AssociationPolicy policy);
129 static id (*$objc_getAssociatedObject)(id object, void *key);
130 static void (*$objc_removeAssociatedObjects)(id object);
131
132 struct BlockLiteral {
133 Class isa;
134 int flags;
135 int reserved;
136 void (*invoke)(void *, ...);
137 void *descriptor;
138 };
139
140 struct BlockDescriptor1 {
141 unsigned long int reserved;
142 unsigned long int size;
143 };
144
145 struct BlockDescriptor2 {
146 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
147 void (*dispose_helper)(BlockLiteral *src);
148 };
149
150 struct BlockDescriptor3 {
151 const char *signature;
152 const char *layout;
153 };
154
155 enum {
156 BLOCK_DEALLOCATING = 0x0001,
157 BLOCK_REFCOUNT_MASK = 0xfffe,
158 BLOCK_NEEDS_FREE = 1 << 24,
159 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
160 BLOCK_HAS_CTOR = 1 << 26,
161 BLOCK_IS_GC = 1 << 27,
162 BLOCK_IS_GLOBAL = 1 << 28,
163 BLOCK_HAS_STRET = 1 << 29,
164 BLOCK_HAS_SIGNATURE = 1 << 30,
165 };
166
167 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
168
169 /* Objective-C Pool Release {{{ */
170 void CYPoolRelease_(void *data) {
171 id object(reinterpret_cast<id>(data));
172 [object release];
173 }
174
175 id CYPoolRelease_(CYPool *pool, id object) {
176 if (object == nil)
177 return nil;
178 else if (pool == NULL)
179 return [object autorelease];
180 else {
181 pool->atexit(CYPoolRelease_);
182 return object;
183 }
184 }
185
186 template <typename Type_>
187 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
188 return (Type_) CYPoolRelease_(pool, (id) object);
189 }
190 /* }}} */
191 /* Objective-C Strings {{{ */
192 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
193 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
194 char *string(new(pool) char[size]);
195 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
196 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
197 return string;
198 }
199
200 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
201 #ifdef __APPLE__
202 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
203 #else
204 CYPool pool;
205 return CYCopyJSString(CYPoolCString(pool, context, value));
206 #endif
207 }
208
209 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
210 if (value == nil)
211 return NULL;
212 // XXX: this definition scares me; is anyone using this?!
213 NSString *string([value description]);
214 return CYCopyJSString(context, string);
215 }
216
217 NSString *CYCopyNSString(const CYUTF8String &value) {
218 #ifdef __APPLE__
219 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
220 #else
221 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
222 #endif
223 }
224
225 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
226 #ifdef __APPLE__
227 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
228 #else
229 CYPool pool;
230 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
231 #endif
232 }
233
234 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
235 return CYCopyNSString(context, CYJSString(context, value));
236 }
237
238 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
239 return CYPoolRelease(pool, CYCopyNSString(value));
240 }
241
242 NSString *CYCastNSString(CYPool *pool, SEL sel) {
243 const char *name(sel_getName(sel));
244 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
245 }
246
247 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
248 return CYPoolRelease(pool, CYCopyNSString(context, value));
249 }
250
251 CYUTF8String CYCastUTF8String(NSString *value) {
252 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
253 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
254 }
255 /* }}} */
256
257 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
258
259 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
260 if (exception == NULL)
261 throw error;
262 *exception = CYCastJSValue(context, error);
263 }
264
265 size_t CYGetIndex(NSString *value) {
266 return CYGetIndex(CYCastUTF8String(value));
267 }
268
269 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
270 return CYGetOffset(CYPoolCString(pool, context, value), index);
271 }
272
273 static JSClassRef Instance_;
274
275 static JSClassRef ArrayInstance_;
276 static JSClassRef FunctionInstance_;
277 static JSClassRef ObjectInstance_;
278 static JSClassRef StringInstance_;
279
280 static JSClassRef Class_;
281 static JSClassRef Internal_;
282 static JSClassRef Message_;
283 static JSClassRef Messages_;
284 static JSClassRef Selector_;
285 static JSClassRef Super_;
286
287 static JSClassRef ObjectiveC_Classes_;
288 static JSClassRef ObjectiveC_Constants_;
289 static JSClassRef ObjectiveC_Protocols_;
290
291 #ifdef __APPLE__
292 static JSClassRef ObjectiveC_Image_Classes_;
293 static JSClassRef ObjectiveC_Images_;
294 #endif
295
296 #ifdef __APPLE__
297 static Class NSCFBoolean_;
298 static Class NSCFType_;
299 static Class NSGenericDeallocHandler_;
300 static Class NSZombie_;
301
302 static std::set<Class> banned_;
303 #else
304 static Class NSBoolNumber_;
305 #endif
306
307 static Class NSArray_;
308 static Class NSBlock_;
309 static Class NSDictionary_;
310 static Class NSString_;
311 static Class Object_;
312
313 static Type_privateData *Object_type;
314 static Type_privateData *Selector_type;
315
316 Type_privateData *Instance::GetType() const {
317 return Object_type;
318 }
319
320 Type_privateData *Selector_privateData::GetType() const {
321 return Selector_type;
322 }
323
324 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
325
326 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
327 if (self == nil)
328 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
329 else if (meta && !class_isMetaClass(self))
330 return CYGetCachedObject(context, CYJSString("Class_prototype"));
331
332 JSObjectRef global(CYGetGlobalObject(context));
333 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
334
335 char label[32];
336 sprintf(label, "i%p", self);
337 CYJSString name(label);
338
339 JSValueRef value(CYGetProperty(context, cy, name));
340 if (!JSValueIsUndefined(context, value))
341 return value;
342
343 JSClassRef _class(NULL);
344 JSValueRef prototype;
345
346 if (self == NSArray_)
347 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
348 else if (self == NSBlock_)
349 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
350 else if (self == NSDictionary_)
351 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
352 else if (self == NSString_)
353 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
354 else
355 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
356
357 JSObjectRef object(JSObjectMake(context, _class, NULL));
358 JSObjectSetPrototype(context, object, prototype);
359 CYSetProperty(context, cy, name, object);
360
361 return object;
362 }
363
364 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
365 return CYGetClassPrototype(context, self, class_isMetaClass(self));
366 }
367
368 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
369 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
370 if (Class super = class_getSuperclass(_class))
371 JSObjectSetPrototype(context, value, Messages::Make(context, super));
372 return value;
373 }
374
375 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
376 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
377 }
378
379 namespace cy {
380 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
381 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
382 return value;
383 } }
384
385 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
386 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
387 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
388 return value;
389 }
390
391 Instance::~Instance() {
392 if ((flags_ & Transient) == 0)
393 // XXX: does this handle background threads correctly?
394 // XXX: this simply does not work on the console because I'm stupid
395 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
396 }
397
398 struct Message_privateData :
399 cy::Functor
400 {
401 SEL sel_;
402
403 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
404 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
405 sel_(sel)
406 {
407 }
408 };
409
410 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
411 Instance::Flags flags;
412
413 if (transient)
414 flags = Instance::Transient;
415 else {
416 flags = Instance::None;
417 object = [object retain];
418 }
419
420 return Instance::Make(context, object, flags);
421 }
422
423 @interface NSMethodSignature (Cycript)
424 - (NSString *) _typeString;
425 @end
426
427 @interface NSObject (Cycript)
428
429 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
430 - (JSType) cy$JSType;
431
432 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
433 - (NSString *) cy$toCYON:(bool)objective;
434
435 - (bool) cy$hasProperty:(NSString *)name;
436 - (NSObject *) cy$getProperty:(NSString *)name;
437 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
438 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
439 - (bool) cy$deleteProperty:(NSString *)name;
440 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
441
442 + (bool) cy$hasImplicitProperties;
443
444 @end
445
446 @protocol Cycript
447 - (id) cy$box;
448 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
449 @end
450
451 NSString *CYCastNSCYON(id value, bool objective) {
452 NSString *string;
453
454 if (value == nil)
455 string = @"nil";
456 else {
457 Class _class(object_getClass(value));
458 SEL sel(@selector(cy$toCYON:));
459
460 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
461 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
462 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
463 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
464 string = [value cy$toCYON:objective];
465 else goto fail;
466 } else fail: {
467 if (false);
468 #ifdef __APPLE__
469 else if (value == NSZombie_)
470 string = @"_NSZombie_";
471 else if (_class == NSZombie_)
472 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
473 // XXX: frowny /in/ the pants
474 else if (banned_.find(value) != banned_.end())
475 string = nil;
476 #endif
477 else
478 string = [NSString stringWithFormat:@"%@", value];
479 }
480
481 // XXX: frowny pants
482 if (string == nil)
483 string = @"undefined";
484 }
485
486 return string;
487 }
488
489 #ifdef __APPLE__
490 struct PropertyAttributes {
491 CYPool pool_;
492
493 const char *name;
494
495 const char *variable;
496
497 const char *getter_;
498 const char *setter_;
499
500 bool readonly;
501 bool copy;
502 bool retain;
503 bool nonatomic;
504 bool dynamic;
505 bool weak;
506 bool garbage;
507
508 PropertyAttributes(objc_property_t property) :
509 variable(NULL),
510 getter_(NULL),
511 setter_(NULL),
512 readonly(false),
513 copy(false),
514 retain(false),
515 nonatomic(false),
516 dynamic(false),
517 weak(false),
518 garbage(false)
519 {
520 name = property_getName(property);
521 const char *attributes(property_getAttributes(property));
522
523 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
524 if ((next = strchr(token, ',')) != NULL)
525 *next++ = '\0';
526 switch (*token) {
527 case 'R': readonly = true; break;
528 case 'C': copy = true; break;
529 case '&': retain = true; break;
530 case 'N': nonatomic = true; break;
531 case 'G': getter_ = token + 1; break;
532 case 'S': setter_ = token + 1; break;
533 case 'V': variable = token + 1; break;
534 }
535 }
536
537 /*if (variable == NULL) {
538 variable = property_getName(property);
539 size_t size(strlen(variable));
540 char *name(new(pool_) char[size + 2]);
541 name[0] = '_';
542 memcpy(name + 1, variable, size);
543 name[size + 1] = '\0';
544 variable = name;
545 }*/
546 }
547
548 const char *Getter() {
549 if (getter_ == NULL)
550 getter_ = pool_.strdup(name);
551 return getter_;
552 }
553
554 const char *Setter() {
555 if (setter_ == NULL && !readonly) {
556 size_t length(strlen(name));
557
558 char *temp(new(pool_) char[length + 5]);
559 temp[0] = 's';
560 temp[1] = 'e';
561 temp[2] = 't';
562
563 if (length != 0) {
564 temp[3] = toupper(name[0]);
565 memcpy(temp + 4, name + 1, length - 1);
566 }
567
568 temp[length + 3] = ':';
569 temp[length + 4] = '\0';
570 setter_ = temp;
571 }
572
573 return setter_;
574 }
575
576 };
577 #endif
578
579 @interface CYWebUndefined : NSObject {
580 }
581
582 + (CYWebUndefined *) undefined;
583
584 @end
585
586 @implementation CYWebUndefined
587
588 + (CYWebUndefined *) undefined {
589 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
590 return instance_;
591 }
592
593 @end
594
595 #define WebUndefined CYWebUndefined
596
597 /* Bridge: CYJSObject {{{ */
598 @interface CYJSObject : NSMutableDictionary {
599 JSObjectRef object_;
600 JSGlobalContextRef context_;
601 }
602
603 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
604
605 - (NSUInteger) count;
606 - (id) objectForKey:(id)key;
607 - (NSEnumerator *) keyEnumerator;
608 - (void) setObject:(id)object forKey:(id)key;
609 - (void) removeObjectForKey:(id)key;
610
611 @end
612 /* }}} */
613 /* Bridge: CYJSArray {{{ */
614 @interface CYJSArray : NSMutableArray {
615 JSObjectRef object_;
616 JSGlobalContextRef context_;
617 }
618
619 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
620
621 - (NSUInteger) count;
622 - (id) objectAtIndex:(NSUInteger)index;
623
624 - (void) addObject:(id)anObject;
625 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
626 - (void) removeLastObject;
627 - (void) removeObjectAtIndex:(NSUInteger)index;
628 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
629
630 @end
631 /* }}} */
632
633 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
634 return JSValueIsObjectOfClass(context, value, Instance_);
635 }
636
637 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
638 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
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_ {
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_ {
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_ {
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_ {
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_ {
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_ {
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_ {
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_ {
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 const char *cyon(CYPoolCCYON(pool, context, object_));
1226 if (cyon == NULL)
1227 return [super cy$toCYON:objective];
1228 else
1229 return [NSString stringWithUTF8String:cyon];
1230 } CYObjectiveCatch }
1231
1232 - (NSUInteger) count { CYObjectiveTry {
1233 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1234 size_t size(JSPropertyNameArrayGetCount(names));
1235 JSPropertyNameArrayRelease(names);
1236 return size;
1237 } CYObjectiveCatch }
1238
1239 - (id) objectForKey:(id)key { CYObjectiveTry {
1240 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1241 if (JSValueIsUndefined(context, value))
1242 return nil;
1243 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1244 } CYObjectiveCatch }
1245
1246 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1247 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1248 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1249 JSPropertyNameArrayRelease(names);
1250 return enumerator;
1251 } CYObjectiveCatch }
1252
1253 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1254 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1255 } CYObjectiveCatch }
1256
1257 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1258 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1259 } CYObjectiveCatch }
1260
1261 @end
1262
1263 @implementation CYJSArray
1264
1265 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1266 CYPool pool;
1267 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_)];
1268 } CYObjectiveCatch }
1269
1270 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1271 if ((self = [super init]) != nil) {
1272 object_ = object;
1273 context_ = CYGetJSContext(context);
1274 JSGlobalContextRetain(context_);
1275 JSValueProtect(context_, object_);
1276 } return self;
1277 } CYObjectiveCatch }
1278
1279 - (void) dealloc { CYObjectiveTry {
1280 JSValueUnprotect(context_, object_);
1281 JSGlobalContextRelease(context_);
1282 [super dealloc];
1283 } CYObjectiveCatch }
1284
1285 - (NSUInteger) count { CYObjectiveTry {
1286 return CYArrayLength(context, object_);
1287 } CYObjectiveCatch }
1288
1289 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1290 size_t bounds([self count]);
1291 if (index >= bounds)
1292 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1293 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1294 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1295 } CYObjectiveCatch }
1296
1297 - (void) addObject:(id)object { CYObjectiveTry {
1298 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1299 } CYObjectiveCatch }
1300
1301 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1302 size_t bounds([self count] + 1);
1303 if (index >= bounds)
1304 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1305 JSValueRef arguments[3];
1306 arguments[0] = CYCastJSValue(context, index);
1307 arguments[1] = CYCastJSValue(context, 0);
1308 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1309 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1310 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1311 } CYObjectiveCatch }
1312
1313 - (void) removeLastObject { CYObjectiveTry {
1314 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1315 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1316 } CYObjectiveCatch }
1317
1318 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1319 size_t bounds([self count]);
1320 if (index >= bounds)
1321 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1322 JSValueRef arguments[2];
1323 arguments[0] = CYCastJSValue(context, index);
1324 arguments[1] = CYCastJSValue(context, 1);
1325 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1326 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1327 } CYObjectiveCatch }
1328
1329 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1330 size_t bounds([self count]);
1331 if (index >= bounds)
1332 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1333 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1334 } CYObjectiveCatch }
1335
1336 @end
1337
1338 // XXX: inherit from or replace with CYJSObject
1339 @interface CYInternal : NSObject {
1340 JSGlobalContextRef context_;
1341 JSObjectRef object_;
1342 }
1343
1344 @end
1345
1346 @implementation CYInternal
1347
1348 - (void) dealloc { CYObjectiveTry {
1349 JSValueUnprotect(context_, object_);
1350 JSGlobalContextRelease(context_);
1351 [super dealloc];
1352 } CYObjectiveCatch }
1353
1354 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1355 if ((self = [super init]) != nil) {
1356 context_ = CYGetJSContext(context);
1357 JSGlobalContextRetain(context_);
1358 } return self;
1359 } CYObjectiveCatch }
1360
1361 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1362 if (object_ == NULL)
1363 return false;
1364
1365 return JSObjectHasProperty(context, object_, name);
1366 }
1367
1368 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1369 if (object_ == NULL)
1370 return NULL;
1371
1372 return CYGetProperty(context, object_, name);
1373 }
1374
1375 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1376 @synchronized (self) {
1377 if (object_ == NULL) {
1378 object_ = JSObjectMake(context, NULL, NULL);
1379 JSValueProtect(context, object_);
1380 }
1381 }
1382
1383 CYSetProperty(context, object_, name, value);
1384 }
1385
1386 + (CYInternal *) get:(id)object {
1387 if ($objc_getAssociatedObject == NULL)
1388 return nil;
1389
1390 @synchronized (object) {
1391 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1392 return internal;
1393 }
1394
1395 return nil;
1396 }
1397
1398 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
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 if ($objc_setAssociatedObject == NULL)
1407 return nil;
1408
1409 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1410 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1411 return internal;
1412 }
1413
1414 return nil;
1415 }
1416
1417 @end
1418
1419 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1420 Selector_privateData *internal(new Selector_privateData(sel));
1421 return JSObjectMake(context, Selector_, internal);
1422 }
1423
1424 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1425 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1426 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1427 return reinterpret_cast<SEL>(internal->value_);
1428 } else
1429 return CYCastPointer<SEL>(context, value);
1430 }
1431
1432 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1433 return (void *) [[NSAutoreleasePool alloc] init];
1434 } CYSadCatch(NULL) }
1435
1436 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1437 return [(NSAutoreleasePool *) handle release];
1438 } CYSadCatch() }
1439
1440 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1441 if (name == "nil")
1442 return Instance::Make(context, nil);
1443 if (Class _class = objc_getClass(name.data))
1444 return CYMakeInstance(context, _class, true);
1445 if (Protocol *protocol = objc_getProtocol(name.data))
1446 return CYMakeInstance(context, protocol, true);
1447 return NULL;
1448 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1449
1450 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1451 ffi_call(cif, function, value, values);
1452 } CYSadCatch() }
1453
1454 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1455 switch (type->primitive) {
1456 // XXX: do something epic about blocks
1457 case sig::block_P:
1458 case sig::object_P:
1459 case sig::typename_P:
1460 // XXX: this works for return values, but not for properties and fields
1461 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1462 break;
1463
1464 case sig::selector_P:
1465 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1466 break;
1467
1468 default:
1469 return false;
1470 }
1471
1472 return true;
1473 } CYSadCatch(false) }
1474
1475 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1476 switch (type->primitive) {
1477 // XXX: do something epic about blocks
1478 case sig::block_P:
1479 case sig::object_P:
1480 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1481 JSValueRef value(CYCastJSValue(context, object));
1482 if (initialize)
1483 [object release];
1484 return value;
1485 } else goto null;
1486
1487 case sig::typename_P:
1488 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1489
1490 case sig::selector_P:
1491 if (SEL sel = *reinterpret_cast<SEL *>(data))
1492 return CYMakeSelector(context, sel);
1493 else goto null;
1494
1495 null:
1496 return CYJSNull(context);
1497 default:
1498 return NULL;
1499 }
1500 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1501
1502 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1503 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1504 if (!devoid)
1505 return true;
1506 #if OBJC_API_VERSION >= 2
1507 char type[16];
1508 method_getReturnType(method, type, sizeof(type));
1509 #else
1510 const char *type(method_getTypeEncoding(method));
1511 #endif
1512 if (type[0] != 'v')
1513 return true;
1514 }
1515
1516 // XXX: possibly use a more "awesome" check?
1517 return false;
1518 }
1519
1520 static const char *CYPoolTypeEncoding(CYPool &pool, JSContextRef context, SEL sel, objc_method *method) {
1521 if (method != NULL)
1522 return method_getTypeEncoding(method);
1523
1524 const char *name(sel_getName(sel));
1525 size_t length(strlen(name));
1526
1527 char keyed[length + 2];
1528 keyed[0] = '6';
1529 keyed[length + 1] = '\0';
1530 memcpy(keyed + 1, name, length);
1531
1532 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1533 return entry->value_;
1534
1535 return NULL;
1536 }
1537
1538 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1539 JSObjectRef _this(CYCastJSObject(context, values[0]));
1540 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1541 }
1542
1543 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1544 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1545 }
1546
1547 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1548 Message_privateData *internal(new Message_privateData(sel, type, imp));
1549 return JSObjectMake(context, Message_, internal);
1550 }
1551
1552 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1553 JSObjectRef function(CYCastJSObject(context, value));
1554 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1555 // XXX: see notes in Library.cpp about needing to leak
1556 return reinterpret_cast<IMP>(internal->GetValue());
1557 }
1558
1559 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1560 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1561 Class _class(internal->GetValue());
1562
1563 CYPool pool;
1564 const char *name(CYPoolCString(pool, context, property));
1565
1566 if (SEL sel = sel_getUid(name))
1567 if (class_getInstanceMethod(_class, sel) != NULL)
1568 return true;
1569
1570 return false;
1571 }
1572
1573 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1574 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1575 Class _class(internal->GetValue());
1576
1577 CYPool pool;
1578 const char *name(CYPoolCString(pool, context, property));
1579
1580 if (SEL sel = sel_getUid(name))
1581 if (objc_method *method = class_getInstanceMethod(_class, sel))
1582 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1583
1584 return NULL;
1585 } CYCatch(NULL) }
1586
1587 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1588 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1589 Class _class(internal->GetValue());
1590
1591 CYPool pool;
1592 const char *name(CYPoolCString(pool, context, property));
1593
1594 SEL sel(sel_registerName(name));
1595
1596 objc_method *method(class_getInstanceMethod(_class, sel));
1597
1598 const char *type;
1599 IMP imp;
1600
1601 if (JSValueIsObjectOfClass(context, value, Message_)) {
1602 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1603 type = sig::Unparse(pool, &message->signature_);
1604 imp = reinterpret_cast<IMP>(message->GetValue());
1605 } else {
1606 type = CYPoolTypeEncoding(pool, context, sel, method);
1607 imp = CYMakeMessage(context, value, type);
1608 }
1609
1610 if (method != NULL)
1611 method_setImplementation(method, imp);
1612 else {
1613 #ifdef GNU_RUNTIME
1614 GSMethodList list(GSAllocMethodList(1));
1615 GSAppendMethodToList(list, sel, type, imp, YES);
1616 GSAddMethodList(_class, list, YES);
1617 GSFlushMethodCacheForClass(_class);
1618 #else
1619 class_addMethod(_class, sel, imp, type);
1620 #endif
1621 }
1622
1623 return true;
1624 } CYCatch(false) }
1625
1626 #if 0 && OBJC_API_VERSION < 2
1627 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1628 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1629 Class _class(internal->GetValue());
1630
1631 CYPool pool;
1632 const char *name(CYPoolCString(pool, context, property));
1633
1634 if (SEL sel = sel_getUid(name))
1635 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1636 objc_method_list list = {NULL, 1, {method}};
1637 class_removeMethods(_class, &list);
1638 return true;
1639 }
1640
1641 return false;
1642 } CYCatch(false) }
1643 #endif
1644
1645 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1646 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1647 Class _class(internal->GetValue());
1648
1649 #if OBJC_API_VERSION >= 2
1650 unsigned int size;
1651 objc_method **data(class_copyMethodList(_class, &size));
1652 for (size_t i(0); i != size; ++i)
1653 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1654 free(data);
1655 #else
1656 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1657 for (int i(0); i != methods->method_count; ++i)
1658 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1659 #endif
1660 }
1661
1662 static bool CYHasImplicitProperties(Class _class) {
1663 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1664 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1665 return true;
1666 return [_class cy$hasImplicitProperties];
1667 }
1668
1669 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1670 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1671 id self(internal->GetValue());
1672
1673 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1674 return true;
1675
1676 CYPool pool;
1677 NSString *name(CYCastNSString(&pool, context, property));
1678
1679 if (CYInternal *internal = [CYInternal get:self])
1680 if ([internal hasProperty:property inContext:context])
1681 return true;
1682
1683 Class _class(object_getClass(self));
1684
1685 CYPoolTry {
1686 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1687 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1688 if ([self cy$hasProperty:name])
1689 return true;
1690 } CYPoolCatch(false)
1691
1692 const char *string(CYPoolCString(pool, context, name));
1693
1694 #ifdef __APPLE__
1695 if (class_getProperty(_class, string) != NULL)
1696 return true;
1697 #endif
1698
1699 if (CYHasImplicitProperties(_class))
1700 if (SEL sel = sel_getUid(string))
1701 if (CYImplements(self, _class, sel, true))
1702 return true;
1703
1704 return false;
1705 }
1706
1707 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1708 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1709 id self(internal->GetValue());
1710
1711 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1712 return Internal::Make(context, self, object);
1713
1714 CYPool pool;
1715 NSString *name(CYCastNSString(&pool, context, property));
1716
1717 if (CYInternal *internal = [CYInternal get:self])
1718 if (JSValueRef value = [internal getProperty:property inContext:context])
1719 return value;
1720
1721 CYPoolTry {
1722 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1723 return value;
1724 } CYPoolCatch(NULL)
1725
1726 const char *string(CYPoolCString(pool, context, name));
1727 Class _class(object_getClass(self));
1728
1729 #ifdef __APPLE__
1730 if (objc_property_t property = class_getProperty(_class, string)) {
1731 PropertyAttributes attributes(property);
1732 SEL sel(sel_registerName(attributes.Getter()));
1733 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1734 }
1735 #endif
1736
1737 if (CYHasImplicitProperties(_class))
1738 if (SEL sel = sel_getUid(string))
1739 if (CYImplements(self, _class, sel, true))
1740 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1741
1742 return NULL;
1743 } CYCatch(NULL) }
1744
1745 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1746 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1747 id self(internal->GetValue());
1748
1749 CYPool pool;
1750
1751 NSString *name(CYCastNSString(&pool, context, property));
1752 NSObject *data(CYCastNSObject(&pool, context, value));
1753
1754 CYPoolTry {
1755 if ([self cy$setProperty:name to:data])
1756 return true;
1757 } CYPoolCatch(false)
1758
1759 const char *string(CYPoolCString(pool, context, name));
1760 Class _class(object_getClass(self));
1761
1762 #ifdef __APPLE__
1763 if (objc_property_t property = class_getProperty(_class, string)) {
1764 PropertyAttributes attributes(property);
1765 if (const char *setter = attributes.Setter()) {
1766 SEL sel(sel_registerName(setter));
1767 JSValueRef arguments[1] = {value};
1768 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1769 return true;
1770 }
1771 }
1772 #endif
1773
1774 size_t length(strlen(string));
1775
1776 char set[length + 5];
1777
1778 set[0] = 's';
1779 set[1] = 'e';
1780 set[2] = 't';
1781
1782 if (string[0] != '\0') {
1783 set[3] = toupper(string[0]);
1784 memcpy(set + 4, string + 1, length - 1);
1785 }
1786
1787 set[length + 3] = ':';
1788 set[length + 4] = '\0';
1789
1790 if (SEL sel = sel_getUid(set))
1791 if (CYImplements(self, _class, sel)) {
1792 JSValueRef arguments[1] = {value};
1793 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1794 return true;
1795 }
1796
1797 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1798 [internal setProperty:property toValue:value inContext:context];
1799 return true;
1800 }
1801
1802 return false;
1803 } CYCatch(false) }
1804
1805 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1806 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1807 id self(internal->GetValue());
1808
1809 CYPoolTry {
1810 NSString *name(CYCastNSString(NULL, context, property));
1811 return [self cy$deleteProperty:name];
1812 } CYPoolCatch(false)
1813 } CYCatch(false) return /*XXX*/ false; }
1814
1815 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1816 const char *name(sel_getName(method_getName(method)));
1817 if (strchr(name, ':') != NULL)
1818 return;
1819
1820 const char *type(method_getTypeEncoding(method));
1821 if (type == NULL || *type == '\0' || *type == 'v')
1822 return;
1823
1824 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1825 }
1826
1827 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1828 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1829 id self(internal->GetValue());
1830
1831 CYPool pool;
1832 Class _class(object_getClass(self));
1833
1834 #ifdef __APPLE__
1835 {
1836 unsigned int size;
1837 objc_property_t *data(class_copyPropertyList(_class, &size));
1838 for (size_t i(0); i != size; ++i)
1839 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1840 free(data);
1841 }
1842 #endif
1843
1844 if (CYHasImplicitProperties(_class))
1845 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1846 #if OBJC_API_VERSION >= 2
1847 unsigned int size;
1848 objc_method **data(class_copyMethodList(current, &size));
1849 for (size_t i(0); i != size; ++i)
1850 Instance_getPropertyNames_message(names, data[i]);
1851 free(data);
1852 #else
1853 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1854 for (int i(0); i != methods->method_count; ++i)
1855 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1856 #endif
1857 }
1858
1859 CYPoolTry {
1860 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1861 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1862 [self cy$getPropertyNames:names inContext:context];
1863 } CYPoolCatch()
1864 }
1865
1866 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1867 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1868 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1869 return value;
1870 } CYCatch(NULL) }
1871
1872 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1873 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1874 id self(internal->GetValue());
1875
1876 if (![self isKindOfClass:NSBlock_])
1877 CYThrow("non-NSBlock object is not a function");
1878 // XXX: replace above logic with the following assertion
1879 //_assert([self isKindOfClass:NSBlock_]);
1880 // to do this, make it so FunctionInstance_ is the class of blocks
1881 // to do /that/, generalize the various "is exactly Instance_" checks
1882 // then, move Instance_callAsFunction to only be on FunctionInstance
1883
1884 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1885
1886 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1887 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1888 descriptor += sizeof(BlockDescriptor1);
1889 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1890 descriptor += sizeof(BlockDescriptor2);
1891 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1892
1893 if (const char *type = descriptor3->signature) {
1894 CYPool pool;
1895
1896 void *setup[1];
1897 setup[0] = &self;
1898
1899 sig::Signature signature;
1900 sig::Parse(pool, &signature, type, &Structor_);
1901
1902 ffi_cif cif;
1903 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1904
1905 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1906 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1907 }
1908 }
1909
1910 if (count != 0)
1911 CYThrow("NSBlock without signature field passed arguments");
1912
1913 CYPoolTry {
1914 [self invoke];
1915 } CYPoolCatch(NULL);
1916
1917 return NULL;
1918 } CYCatch(NULL) }
1919
1920 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1921 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1922 Class _class(internal->GetValue());
1923 if (!CYIsClass(_class))
1924 return false;
1925
1926 if (CYJSValueIsNSObject(context, instance)) {
1927 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1928 // XXX: this isn't always safe
1929 return [linternal->GetValue() isKindOfClass:_class];
1930 }
1931
1932 return false;
1933 } CYCatch(false) }
1934
1935 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1936 if (count == 0)
1937 throw CYJSError(context, "incorrect number of arguments to Instance");
1938 CYPool pool;
1939 id value(CYCastNSObject(&pool, context, arguments[0]));
1940 if (value == nil)
1941 value = [NSNull null];
1942 return CYCastJSValue(context, [value cy$box]);
1943 } CYCatch(NULL) }
1944
1945 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1946 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1947 CYPool pool;
1948
1949 id self(internal->GetValue());
1950 const char *name(CYPoolCString(pool, context, property));
1951
1952 if (object_getInstanceVariable(self, name, NULL) != NULL)
1953 return true;
1954
1955 return false;
1956 }
1957
1958 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
1959 length = CYCastDouble(encoding + 1);
1960 shift = 0;
1961
1962 unsigned int size;
1963 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
1964 for (size_t i(0); i != size; ++i)
1965 if (ivars[i] == ivar)
1966 break;
1967 else if (ivar_getOffset(ivars[i]) == offset) {
1968 const char *encoding(ivar_getTypeEncoding(ivars[i]));
1969 _assert(encoding[0] == 'b');
1970 shift += CYCastDouble(encoding + 1);
1971 }
1972 free(ivars);
1973 }
1974
1975 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1976 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1977 CYPool pool;
1978
1979 id self(internal->GetValue());
1980 const char *name(CYPoolCString(pool, context, property));
1981
1982 #ifdef __arm64__
1983 if (strcmp(name, "isa") == 0)
1984 return CYCastJSValue(context, object_getClass(self));
1985 #endif
1986
1987 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1988 ptrdiff_t offset(ivar_getOffset(ivar));
1989 void *data(reinterpret_cast<uint8_t *>(self) + offset);
1990
1991 const char *encoding(ivar_getTypeEncoding(ivar));
1992 if (encoding[0] == 'b') {
1993 unsigned length, shift;
1994 CYBitField(length, shift, self, ivar, encoding, offset);
1995 _assert(shift + length <= sizeof(uintptr_t) * 8);
1996 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
1997 uintptr_t mask((1 << length) - 1);
1998 return CYCastJSValue(context, (field >> shift) & mask);
1999 } else {
2000 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2001 return CYFromFFI(context, type.type_, type.GetFFI(), data);
2002 }
2003 }
2004
2005 return NULL;
2006 } CYCatch(NULL) }
2007
2008 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2009 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2010 CYPool pool;
2011
2012 id self(internal->GetValue());
2013 const char *name(CYPoolCString(pool, context, property));
2014
2015 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2016 ptrdiff_t offset(ivar_getOffset(ivar));
2017 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2018
2019 const char *encoding(ivar_getTypeEncoding(ivar));
2020 if (encoding[0] == 'b') {
2021 unsigned length, shift;
2022 CYBitField(length, shift, self, ivar, encoding, offset);
2023 _assert(shift + length <= sizeof(uintptr_t) * 8);
2024 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2025 uintptr_t mask((1 << length) - 1);
2026 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2027 } else {
2028 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2029 CYPoolFFI(&pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2030 return true;
2031 }
2032 }
2033
2034 return false;
2035 } CYCatch(false) }
2036
2037 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2038 if (Class super = class_getSuperclass(_class))
2039 Internal_getPropertyNames_(super, names);
2040
2041 #if OBJC_API_VERSION >= 2
2042 unsigned int size;
2043 objc_ivar **data(class_copyIvarList(_class, &size));
2044 for (size_t i(0); i != size; ++i)
2045 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2046 free(data);
2047 #else
2048 if (objc_ivar_list *ivars = _class->ivars)
2049 for (int i(0); i != ivars->ivar_count; ++i)
2050 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2051 #endif
2052 }
2053
2054 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2055 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2056 CYPool pool;
2057
2058 id self(internal->GetValue());
2059 Class _class(object_getClass(self));
2060
2061 Internal_getPropertyNames_(_class, names);
2062 }
2063
2064 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2065 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2066 return internal->GetOwner();
2067 } CYCatch(NULL) }
2068
2069 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2070 CYPool pool;
2071 NSString *name(CYCastNSString(&pool, context, property));
2072 if (Class _class = NSClassFromString(name))
2073 return CYMakeInstance(context, _class, true);
2074 return NULL;
2075 } CYCatch(NULL) }
2076
2077 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2078 #ifdef __APPLE__
2079 size_t size(objc_getClassList(NULL, 0));
2080 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2081
2082 get:
2083 size_t writ(objc_getClassList(data, size));
2084 if (size < writ) {
2085 size = writ;
2086 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2087 data = copy;
2088 goto get;
2089 } else goto done;
2090 }
2091
2092 for (size_t i(0); i != writ; ++i)
2093 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2094
2095 done:
2096 free(data);
2097 #else
2098 void *state(NULL);
2099 while (Class _class = objc_next_class(&state))
2100 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2101 #endif
2102 }
2103
2104 #if OBJC_API_VERSION >= 2
2105 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2106 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2107
2108 CYPool pool;
2109 const char *name(CYPoolCString(pool, context, property));
2110 unsigned int size;
2111 const char **data(objc_copyClassNamesForImage(internal, &size));
2112 JSValueRef value;
2113 for (size_t i(0); i != size; ++i)
2114 if (strcmp(name, data[i]) == 0) {
2115 if (Class _class = objc_getClass(name)) {
2116 value = CYMakeInstance(context, _class, true);
2117 goto free;
2118 } else
2119 break;
2120 }
2121 value = NULL;
2122 free:
2123 free(data);
2124 return value;
2125 } CYCatch(NULL) }
2126
2127 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2128 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2129 unsigned int size;
2130 const char **data(objc_copyClassNamesForImage(internal, &size));
2131 for (size_t i(0); i != size; ++i)
2132 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2133 free(data);
2134 }
2135
2136 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2137 CYPool pool;
2138 const char *name(CYPoolCString(pool, context, property));
2139 unsigned int size;
2140 const char **data(objc_copyImageNames(&size));
2141 for (size_t i(0); i != size; ++i)
2142 if (strcmp(name, data[i]) == 0) {
2143 name = data[i];
2144 goto free;
2145 }
2146 name = NULL;
2147 free:
2148 free(data);
2149 if (name == NULL)
2150 return NULL;
2151 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2152 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2153 return value;
2154 } CYCatch(NULL) }
2155
2156 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2157 unsigned int size;
2158 const char **data(objc_copyImageNames(&size));
2159 for (size_t i(0); i != size; ++i)
2160 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2161 free(data);
2162 }
2163 #endif
2164
2165 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2166 CYPool pool;
2167 const char *name(CYPoolCString(pool, context, property));
2168 if (Protocol *protocol = objc_getProtocol(name))
2169 return CYMakeInstance(context, protocol, true);
2170 return NULL;
2171 } CYCatch(NULL) }
2172
2173 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2174 #if OBJC_API_VERSION >= 2
2175 unsigned int size;
2176 Protocol **data(objc_copyProtocolList(&size));
2177 for (size_t i(0); i != size; ++i)
2178 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2179 free(data);
2180 #else
2181 // XXX: fix this!
2182 #endif
2183 }
2184
2185 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2186 CYPool pool;
2187 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2188 if (name == "nil")
2189 return Instance::Make(context, nil);
2190 return NULL;
2191 } CYCatch(NULL) }
2192
2193 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2194 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2195 }
2196
2197 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2198 *data = reinterpret_cast<void *>(address);
2199 return KERN_SUCCESS;
2200 }
2201
2202 struct CYChoice {
2203 Class query_;
2204 JSContextRef context_;
2205 JSObjectRef results_;
2206 };
2207
2208 struct CYObjectStruct {
2209 Class isa_;
2210 };
2211
2212 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2213 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2214 JSContextRef context(choice->context_);
2215
2216 for (unsigned i(0); i != count; ++i) {
2217 vm_range_t &range(ranges[i]);
2218 void *data(reinterpret_cast<void *>(range.address));
2219 size_t size(range.size);
2220
2221 if (size < sizeof(CYObjectStruct))
2222 continue;
2223
2224 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2225 #ifdef __arm64__
2226 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2227 #else
2228 Class isa(reinterpret_cast<Class>(pointers[0]));
2229 #endif
2230
2231 if (isa != choice->query_)
2232 continue;
2233 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2234 }
2235 }
2236
2237 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2238 if (count != 1)
2239 throw CYJSError(context, "choose() takes a class argument");
2240
2241 CYPool pool;
2242 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2243
2244 vm_address_t *zones(NULL);
2245 unsigned size(0);
2246 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2247 _assert(error == KERN_SUCCESS);
2248
2249 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2250 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2251
2252 CYChoice choice;
2253 choice.query_ = _class;
2254 choice.context_ = context;
2255 choice.results_ = results;
2256
2257 for (unsigned i(0); i != size; ++i) {
2258 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2259 if (zone == NULL || zone->introspect == NULL)
2260 continue;
2261 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2262 }
2263
2264 return results;
2265 } CYCatch(NULL) }
2266
2267 #ifdef __APPLE__
2268 #if defined(__i386__) || defined(__x86_64__)
2269 #define OBJC_MAX_STRUCT_BY_VALUE 8
2270 static int struct_forward_array[] = {
2271 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2272 #elif defined(__arm__)
2273 #define OBJC_MAX_STRUCT_BY_VALUE 1
2274 static int struct_forward_array[] = {
2275 0, 0 };
2276 #elif defined(__arm64__)
2277 #define CY_NO_STRET
2278 #else
2279 #error missing objc-runtime-info
2280 #endif
2281
2282 #ifndef CY_NO_STRET
2283 static bool stret(ffi_type *ffi_type) {
2284 return ffi_type->type == FFI_TYPE_STRUCT && (
2285 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2286 struct_forward_array[ffi_type->size] != 0
2287 );
2288 }
2289 #endif
2290 #endif
2291
2292 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2293 const char *type;
2294
2295 if (_class == NULL)
2296 _class = object_getClass(self);
2297
2298 IMP imp;
2299
2300 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2301 imp = method_getImplementation(method);
2302 type = method_getTypeEncoding(method);
2303 } else {
2304 imp = NULL;
2305
2306 CYPoolTry {
2307 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2308 if (method == nil)
2309 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2310 type = CYPoolCString(pool, context, [method _typeString]);
2311 } CYPoolCatch(NULL)
2312 }
2313
2314 void *setup[2];
2315 setup[0] = &self;
2316 setup[1] = &_cmd;
2317
2318 sig::Signature signature;
2319 sig::Parse(pool, &signature, type, &Structor_);
2320
2321 size_t used(count + 3);
2322 if (used > signature.count) {
2323 sig::Element *elements(new (pool) sig::Element[used]);
2324 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2325
2326 for (size_t index(signature.count); index != used; ++index) {
2327 sig::Element *element(&elements[index]);
2328 element->name = NULL;
2329 element->offset = _not(size_t);
2330
2331 sig::Type *type(new (pool) sig::Type);
2332 memset(type, 0, sizeof(*type));
2333 type->primitive = sig::object_P;
2334 element->type = type;
2335 }
2336
2337 signature.elements = elements;
2338 signature.count = used;
2339 }
2340
2341 ffi_cif cif;
2342 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2343
2344 if (imp == NULL) {
2345 #ifdef __APPLE__
2346 #ifndef CY_NO_STRET
2347 if (stret(cif.rtype))
2348 imp = class_getMethodImplementation_stret(_class, _cmd);
2349 else
2350 #endif
2351 imp = class_getMethodImplementation(_class, _cmd);
2352 #else
2353 objc_super super = {self, _class};
2354 imp = objc_msg_lookup_super(&super, _cmd);
2355 #endif
2356 }
2357
2358 void (*function)() = reinterpret_cast<void (*)()>(imp);
2359 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2360 }
2361
2362 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2363 if (count < 2)
2364 throw CYJSError(context, "too few arguments to objc_msgSend");
2365
2366 CYPool pool;
2367
2368 bool uninitialized;
2369
2370 id self;
2371 SEL _cmd;
2372 Class _class;
2373
2374 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2375 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2376 self = internal->GetValue();
2377 _class = internal->class_;;
2378 uninitialized = false;
2379 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2380 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2381 self = internal->GetValue();
2382 _class = nil;
2383 uninitialized = internal->IsUninitialized();
2384 if (uninitialized)
2385 internal->value_ = nil;
2386 } else {
2387 self = CYCastNSObject(&pool, context, arguments[0]);
2388 _class = nil;
2389 uninitialized = false;
2390 }
2391
2392 if (self == nil)
2393 return CYJSNull(context);
2394
2395 _cmd = CYCastSEL(context, arguments[1]);
2396
2397 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2398 }
2399
2400 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2401 return $objc_msgSend(context, object, _this, count, arguments);
2402 } CYCatch(NULL) }
2403
2404 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2405 JSValueRef setup[count + 2];
2406 setup[0] = _this;
2407 setup[1] = object;
2408 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2409 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2410 } CYCatch(NULL) }
2411
2412 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2413 CYPool pool;
2414 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2415
2416 // XXX: handle Instance::Uninitialized?
2417 id self(CYCastNSObject(&pool, context, _this));
2418
2419 void *setup[2];
2420 setup[0] = &self;
2421 setup[1] = &internal->sel_;
2422
2423 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2424 } CYCatch(NULL) }
2425
2426 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2427 if (count != 2)
2428 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2429 CYPool pool;
2430 id self(CYCastNSObject(&pool, context, arguments[0]));
2431 Class _class(CYCastClass(pool, context, arguments[1]));
2432 return cy::Super::Make(context, self, _class);
2433 } CYCatch(NULL) }
2434
2435 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2436 if (count != 1)
2437 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2438 CYPool pool;
2439 const char *name(CYPoolCString(pool, context, arguments[0]));
2440 return CYMakeSelector(context, sel_registerName(name));
2441 } CYCatch(NULL) }
2442
2443 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2444 if (count > 1)
2445 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2446 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2447 return CYMakeInstance(context, self, false);
2448 } CYCatch(NULL) }
2449
2450 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2451 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2452 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2453 } CYCatch(NULL) }
2454
2455 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2456 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2457 Type_privateData *typical(internal->GetType());
2458
2459 sig::Type *type;
2460 ffi_type *ffi;
2461
2462 if (typical == NULL) {
2463 type = NULL;
2464 ffi = NULL;
2465 } else {
2466 type = typical->type_;
2467 ffi = typical->ffi_;
2468 }
2469
2470 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2471 } CYCatch(NULL) }
2472
2473 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2474 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2475 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2476 } CYCatch(NULL) }
2477
2478 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2479 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2480 id self(internal->GetValue());
2481 if (!CYIsClass(self))
2482 return CYJSUndefined(context);
2483 return CYGetClassPrototype(context, self);
2484 } CYCatch(NULL) }
2485
2486 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2487 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2488 id self(internal->GetValue());
2489 if (!CYIsClass(self))
2490 return CYJSUndefined(context);
2491 return Messages::Make(context, (Class) self);
2492 } CYCatch(NULL) }
2493
2494 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2495 if (!CYJSValueIsNSObject(context, _this))
2496 return NULL;
2497
2498 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2499 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2500 } CYCatch(NULL) }
2501
2502 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2503 if (!CYJSValueIsNSObject(context, _this))
2504 return NULL;
2505
2506 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2507 id value(internal->GetValue());
2508
2509 CYPoolTry {
2510 NSString *key;
2511 if (count == 0)
2512 key = nil;
2513 else
2514 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2515
2516 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2517 return CYJSUndefined(context);
2518 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2519 return json;
2520 else
2521 return CYCastJSValue(context, CYJSString(context, [value description]));
2522 } CYPoolCatch(NULL)
2523 } CYCatch(NULL) return /*XXX*/ NULL; }
2524
2525 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2526 if (!CYJSValueIsNSObject(context, _this))
2527 return NULL;
2528
2529 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2530 id value(internal->GetValue());
2531
2532 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2533 return _this;
2534
2535 if (JSValueRef result = [value cy$valueOfInContext:context])
2536 return result;
2537
2538 return _this;
2539 } CYCatch(NULL) return /*XXX*/ NULL; }
2540
2541 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2542 if (!CYJSValueIsNSObject(context, _this))
2543 return NULL;
2544
2545 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2546 // XXX: but... but... THIS ISN'T A POINTER! :(
2547 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2548 } CYCatch(NULL) return /*XXX*/ NULL; }
2549
2550 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2551 if (!CYJSValueIsNSObject(context, _this))
2552 return NULL;
2553
2554 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2555 id value(internal->GetValue());
2556
2557 CYPoolTry {
2558 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2559 return CYCastJSValue(context, CYJSString(context, [value description]));
2560 } CYPoolCatch(NULL)
2561 } CYCatch(NULL) return /*XXX*/ NULL; }
2562
2563 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2564 if (!CYJSValueIsNSObject(context, _this))
2565 return NULL;
2566
2567 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2568 id value(internal->GetValue());
2569
2570 if (!CYIsClass(value))
2571 CYThrow("non-Class object cannot be used as Type");
2572
2573 // XXX: this is a very silly implementation
2574
2575 std::ostringstream type;
2576 type << "@\"";
2577 type << class_getName(value);
2578 type << "\"";
2579
2580 CYPoolTry {
2581 return CYMakeType(context, type.str().c_str());
2582 } CYPoolCatch(NULL)
2583 } CYCatch(NULL) return /*XXX*/ NULL; }
2584
2585 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2586 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2587 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2588 } CYCatch(NULL) }
2589
2590 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2591 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2592 }
2593
2594 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2595 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2596 const char *name(sel_getName(internal->GetValue()));
2597
2598 CYPoolTry {
2599 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2600 return CYCastJSValue(context, CYJSString(context, string));
2601 } CYPoolCatch(NULL)
2602 } CYCatch(NULL) return /*XXX*/ NULL; }
2603
2604 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2605 if (count != 1)
2606 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2607
2608 CYPool pool;
2609 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2610 SEL sel(internal->GetValue());
2611
2612 objc_method *method;
2613 if (Class _class = CYCastClass(pool, context, arguments[0]))
2614 method = class_getInstanceMethod(_class, sel);
2615 else
2616 method = NULL;
2617
2618 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2619 return CYCastJSValue(context, CYJSString(type));
2620
2621 return CYJSNull(context);
2622 } CYCatch(NULL) }
2623
2624 static JSStaticValue Selector_staticValues[2] = {
2625 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2626 {NULL, NULL, NULL, 0}
2627 };
2628
2629 static JSStaticValue Instance_staticValues[5] = {
2630 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2631 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2632 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2633 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2634 {NULL, NULL, NULL, 0}
2635 };
2636
2637 static JSStaticFunction Instance_staticFunctions[7] = {
2638 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2639 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2640 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2641 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2642 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2643 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2644 {NULL, NULL, 0}
2645 };
2646
2647 static JSStaticFunction Class_staticFunctions[2] = {
2648 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2649 {NULL, NULL, 0}
2650 };
2651
2652 static JSStaticFunction Internal_staticFunctions[2] = {
2653 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2654 {NULL, NULL, 0}
2655 };
2656
2657 static JSStaticFunction Selector_staticFunctions[5] = {
2658 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2659 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2660 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2661 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2662 {NULL, NULL, 0}
2663 };
2664
2665 #ifdef __APPLE__
2666 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2667 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2668 } CYObjectiveCatch }
2669 #endif
2670
2671 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2672 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2673 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2674 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2675
2676 CYPool &pool(CYGetGlobalPool());
2677
2678 Object_type = new(pool) Type_privateData("@");
2679 Selector_type = new(pool) Type_privateData(":");
2680
2681 NSArray_ = objc_getClass("NSArray");
2682 NSBlock_ = objc_getClass("NSBlock");
2683 NSDictionary_ = objc_getClass("NSDictionary");
2684 NSString_ = objc_getClass("NSString");
2685 Object_ = objc_getClass("Object");
2686
2687 #ifdef __APPLE__
2688 // XXX: apparently, iOS now has both of these
2689 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2690 if (NSCFBoolean_ == nil)
2691 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2692
2693 NSCFType_ = objc_getClass("NSCFType");
2694
2695 NSZombie_ = objc_getClass("_NSZombie_");
2696
2697 banned_.insert(Object_);
2698 banned_.insert(objc_getClass("__NSAtom"));
2699 banned_.insert(objc_getClass("__NSGenericDeallocHandler"));
2700 banned_.insert(objc_getClass("NSMessageBuilder"));
2701 banned_.insert(objc_getClass("__NSMessageBuilder"));
2702 #else
2703 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2704 #endif
2705
2706 JSClassDefinition definition;
2707
2708 definition = kJSClassDefinitionEmpty;
2709 definition.className = "Instance";
2710 definition.staticValues = Instance_staticValues;
2711 definition.staticFunctions = Instance_staticFunctions;
2712 definition.hasProperty = &Instance_hasProperty;
2713 definition.getProperty = &Instance_getProperty;
2714 definition.setProperty = &Instance_setProperty;
2715 definition.deleteProperty = &Instance_deleteProperty;
2716 definition.getPropertyNames = &Instance_getPropertyNames;
2717 definition.callAsConstructor = &Instance_callAsConstructor;
2718 definition.callAsFunction = &Instance_callAsFunction;
2719 definition.hasInstance = &Instance_hasInstance;
2720 definition.finalize = &CYFinalize;
2721 Instance_ = JSClassCreate(&definition);
2722
2723 definition.className = "ArrayInstance";
2724 ArrayInstance_ = JSClassCreate(&definition);
2725
2726 definition.className = "FunctionInstance";
2727 FunctionInstance_ = JSClassCreate(&definition);
2728
2729 definition.className = "ObjectInstance";
2730 ObjectInstance_ = JSClassCreate(&definition);
2731
2732 definition.className = "StringInstance";
2733 StringInstance_ = JSClassCreate(&definition);
2734
2735 definition = kJSClassDefinitionEmpty;
2736 definition.className = "Class";
2737 definition.staticFunctions = Class_staticFunctions;
2738 Class_ = JSClassCreate(&definition);
2739
2740 definition = kJSClassDefinitionEmpty;
2741 definition.className = "Internal";
2742 definition.staticFunctions = Internal_staticFunctions;
2743 definition.hasProperty = &Internal_hasProperty;
2744 definition.getProperty = &Internal_getProperty;
2745 definition.setProperty = &Internal_setProperty;
2746 definition.getPropertyNames = &Internal_getPropertyNames;
2747 definition.finalize = &CYFinalize;
2748 Internal_ = JSClassCreate(&definition);
2749
2750 definition = kJSClassDefinitionEmpty;
2751 definition.className = "Message";
2752 definition.staticFunctions = cy::Functor::StaticFunctions;
2753 definition.callAsFunction = &Message_callAsFunction;
2754 definition.finalize = &CYFinalize;
2755 Message_ = JSClassCreate(&definition);
2756
2757 definition = kJSClassDefinitionEmpty;
2758 definition.className = "Messages";
2759 definition.hasProperty = &Messages_hasProperty;
2760 definition.getProperty = &Messages_getProperty;
2761 definition.setProperty = &Messages_setProperty;
2762 #if 0 && OBJC_API_VERSION < 2
2763 definition.deleteProperty = &Messages_deleteProperty;
2764 #endif
2765 definition.getPropertyNames = &Messages_getPropertyNames;
2766 definition.finalize = &CYFinalize;
2767 Messages_ = JSClassCreate(&definition);
2768
2769 definition = kJSClassDefinitionEmpty;
2770 definition.className = "Selector";
2771 definition.staticValues = Selector_staticValues;
2772 definition.staticFunctions = Selector_staticFunctions;
2773 definition.callAsFunction = &Selector_callAsFunction;
2774 definition.finalize = &CYFinalize;
2775 Selector_ = JSClassCreate(&definition);
2776
2777 definition = kJSClassDefinitionEmpty;
2778 definition.className = "Super";
2779 definition.staticFunctions = Internal_staticFunctions;
2780 definition.finalize = &CYFinalize;
2781 Super_ = JSClassCreate(&definition);
2782
2783 definition = kJSClassDefinitionEmpty;
2784 definition.className = "ObjectiveC::Classes";
2785 definition.getProperty = &ObjectiveC_Classes_getProperty;
2786 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2787 ObjectiveC_Classes_ = JSClassCreate(&definition);
2788
2789 definition = kJSClassDefinitionEmpty;
2790 definition.className = "ObjectiveC::Constants";
2791 definition.getProperty = &ObjectiveC_Constants_getProperty;
2792 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2793 ObjectiveC_Constants_ = JSClassCreate(&definition);
2794
2795 #if OBJC_API_VERSION >= 2
2796 definition = kJSClassDefinitionEmpty;
2797 definition.className = "ObjectiveC::Images";
2798 definition.getProperty = &ObjectiveC_Images_getProperty;
2799 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2800 ObjectiveC_Images_ = JSClassCreate(&definition);
2801
2802 definition = kJSClassDefinitionEmpty;
2803 definition.className = "ObjectiveC::Image::Classes";
2804 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2805 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2806 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2807 #endif
2808
2809 definition = kJSClassDefinitionEmpty;
2810 definition.className = "ObjectiveC::Protocols";
2811 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2812 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2813 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2814
2815 #ifdef __APPLE__
2816 // XXX: this is horrible; there has to be a better way to do this
2817 #ifdef __LP64__
2818 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24");
2819 #else
2820 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2821 #endif
2822 #endif
2823 } CYPoolCatch() }
2824
2825 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2826 JSObjectRef global(CYGetGlobalObject(context));
2827 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2828 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2829 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2830 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2831
2832 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2833 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2834
2835 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2836 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2837 CYArrayPush(context, alls, protocols);
2838
2839 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2840 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2841 CYArrayPush(context, alls, classes);
2842
2843 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2844 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2845 CYArrayPush(context, alls, constants);
2846
2847 #if OBJC_API_VERSION >= 2
2848 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2849 #endif
2850
2851 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2852 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2853 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2854 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2855 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2856
2857 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2858 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2859
2860 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2861 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2862 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2863 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2864 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2865
2866 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2867 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2868 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2869 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2870 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2871
2872 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2873 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2874 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2875 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2876 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2877
2878 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2879 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2880 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2881 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2882 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2883
2884 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2885 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2886 JSObjectSetPrototype(context, Class_prototype, Instance_prototype);
2887
2888 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2889 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2890 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2891
2892 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2893 CYSetProperty(context, Instance, CYJSString("box"), box);
2894
2895 #if defined(__APPLE__) && defined(__arm__) && 0
2896 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2897 #endif
2898
2899 #ifdef __APPLE__
2900 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2901 #endif
2902
2903 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2904
2905 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2906 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2907 } CYPoolCatch() }
2908
2909 static CYHooks CYObjectiveCHooks = {
2910 &CYObjectiveC_ExecuteStart,
2911 &CYObjectiveC_ExecuteEnd,
2912 &CYObjectiveC_CallFunction,
2913 &CYObjectiveC_Initialize,
2914 &CYObjectiveC_SetupContext,
2915 &CYObjectiveC_PoolFFI,
2916 &CYObjectiveC_FromFFI,
2917 };
2918
2919 struct CYObjectiveC {
2920 CYObjectiveC() {
2921 hooks_ = &CYObjectiveCHooks;
2922 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2923 _assert(hooks_ != NULL);
2924 }
2925 } CYObjectiveC;