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