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