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