]> git.saurik.com Git - cycript.git/blob - ObjectiveC/Library.mm
This implementation for Java works, but I hate it.
[cycript.git] / ObjectiveC / Library.mm
1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2015 Jay Freeman (saurik)
3 */
4
5 /* GNU Affero General Public License, Version 3 {{{ */
6 /*
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 **/
20 /* }}} */
21
22 #include "cycript.hpp"
23
24 #include <cmath>
25
26 #include <map>
27 #include <set>
28
29 #include <dlfcn.h>
30
31 #ifdef __APPLE__
32 #include <malloc/malloc.h>
33 #include <mach/mach.h>
34 #endif
35
36 #include <objc/message.h>
37 #include <objc/runtime.h>
38
39 #ifdef __APPLE__
40 #include <CoreFoundation/CoreFoundation.h>
41 #include <JavaScriptCore/JSStringRefCF.h>
42 #endif
43
44 #include <Foundation/Foundation.h>
45
46 #include "Code.hpp"
47 #include "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 CYTypedIdentifier *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(Class _class) {
1701 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1702 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1703 return true;
1704 return [_class cy$hasImplicitProperties];
1705 }
1706
1707 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1708 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1709 id self(internal->value_);
1710
1711 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1712 return true;
1713
1714 CYPool pool;
1715 NSString *name(CYCastNSString(&pool, context, property));
1716
1717 if (CYInternal *internal = [CYInternal get:self])
1718 if ([internal hasProperty:property inContext:context])
1719 return true;
1720
1721 Class _class(object_getClass(self));
1722
1723 CYPoolTry {
1724 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1725 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1726 if ([self cy$hasProperty:name])
1727 return true;
1728 } CYPoolCatch(false)
1729
1730 const char *string(CYPoolCString(pool, context, name));
1731
1732 if (class_getProperty(_class, string) != NULL)
1733 return true;
1734
1735 if (CYHasImplicitProperties(_class))
1736 if (SEL sel = sel_getUid(string))
1737 if (CYImplements(self, _class, sel, true))
1738 return true;
1739
1740 return false;
1741 }
1742
1743 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1744 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1745 id self(internal->value_);
1746
1747 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1748 return Internal::Make(context, self, context, object);
1749
1750 CYPool pool;
1751 NSString *name(CYCastNSString(&pool, context, property));
1752
1753 if (CYInternal *internal = [CYInternal get:self])
1754 if (JSValueRef value = [internal getProperty:property inContext:context])
1755 return value;
1756
1757 CYPoolTry {
1758 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1759 return value;
1760 } CYPoolCatch(NULL)
1761
1762 const char *string(CYPoolCString(pool, context, name));
1763 Class _class(object_getClass(self));
1764
1765 if (objc_property_t property = class_getProperty(_class, string)) {
1766 PropertyAttributes attributes(property);
1767 SEL sel(sel_registerName(attributes.Getter()));
1768 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1769 }
1770
1771 if (CYHasImplicitProperties(_class))
1772 if (SEL sel = sel_getUid(string))
1773 if (CYImplements(self, _class, sel, true))
1774 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1775
1776 return NULL;
1777 } CYCatch(NULL) }
1778
1779 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1780 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1781 id self(internal->value_);
1782
1783 CYPool pool;
1784
1785 NSString *name(CYCastNSString(&pool, context, property));
1786 NSObject *data(CYCastNSObject(&pool, context, value));
1787
1788 CYPoolTry {
1789 if ([self cy$setProperty:name to:data])
1790 return true;
1791 } CYPoolCatch(false)
1792
1793 const char *string(CYPoolCString(pool, context, name));
1794 Class _class(object_getClass(self));
1795
1796 if (objc_property_t property = class_getProperty(_class, string)) {
1797 PropertyAttributes attributes(property);
1798 if (const char *setter = attributes.Setter()) {
1799 SEL sel(sel_registerName(setter));
1800 JSValueRef arguments[1] = {value};
1801 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1802 return true;
1803 }
1804 }
1805
1806 size_t length(strlen(string));
1807
1808 char set[length + 5];
1809
1810 set[0] = 's';
1811 set[1] = 'e';
1812 set[2] = 't';
1813
1814 if (string[0] != '\0') {
1815 set[3] = toupper(string[0]);
1816 memcpy(set + 4, string + 1, length - 1);
1817 }
1818
1819 set[length + 3] = ':';
1820 set[length + 4] = '\0';
1821
1822 if (SEL sel = sel_getUid(set))
1823 if (CYImplements(self, _class, sel)) {
1824 JSValueRef arguments[1] = {value};
1825 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1826 return true;
1827 }
1828
1829 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1830 [internal setProperty:property toValue:value inContext:context];
1831 return true;
1832 }
1833
1834 return false;
1835 } CYCatch(false) }
1836
1837 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1838 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1839 id self(internal->value_);
1840
1841 CYPoolTry {
1842 NSString *name(CYCastNSString(NULL, context, property));
1843 return [self cy$deleteProperty:name];
1844 } CYPoolCatch(false)
1845 } CYCatch(false) return /*XXX*/ false; }
1846
1847 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1848 const char *name(sel_getName(method_getName(method)));
1849 if (strchr(name, ':') != NULL)
1850 return;
1851
1852 const char *type(method_getTypeEncoding(method));
1853 if (type == NULL || *type == '\0' || *type == 'v')
1854 return;
1855
1856 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1857 }
1858
1859 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1860 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1861 id self(internal->value_);
1862
1863 CYPool pool;
1864 Class _class(object_getClass(self));
1865
1866 {
1867 unsigned int size;
1868 objc_property_t *data(class_copyPropertyList(_class, &size));
1869 for (size_t i(0); i != size; ++i)
1870 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1871 free(data);
1872 }
1873
1874 if (CYHasImplicitProperties(_class))
1875 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1876 unsigned int size;
1877 objc_method **data(class_copyMethodList(current, &size));
1878 for (size_t i(0); i != size; ++i)
1879 Instance_getPropertyNames_message(names, data[i]);
1880 free(data);
1881 }
1882
1883 CYPoolTry {
1884 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1885 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1886 [self cy$getPropertyNames:names inContext:context];
1887 } CYPoolCatch()
1888 }
1889
1890 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1891 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1892 JSObjectRef value(CYMakeInstance(context, [internal->value_ alloc], Instance::Uninitialized));
1893 return value;
1894 } CYCatch(NULL) }
1895
1896 static const char *CYBlockEncoding(NSBlock *self) {
1897 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1898 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1899 return NULL;
1900 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1901 descriptor += sizeof(BlockDescriptor1);
1902 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1903 descriptor += sizeof(BlockDescriptor2);
1904 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1905 return descriptor3->signature;
1906 }
1907
1908 static bool CYBlockSignature(CYPool &pool, NSBlock *self, sig::Signature &signature) {
1909 const char *encoding(CYBlockEncoding(self));
1910 if (encoding == NULL)
1911 return false;
1912
1913 sig::Parse(pool, &signature, encoding, &Structor_);
1914 _assert(signature.count >= 2);
1915
1916 _assert(dynamic_cast<sig::Object *>(signature.elements[1].type) != NULL);
1917 signature.elements[1] = signature.elements[0];
1918
1919 ++signature.elements;
1920 --signature.count;
1921
1922 return true;
1923 }
1924
1925 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1926 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1927 id self(internal->value_);
1928
1929 if (const char *encoding = CYBlockEncoding(self)) {
1930 CYPool pool;
1931
1932 void *setup[1];
1933 setup[0] = &self;
1934
1935 sig::Signature signature;
1936 sig::Parse(pool, &signature, encoding, &Structor_);
1937
1938 ffi_cif cif;
1939 sig::sig_ffi_cif(pool, 0, signature, &cif);
1940
1941 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1942 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1943 return CYCallFunction(pool, context, 1, setup, count, arguments, false, false, signature, &cif, function);
1944 }
1945
1946 if (count != 0)
1947 CYThrow("NSBlock without signature field passed arguments");
1948
1949 CYPoolTry {
1950 [self invoke];
1951 } CYPoolCatch(NULL);
1952
1953 return NULL;
1954 } CYCatch(NULL) }
1955
1956 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1957 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1958 Class _class(internal->value_);
1959 if (!CYIsClass(_class))
1960 return false;
1961
1962 if (CYJSValueIsNSObject(context, instance)) {
1963 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1964 // XXX: this isn't always safe
1965 return [linternal->value_ isKindOfClass:_class];
1966 }
1967
1968 return false;
1969 } CYCatch(false) }
1970
1971 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1972 if (count == 0)
1973 throw CYJSError(context, "incorrect number of arguments to Instance");
1974 CYPool pool;
1975 id value(CYCastNSObject(&pool, context, arguments[0]));
1976 if (value == nil)
1977 value = [NSNull null];
1978 return CYCastJSValue(context, [value cy$box]);
1979 } CYCatch(NULL) }
1980
1981 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1982 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1983 CYPool pool;
1984
1985 id self(internal->value_);
1986 const char *name(CYPoolCString(pool, context, property));
1987
1988 if (object_getInstanceVariable(self, name, NULL) != NULL)
1989 return true;
1990
1991 return false;
1992 }
1993
1994 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
1995 length = CYCastDouble(encoding + 1);
1996 shift = 0;
1997
1998 unsigned int size;
1999 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2000 for (size_t i(0); i != size; ++i)
2001 if (ivars[i] == ivar)
2002 break;
2003 else if (ivar_getOffset(ivars[i]) == offset) {
2004 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2005 _assert(encoding != NULL);
2006 _assert(encoding[0] == 'b');
2007 shift += CYCastDouble(encoding + 1);
2008 }
2009 free(ivars);
2010 }
2011
2012 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2013 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2014 CYPool pool;
2015
2016 id self(internal->value_);
2017 const char *name(CYPoolCString(pool, context, property));
2018
2019 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2020 ptrdiff_t offset(ivar_getOffset(ivar));
2021 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2022
2023 const char *encoding(ivar_getTypeEncoding(ivar));
2024 _assert(encoding != NULL);
2025 _assert(encoding[0] != '\0');
2026 if (encoding[0] == 'b') {
2027 unsigned length, shift;
2028 CYBitField(length, shift, self, ivar, encoding, offset);
2029 _assert(shift + length <= sizeof(uintptr_t) * 8);
2030 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2031 uintptr_t mask((1 << length) - 1);
2032 return CYCastJSValue(context, (field >> shift) & mask);
2033 } else {
2034 #if defined(__APPLE__) && defined(__LP64__)
2035 // XXX: maybe do even more verifications here
2036 if (strcmp(name, "isa") == 0)
2037 return CYCastJSValue(context, object_getClass(self));
2038 #endif
2039
2040 auto type(new(pool) Type_privateData(encoding));
2041 return type->type_->FromFFI(context, type->GetFFI(), data);
2042 }
2043 }
2044
2045 return NULL;
2046 } CYCatch(NULL) }
2047
2048 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2049 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2050 CYPool pool;
2051
2052 id self(internal->value_);
2053 const char *name(CYPoolCString(pool, context, property));
2054
2055 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2056 ptrdiff_t offset(ivar_getOffset(ivar));
2057 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2058
2059 const char *encoding(ivar_getTypeEncoding(ivar));
2060 _assert(encoding != NULL);
2061 if (encoding[0] == 'b') {
2062 unsigned length, shift;
2063 CYBitField(length, shift, self, ivar, encoding, offset);
2064 _assert(shift + length <= sizeof(uintptr_t) * 8);
2065 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2066 uintptr_t mask((1 << length) - 1);
2067 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2068 } else {
2069 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2070 type->type_->PoolFFI(&pool, context, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2071 return true;
2072 }
2073 }
2074
2075 return false;
2076 } CYCatch(false) }
2077
2078 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2079 if (Class super = class_getSuperclass(_class))
2080 Internal_getPropertyNames_(super, names);
2081
2082 unsigned int size;
2083 objc_ivar **data(class_copyIvarList(_class, &size));
2084 for (size_t i(0); i != size; ++i)
2085 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2086 free(data);
2087 }
2088
2089 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2090 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2091 CYPool pool;
2092
2093 id self(internal->value_);
2094 Class _class(object_getClass(self));
2095
2096 Internal_getPropertyNames_(_class, names);
2097 }
2098
2099 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2100 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2101 return internal->owner_;
2102 } CYCatch(NULL) }
2103
2104 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2105 CYPool pool;
2106 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2107 }
2108
2109 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2110 CYPool pool;
2111 NSString *name(CYCastNSString(&pool, context, property));
2112 if (Class _class = NSClassFromString(name))
2113 return CYMakeInstance(context, _class, Instance::Permanent);
2114 return NULL;
2115 } CYCatch(NULL) }
2116
2117 static Class *CYCopyClassList(size_t &size) {
2118 size = objc_getClassList(NULL, 0);
2119 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2120
2121 for (;;) {
2122 size_t writ(objc_getClassList(data, size));
2123 if (writ <= size) {
2124 size = writ;
2125 return data;
2126 }
2127
2128 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2129 if (copy == NULL) {
2130 free(data);
2131 return NULL;
2132 }
2133
2134 data = copy;
2135 size = writ;
2136 }
2137 }
2138
2139 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2140 size_t size;
2141 if (Class *data = CYCopyClassList(size)) {
2142 for (size_t i(0); i != size; ++i)
2143 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2144 free(data);
2145 }
2146 }
2147
2148 #ifdef __APPLE__
2149 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2150 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2151
2152 CYPool pool;
2153 const char *name(CYPoolCString(pool, context, property));
2154 unsigned int size;
2155 const char **data(objc_copyClassNamesForImage(internal, &size));
2156 JSValueRef value;
2157 for (size_t i(0); i != size; ++i)
2158 if (strcmp(name, data[i]) == 0) {
2159 if (Class _class = objc_getClass(name)) {
2160 value = CYMakeInstance(context, _class, Instance::Permanent);
2161 goto free;
2162 } else
2163 break;
2164 }
2165 value = NULL;
2166 free:
2167 free(data);
2168 return value;
2169 } CYCatch(NULL) }
2170
2171 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2172 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2173 unsigned int size;
2174 const char **data(objc_copyClassNamesForImage(internal, &size));
2175 for (size_t i(0); i != size; ++i)
2176 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2177 free(data);
2178 }
2179
2180 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2181 CYPool pool;
2182 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2183
2184 unsigned int size;
2185 const char **data(objc_copyImageNames(&size));
2186 pool.atexit(free, data);
2187
2188 for (size_t i(0); i != size; ++i)
2189 if (name == data[i]) {
2190 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2191 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2192 return value;
2193 }
2194
2195 return NULL;
2196 } CYCatch(NULL) }
2197
2198 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2199 unsigned int size;
2200 const char **data(objc_copyImageNames(&size));
2201 for (size_t i(0); i != size; ++i)
2202 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2203 free(data);
2204 }
2205 #endif
2206
2207 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2208 CYPool pool;
2209 const char *name(CYPoolCString(pool, context, property));
2210 if (Protocol *protocol = objc_getProtocol(name))
2211 return CYMakeInstance(context, protocol, Instance::Permanent);
2212 return NULL;
2213 } CYCatch(NULL) }
2214
2215 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2216 unsigned int size;
2217 Protocol **data(objc_copyProtocolList(&size));
2218 for (size_t i(0); i != size; ++i)
2219 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2220 free(data);
2221 }
2222
2223 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2224 CYPool pool;
2225 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2226 if (name == "nil")
2227 return CYJSNull(context);
2228 return NULL;
2229 } CYCatch(NULL) }
2230
2231 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2232 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2233 }
2234
2235 #ifdef __APPLE__
2236 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2237 *data = reinterpret_cast<void *>(address);
2238 return KERN_SUCCESS;
2239 }
2240
2241 struct CYChoice {
2242 std::set<Class> query_;
2243 JSContextRef context_;
2244 JSObjectRef results_;
2245 };
2246
2247 struct CYObjectStruct {
2248 Class isa_;
2249 };
2250
2251 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2252 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2253 JSContextRef context(choice->context_);
2254
2255 for (unsigned i(0); i != count; ++i) {
2256 vm_range_t &range(ranges[i]);
2257 void *data(reinterpret_cast<void *>(range.address));
2258 size_t size(range.size);
2259
2260 if (size < sizeof(CYObjectStruct))
2261 continue;
2262
2263 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2264 #if defined(__APPLE__) && defined(__LP64__)
2265 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2266 #else
2267 Class isa(reinterpret_cast<Class>(pointers[0]));
2268 #endif
2269
2270 std::set<Class>::const_iterator result(choice->query_.find(isa));
2271 if (result == choice->query_.end())
2272 continue;
2273
2274 size_t needed(class_getInstanceSize(*result));
2275 // XXX: if (size < needed)
2276
2277 size_t boundary(496);
2278 #ifdef __LP64__
2279 boundary *= 2;
2280 #endif
2281 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2282 continue;
2283 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2284 }
2285 }
2286
2287 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2288 if (count != 1)
2289 throw CYJSError(context, "choose() takes a class argument");
2290
2291 CYGarbageCollect(context);
2292
2293 CYPool pool;
2294 id _class(CYCastNSObject(&pool, context, arguments[0]));
2295
2296 vm_address_t *zones(NULL);
2297 unsigned size(0);
2298 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2299 _assert(error == KERN_SUCCESS);
2300
2301 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2302 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2303
2304 CYChoice choice;
2305 choice.context_ = context;
2306 choice.results_ = results;
2307
2308 size_t number;
2309 Class *classes(CYCopyClassList(number));
2310 _assert(classes != NULL);
2311
2312 for (size_t i(0); i != number; ++i)
2313 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2314 if (current == _class) {
2315 choice.query_.insert(classes[i]);
2316 break;
2317 }
2318
2319 free(classes);
2320
2321 for (unsigned i(0); i != size; ++i) {
2322 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2323 if (zone == NULL || zone->introspect == NULL)
2324 continue;
2325
2326 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2327 }
2328
2329 return results;
2330 } CYCatch(NULL) }
2331 #endif
2332
2333 #ifdef __APPLE__
2334 #if defined(__i386__) || defined(__x86_64__)
2335 #define OBJC_MAX_STRUCT_BY_VALUE 8
2336 static int struct_forward_array[] = {
2337 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2338 #elif defined(__arm__)
2339 #define OBJC_MAX_STRUCT_BY_VALUE 1
2340 static int struct_forward_array[] = {
2341 0, 0 };
2342 #elif defined(__arm64__)
2343 #define CY_NO_STRET
2344 #else
2345 #error missing objc-runtime-info
2346 #endif
2347
2348 #ifndef CY_NO_STRET
2349 static bool stret(ffi_type *ffi_type) {
2350 return ffi_type->type == FFI_TYPE_STRUCT && (
2351 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2352 struct_forward_array[ffi_type->size] != 0
2353 );
2354 }
2355 #endif
2356 #else
2357 #define CY_NO_STRET
2358 #endif
2359
2360 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2361 const char *type;
2362
2363 if (_class == NULL)
2364 _class = object_getClass(self);
2365
2366 IMP imp;
2367
2368 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2369 imp = method_getImplementation(method);
2370 type = method_getTypeEncoding(method);
2371 } else {
2372 imp = NULL;
2373
2374 CYPoolTry {
2375 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2376 type = CYPoolCString(pool, context, [method _typeString]);
2377 else
2378 type = NULL;
2379 } CYPoolCatch(NULL)
2380
2381 if (type == NULL)
2382 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2383 }
2384
2385 void *setup[2];
2386 setup[0] = &self;
2387 setup[1] = &_cmd;
2388
2389 sig::Signature signature;
2390 sig::Parse(pool, &signature, type, &Structor_);
2391
2392 ffi_cif cif;
2393 sig::sig_ffi_cif(pool, 0, signature, &cif);
2394
2395 if (imp == NULL) {
2396 #ifndef CY_NO_STRET
2397 if (stret(cif.rtype))
2398 imp = class_getMethodImplementation_stret(_class, _cmd);
2399 else
2400 #endif
2401 imp = class_getMethodImplementation(_class, _cmd);
2402 }
2403
2404 void (*function)() = reinterpret_cast<void (*)()>(imp);
2405 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, true, signature, &cif, function);
2406 }
2407
2408 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2409 if (count < 2)
2410 throw CYJSError(context, "too few arguments to objc_msgSend");
2411
2412 CYPool pool;
2413
2414 bool uninitialized;
2415
2416 id self;
2417 SEL _cmd;
2418 Class _class;
2419
2420 if (JSValueIsObjectOfClass(context, arguments[0], cy::Super::Class_)) {
2421 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2422 self = internal->value_;
2423 _class = internal->class_;;
2424 uninitialized = false;
2425 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2426 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2427 self = internal->value_;
2428 _class = nil;
2429 uninitialized = internal->IsUninitialized();
2430 if (uninitialized)
2431 internal->value_ = nil;
2432 } else {
2433 self = CYCastNSObject(&pool, context, arguments[0]);
2434 _class = nil;
2435 uninitialized = false;
2436 }
2437
2438 if (self == nil)
2439 return CYJSNull(context);
2440
2441 _cmd = CYCastSEL(context, arguments[1]);
2442
2443 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2444 }
2445
2446 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2447 return $objc_msgSend(context, object, _this, count, arguments);
2448 } CYCatch(NULL) }
2449
2450 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2451 JSValueRef setup[count + 2];
2452 setup[0] = _this;
2453 setup[1] = object;
2454 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2455 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2456 } CYCatch(NULL) }
2457
2458 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2459 CYPool pool;
2460 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2461
2462 // XXX: handle Instance::Uninitialized?
2463 id self(CYCastNSObject(&pool, context, _this));
2464
2465 void *setup[2];
2466 setup[0] = &self;
2467 setup[1] = &internal->sel_;
2468
2469 return CYCallFunction(pool, context, 2, setup, count, arguments, false, true, internal->signature_, &internal->cif_, internal->value_);
2470 } CYCatch(NULL) }
2471
2472 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2473 if (count != 2)
2474 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2475 CYPool pool;
2476 id self(CYCastNSObject(&pool, context, arguments[0]));
2477 Class _class(CYCastClass(pool, context, arguments[1]));
2478 return cy::Super::Make(context, self, _class);
2479 } CYCatch(NULL) }
2480
2481 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2482 if (count != 1)
2483 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2484 CYPool pool;
2485 const char *name(CYPoolCString(pool, context, arguments[0]));
2486 return Selector_privateData::Make(context, sel_registerName(name));
2487 } CYCatch(NULL) }
2488
2489 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2490 if (count != 1)
2491 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2492 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2493 } CYCatch(NULL) }
2494
2495 static JSValueRef Selector_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2496 return CYMakeType(context, sig::Selector());
2497 } CYCatch(NULL) }
2498
2499 static JSValueRef Instance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2500 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2501 id self(internal->value_);
2502 if (CYIsClass(self))
2503 return CYMakeType(context, sig::Meta());
2504 return CYMakeType(context, sig::Object(class_getName(object_getClass(self))));
2505 } CYCatch(NULL) }
2506
2507 static JSValueRef FunctionInstance_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2508 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2509 CYPool pool;
2510 sig::Block type;
2511 if (!CYBlockSignature(pool, internal->value_, type.signature))
2512 return CYJSNull(context);
2513 return CYMakeType(context, type);
2514 } CYCatch(NULL) }
2515
2516 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2517 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2518 return CYMakeInstance(context, object_getClass(internal->value_), Instance::Permanent);
2519 } CYCatch(NULL) }
2520
2521 static JSValueRef Instance_getProperty_prototype(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 CYJSUndefined(context);
2526 return CYGetClassPrototype(context, self);
2527 } CYCatch(NULL) }
2528
2529 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2530 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2531 id self(internal->value_);
2532 if (!CYIsClass(self))
2533 return CYJSUndefined(context);
2534 return Messages::Make(context, (Class) self);
2535 } CYCatch(NULL) }
2536
2537 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2538 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2539
2540 if (!CYJSValueIsNSObject(context, _this))
2541 return NULL;
2542
2543 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2544 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->value_, false, objects)));
2545 } CYCatch(NULL) }
2546
2547 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2548 if (!CYJSValueIsNSObject(context, _this))
2549 return NULL;
2550
2551 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2552 id value(internal->value_);
2553
2554 CYPoolTry {
2555 NSString *key;
2556 if (count == 0)
2557 key = nil;
2558 else
2559 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2560
2561 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2562 return CYJSUndefined(context);
2563 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2564 return json;
2565 else
2566 return CYCastJSValue(context, CYJSString(context, [value description]));
2567 } CYPoolCatch(NULL)
2568 } CYCatch(NULL) return /*XXX*/ NULL; }
2569
2570 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2571 if (!CYJSValueIsNSObject(context, _this))
2572 return NULL;
2573
2574 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2575 id value(internal->value_);
2576 _assert(value != nil);
2577
2578 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2579 return _this;
2580
2581 if (JSValueRef result = [value cy$valueOfInContext:context])
2582 return result;
2583
2584 return _this;
2585 } CYCatch(NULL) return /*XXX*/ NULL; }
2586
2587 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2588 if (!CYJSValueIsNSObject(context, _this))
2589 return NULL;
2590
2591 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2592 // XXX: but... but... THIS ISN'T A POINTER! :(
2593 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2594 } CYCatch(NULL) return /*XXX*/ NULL; }
2595
2596 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2597 if (!CYJSValueIsNSObject(context, _this))
2598 return NULL;
2599
2600 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2601 id value(internal->value_);
2602
2603 CYPoolTry {
2604 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2605 return CYCastJSValue(context, CYJSString(context, [value description]));
2606 } CYPoolCatch(NULL)
2607 } CYCatch(NULL) return /*XXX*/ NULL; }
2608
2609 static JSValueRef Class_callAsFunction_pointerTo(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 id value(internal->value_);
2615
2616 if (!CYIsClass(value))
2617 CYThrow("non-Class object cannot be used as Type");
2618
2619 sig::Object type(class_getName(value));
2620 return CYMakeType(context, type);
2621 } CYCatch(NULL) return /*XXX*/ NULL; }
2622
2623 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2624 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2625 return CYCastJSValue(context, sel_getName(internal->value_));
2626 } CYCatch(NULL) }
2627
2628 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2629 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2630 }
2631
2632 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2633 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2634 const char *name(sel_getName(internal->value_));
2635
2636 CYPoolTry {
2637 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2638 return CYCastJSValue(context, CYJSString(context, string));
2639 } CYPoolCatch(NULL)
2640 } CYCatch(NULL) return /*XXX*/ NULL; }
2641
2642 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2643 if (count != 1)
2644 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2645
2646 CYPool pool;
2647 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2648 SEL sel(internal->value_);
2649
2650 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2651 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2652 const char *encoding(method_getTypeEncoding(method));
2653
2654 sig::Function type(false);
2655 sig::Parse(pool, &type.signature, encoding, &Structor_);
2656 return CYMakeType(context, type);
2657 } CYCatch(NULL) }
2658
2659 static JSStaticValue Selector_staticValues[2] = {
2660 {"$cyt", &Selector_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2661 {NULL, NULL, NULL, 0}
2662 };
2663
2664 static JSStaticValue Instance_staticValues[5] = {
2665 {"$cyt", &Instance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2666 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2667 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2668 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2669 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2670 {NULL, NULL, NULL, 0}
2671 };
2672
2673 static JSStaticValue FunctionInstance_staticValues[5] = {
2674 {"$cyt", &FunctionInstance_getProperty_$cyt, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2675 // XXX: this is sadly a duplicate of Instance_staticValues
2676 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2677 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2678 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2679 {NULL, NULL, NULL, 0}
2680 };
2681
2682 static JSStaticFunction Instance_staticFunctions[6] = {
2683 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2684 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2685 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2686 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2687 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2688 {NULL, NULL, 0}
2689 };
2690
2691 static JSStaticFunction Class_staticFunctions[2] = {
2692 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2693 {NULL, NULL, 0}
2694 };
2695
2696 static JSStaticFunction Internal_staticFunctions[2] = {
2697 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2698 {NULL, NULL, 0}
2699 };
2700
2701 static JSStaticFunction Selector_staticFunctions[5] = {
2702 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2703 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2704 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2705 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2706 {NULL, NULL, 0}
2707 };
2708
2709 #ifdef __APPLE__
2710 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2711 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2712 } CYObjectiveCatch }
2713 #endif
2714
2715 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2716 NSArray_ = objc_getClass("NSArray");
2717 NSBlock_ = objc_getClass("NSBlock");
2718 NSDictionary_ = objc_getClass("NSDictionary");
2719 NSNumber_ = objc_getClass("NSNumber");
2720 NSString_ = objc_getClass("NSString");
2721 Object_ = objc_getClass("Object");
2722
2723 #ifdef __APPLE__
2724 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2725
2726 // XXX: apparently, iOS now has both of these
2727 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2728 if (NSCFBoolean_ == nil)
2729 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2730
2731 NSCFType_ = objc_getClass("NSCFType");
2732
2733 NSZombie_ = objc_getClass("_NSZombie_");
2734 #else
2735 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2736 NSZombie_ = objc_getClass("NSZombie");
2737 #endif
2738
2739 JSClassDefinition definition;
2740
2741 definition = kJSClassDefinitionEmpty;
2742 definition.className = "Instance";
2743 definition.staticValues = Instance_staticValues;
2744 definition.staticFunctions = Instance_staticFunctions;
2745 definition.hasProperty = &Instance_hasProperty;
2746 definition.getProperty = &Instance_getProperty;
2747 definition.setProperty = &Instance_setProperty;
2748 definition.deleteProperty = &Instance_deleteProperty;
2749 definition.getPropertyNames = &Instance_getPropertyNames;
2750 definition.callAsConstructor = &Instance_callAsConstructor;
2751 definition.hasInstance = &Instance_hasInstance;
2752 definition.finalize = &CYFinalize;
2753 Instance::Class_ = JSClassCreate(&definition);
2754
2755 definition.className = "ArrayInstance";
2756 ArrayInstance_ = JSClassCreate(&definition);
2757
2758 definition.className = "BooleanInstance";
2759 BooleanInstance_ = JSClassCreate(&definition);
2760
2761 definition.className = "NumberInstance";
2762 NumberInstance_ = JSClassCreate(&definition);
2763
2764 definition.className = "ObjectInstance";
2765 ObjectInstance_ = JSClassCreate(&definition);
2766
2767 definition.className = "StringInstance";
2768 StringInstance_ = JSClassCreate(&definition);
2769
2770 definition.className = "FunctionInstance";
2771 definition.staticValues = FunctionInstance_staticValues;
2772 definition.callAsFunction = &FunctionInstance_callAsFunction;
2773 FunctionInstance_ = JSClassCreate(&definition);
2774
2775 definition = kJSClassDefinitionEmpty;
2776 definition.className = "Class";
2777 definition.staticFunctions = Class_staticFunctions;
2778 ClassInstance_ = JSClassCreate(&definition);
2779
2780 definition = kJSClassDefinitionEmpty;
2781 definition.className = "Internal";
2782 definition.staticFunctions = Internal_staticFunctions;
2783 definition.hasProperty = &Internal_hasProperty;
2784 definition.getProperty = &Internal_getProperty;
2785 definition.setProperty = &Internal_setProperty;
2786 definition.getPropertyNames = &Internal_getPropertyNames;
2787 definition.finalize = &CYFinalize;
2788 Internal::Class_ = JSClassCreate(&definition);
2789
2790 definition = kJSClassDefinitionEmpty;
2791 definition.className = "Message";
2792 definition.staticFunctions = cy::Functor::StaticFunctions;
2793 definition.staticValues = cy::Functor::StaticValues;
2794 definition.callAsFunction = &Message_callAsFunction;
2795 definition.finalize = &CYFinalize;
2796 Message_privateData::Class_ = JSClassCreate(&definition);
2797
2798 definition = kJSClassDefinitionEmpty;
2799 definition.className = "Messages";
2800 definition.hasProperty = &Messages_hasProperty;
2801 definition.getProperty = &Messages_getProperty;
2802 definition.setProperty = &Messages_setProperty;
2803 definition.getPropertyNames = &Messages_getPropertyNames;
2804 definition.finalize = &CYFinalize;
2805 Messages::Class_ = JSClassCreate(&definition);
2806
2807 definition = kJSClassDefinitionEmpty;
2808 definition.className = "Selector";
2809 definition.staticValues = Selector_staticValues;
2810 definition.staticFunctions = Selector_staticFunctions;
2811 definition.callAsFunction = &Selector_callAsFunction;
2812 definition.finalize = &CYFinalize;
2813 Selector_privateData::Class_ = JSClassCreate(&definition);
2814
2815 definition = kJSClassDefinitionEmpty;
2816 definition.className = "Super";
2817 definition.finalize = &CYFinalize;
2818 cy::Super::Class_ = JSClassCreate(&definition);
2819
2820 definition = kJSClassDefinitionEmpty;
2821 definition.className = "ObjectiveC::Classes";
2822 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2823 definition.getProperty = &ObjectiveC_Classes_getProperty;
2824 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2825 ObjectiveC_Classes_ = JSClassCreate(&definition);
2826
2827 definition = kJSClassDefinitionEmpty;
2828 definition.className = "ObjectiveC::Constants";
2829 definition.getProperty = &ObjectiveC_Constants_getProperty;
2830 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2831 ObjectiveC_Constants_ = JSClassCreate(&definition);
2832
2833 #ifdef __APPLE__
2834 definition = kJSClassDefinitionEmpty;
2835 definition.className = "ObjectiveC::Images";
2836 definition.getProperty = &ObjectiveC_Images_getProperty;
2837 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2838 ObjectiveC_Images_ = JSClassCreate(&definition);
2839
2840 definition = kJSClassDefinitionEmpty;
2841 definition.className = "ObjectiveC::Image::Classes";
2842 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2843 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2844 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2845 #endif
2846
2847 definition = kJSClassDefinitionEmpty;
2848 definition.className = "ObjectiveC::Protocols";
2849 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2850 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2851 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2852
2853 #ifdef __APPLE__
2854 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2855 // XXX: this is horrible; there has to be a better way to do this
2856 #ifdef __LP64__
2857 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2858 #else
2859 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2860 #endif
2861 );
2862 #endif
2863 } CYPoolCatch() }
2864
2865 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2866 JSObjectRef global(CYGetGlobalObject(context));
2867 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2868 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2869 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2870 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2871
2872 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2873 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2874
2875 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2876 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2877 CYArrayPush(context, alls, protocols);
2878
2879 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2880 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2881 CYArrayPush(context, alls, classes);
2882
2883 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2884 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2885 CYArrayPush(context, alls, constants);
2886
2887 #ifdef __APPLE__
2888 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2889 #endif
2890
2891 JSObjectRef Message(JSObjectMakeConstructor(context, Message_privateData::Class_, NULL));
2892 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_privateData::Class_, &Selector_new));
2893 JSObjectRef Super(JSObjectMakeConstructor(context, cy::Super::Class_, &Super_new));
2894
2895 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance::Class_, &Instance_new));
2896 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2897 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2898
2899 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2900 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2901 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2902 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2903 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2904
2905 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2906 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2907 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2908 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2909 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2910
2911 JSObjectRef ClassInstance(JSObjectMakeConstructor(context, ClassInstance_, NULL));
2912 JSObjectRef ClassInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ClassInstance, prototype_s)));
2913 CYSetProperty(context, cy, CYJSString("ClassInstance_prototype"), ClassInstance_prototype);
2914 // XXX: this doesn't fit the pattern of the other ones; maybe it sort of should?
2915 CYSetPrototype(context, ClassInstance_prototype, Instance_prototype);
2916
2917 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2918 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2919 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2920 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2921 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2922
2923 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2924 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2925 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2926 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2927 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2928
2929 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2930 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2931 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2932 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2933 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2934
2935 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2936 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2937 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2938 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2939 CYSetPrototype(context, StringInstance_prototype, String_prototype);
2940
2941 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2942 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2943 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
2944
2945 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2946 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
2947
2948 #ifdef __APPLE__
2949 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2950 #endif
2951
2952 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2953
2954 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2955 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2956
2957 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
2958 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
2959 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
2960 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::Object()), kJSPropertyAttributeDontEnum);
2961 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::Meta()), kJSPropertyAttributeDontEnum);
2962 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::Selector()), kJSPropertyAttributeDontEnum);
2963 } CYPoolCatch() }
2964
2965 static void *CYObjectiveC_CastSymbol(const char *name) {
2966 if (false);
2967 #ifdef __GNU_LIBOBJC__
2968 else if (strcmp(name, "object_getClass") == 0)
2969 return reinterpret_cast<void *>(&object_getClass);
2970 #endif
2971 return NULL;
2972 }
2973
2974 static CYHook CYObjectiveCHook = {
2975 &CYObjectiveC_ExecuteStart,
2976 &CYObjectiveC_ExecuteEnd,
2977 &CYObjectiveC_CallFunction,
2978 &CYObjectiveC_Initialize,
2979 &CYObjectiveC_SetupContext,
2980 &CYObjectiveC_CastSymbol,
2981 };
2982
2983 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
2984
2985 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
2986 CYSetupContext(context);
2987 } CYObjectiveCatch }
2988
2989 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
2990 CYPool pool;
2991
2992 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
2993 utf8 = CYPoolCode(pool, utf8);
2994
2995 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
2996 size_t bytes(utf16.size * sizeof(uint16_t));
2997 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
2998 memcpy(copy, utf16.data, bytes);
2999
3000 *data = copy;
3001 *size = utf16.size;
3002 } catch (const CYException &exception) {
3003 CYPool pool;
3004 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];
3005 } }