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