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