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