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