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