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