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