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