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