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