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