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