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