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