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