]> git.saurik.com Git - cycript.git/blob - ObjectiveC/Library.mm
Rely on (automatic) weak symbols instead of dlsym.
[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, bool permanent) {
429 Instance::Flags flags;
430
431 if (permanent)
432 flags = Instance::Permanent;
433 else {
434 flags = Instance::None;
435 object = [object retain];
436 }
437
438 return Instance::Make(context, object, flags);
439 }
440
441 @interface NSMethodSignature (Cycript)
442 - (NSString *) _typeString;
443 @end
444
445 @interface NSObject (Cycript)
446
447 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
448 - (JSType) cy$JSType;
449
450 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
451 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
452
453 - (bool) cy$hasProperty:(NSString *)name;
454 - (NSObject *) cy$getProperty:(NSString *)name;
455 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
456 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
457 - (bool) cy$deleteProperty:(NSString *)name;
458 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
459
460 + (bool) cy$hasImplicitProperties;
461
462 @end
463
464 @protocol Cycript
465 - (id) cy$box;
466 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
467 @end
468
469 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
470 NSString *string;
471
472 if (value == nil)
473 string = @"nil";
474 else {
475 Class _class(object_getClass(value));
476 SEL sel(@selector(cy$toCYON:inSet:));
477
478 if (class_isMetaClass(_class)) {
479 const char *name(class_getName(value));
480 if (class_isMetaClass(value))
481 string = [NSString stringWithFormat:@"object_getClass(%s)", name];
482 else
483 string = [NSString stringWithUTF8String:name];
484 } else if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
485 string = reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
486 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
487 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
488 string = [value cy$toCYON:objective inSet:objects];
489 else goto fail;
490 } else fail: {
491 if (false);
492 #ifdef __APPLE__
493 else if (_class == NSZombie_)
494 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
495 #endif
496 else
497 string = [NSString stringWithFormat:@"%@", value];
498 }
499
500 // XXX: frowny pants
501 if (string == nil)
502 string = @"undefined";
503 }
504
505 return string;
506 }
507
508 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
509 if (objects != NULL)
510 return CYCastNSCYON(value, objective, *objects);
511 else {
512 std::set<void *> objects;
513 return CYCastNSCYON(value, objective, objects);
514 }
515 }
516
517 #ifdef __APPLE__
518 struct PropertyAttributes {
519 CYPool pool_;
520
521 const char *name;
522
523 const char *variable;
524
525 const char *getter_;
526 const char *setter_;
527
528 bool readonly;
529 bool copy;
530 bool retain;
531 bool nonatomic;
532 bool dynamic;
533 bool weak;
534 bool garbage;
535
536 PropertyAttributes(objc_property_t property) :
537 variable(NULL),
538 getter_(NULL),
539 setter_(NULL),
540 readonly(false),
541 copy(false),
542 retain(false),
543 nonatomic(false),
544 dynamic(false),
545 weak(false),
546 garbage(false)
547 {
548 name = property_getName(property);
549 const char *attributes(property_getAttributes(property));
550
551 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
552 if ((next = strchr(token, ',')) != NULL)
553 *next++ = '\0';
554 switch (*token) {
555 case 'R': readonly = true; break;
556 case 'C': copy = true; break;
557 case '&': retain = true; break;
558 case 'N': nonatomic = true; break;
559 case 'G': getter_ = token + 1; break;
560 case 'S': setter_ = token + 1; break;
561 case 'V': variable = token + 1; break;
562 }
563 }
564
565 /*if (variable == NULL) {
566 variable = property_getName(property);
567 size_t size(strlen(variable));
568 char *name(new(pool_) char[size + 2]);
569 name[0] = '_';
570 memcpy(name + 1, variable, size);
571 name[size + 1] = '\0';
572 variable = name;
573 }*/
574 }
575
576 const char *Getter() {
577 if (getter_ == NULL)
578 getter_ = pool_.strdup(name);
579 return getter_;
580 }
581
582 const char *Setter() {
583 if (setter_ == NULL && !readonly) {
584 size_t length(strlen(name));
585
586 char *temp(new(pool_) char[length + 5]);
587 temp[0] = 's';
588 temp[1] = 'e';
589 temp[2] = 't';
590
591 if (length != 0) {
592 temp[3] = toupper(name[0]);
593 memcpy(temp + 4, name + 1, length - 1);
594 }
595
596 temp[length + 3] = ':';
597 temp[length + 4] = '\0';
598 setter_ = temp;
599 }
600
601 return setter_;
602 }
603
604 };
605 #endif
606
607 @interface CYWebUndefined : NSObject {
608 }
609
610 + (CYWebUndefined *) undefined;
611
612 @end
613
614 @implementation CYWebUndefined
615
616 + (CYWebUndefined *) undefined {
617 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
618 return instance_;
619 }
620
621 @end
622
623 #define WebUndefined CYWebUndefined
624
625 /* Bridge: CYJSObject {{{ */
626 @interface CYJSObject : NSMutableDictionary {
627 JSObjectRef object_;
628 JSGlobalContextRef context_;
629 }
630
631 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
632
633 - (NSUInteger) count;
634 - (id) objectForKey:(id)key;
635 - (NSEnumerator *) keyEnumerator;
636 - (void) setObject:(id)object forKey:(id)key;
637 - (void) removeObjectForKey:(id)key;
638
639 @end
640 /* }}} */
641 /* Bridge: CYJSArray {{{ */
642 @interface CYJSArray : NSMutableArray {
643 JSObjectRef object_;
644 JSGlobalContextRef context_;
645 }
646
647 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
648
649 - (NSUInteger) count;
650 - (id) objectAtIndex:(NSUInteger)index;
651
652 - (void) addObject:(id)anObject;
653 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
654 - (void) removeLastObject;
655 - (void) removeObjectAtIndex:(NSUInteger)index;
656 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
657
658 @end
659 /* }}} */
660
661 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
662 return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
663 }
664
665 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
666 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
667 }
668
669 struct CYBlockDescriptor {
670 struct {
671 BlockDescriptor1 one_;
672 BlockDescriptor2 two_;
673 BlockDescriptor3 three_;
674 } d_;
675
676 Closure_privateData *internal_;
677 };
678
679 void CYDisposeBlock(BlockLiteral *literal) {
680 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
681 }
682
683 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
684 JSObjectRef _this(CYCastJSObject(context, values[0]));
685 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
686 }
687
688 static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
689 CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
690 }
691
692 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
693 _assert(__NSMallocBlock__ != Nil);
694 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
695
696 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
697 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
698
699 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
700 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
701
702 literal->isa = __NSMallocBlock__;
703 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
704 literal->reserved = 0;
705 literal->descriptor = descriptor;
706
707 descriptor->d_.one_.size = sizeof(descriptor->d_);
708 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
709 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
710
711 return reinterpret_cast<NSBlock *>(literal);
712 }
713
714 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
715 if (CYJSValueIsNSObject(context, object)) {
716 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
717 return internal->GetValue();
718 }
719
720 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
721 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
722 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
723 }
724
725 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
726 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
727 }
728
729 #ifndef __APPLE__
730 @interface NSBoolNumber : NSNumber {
731 }
732 @end
733 #endif
734
735 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
736 id object;
737 bool copy;
738
739 switch (JSType type = JSValueGetType(context, value)) {
740 case kJSTypeUndefined:
741 object = [WebUndefined undefined];
742 copy = false;
743 break;
744
745 case kJSTypeNull:
746 return NULL;
747 break;
748
749 case kJSTypeBoolean:
750 #ifdef __APPLE__
751 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
752 copy = false;
753 #else
754 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
755 copy = true;
756 #endif
757 break;
758
759 case kJSTypeNumber:
760 object = CYCopyNSNumber(context, value);
761 copy = true;
762 break;
763
764 case kJSTypeString:
765 object = CYCopyNSString(context, value);
766 copy = true;
767 break;
768
769 case kJSTypeObject:
770 // XXX: this might could be more efficient
771 object = CYCastNSObject(pool, context, (JSObjectRef) value);
772 copy = false;
773 break;
774
775 default:
776 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
777 break;
778 }
779
780 if (cast != copy)
781 return object;
782 else if (copy)
783 return CYPoolRelease(pool, object);
784 else
785 return [object retain];
786 }
787
788 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
789 return CYNSObject(pool, context, value, true);
790 }
791
792 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
793 return CYNSObject(&pool, context, value, false);
794 }
795
796 /* Bridge: NSArray {{{ */
797 @implementation NSArray (Cycript)
798
799 - (id) cy$box {
800 return [[self mutableCopy] autorelease];
801 }
802
803 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
804 _oassert(objects.insert(self).second);
805
806 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
807 [json appendString:@"@["];
808
809 bool comma(false);
810 #ifdef __APPLE__
811 for (id object in self) {
812 #else
813 for (size_t index(0), count([self count]); index != count; ++index) {
814 id object([self objectAtIndex:index]);
815 #endif
816 if (comma)
817 [json appendString:@","];
818 else
819 comma = true;
820 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
821 [json appendString:CYCastNSCYON(object, true, objects)];
822 else {
823 [json appendString:@","];
824 comma = false;
825 }
826 }
827
828 [json appendString:@"]"];
829 return json;
830 }
831
832 - (bool) cy$hasProperty:(NSString *)name {
833 if ([name isEqualToString:@"length"])
834 return true;
835
836 size_t index(CYGetIndex(name));
837 if (index == _not(size_t) || index >= [self count])
838 return [super cy$hasProperty:name];
839 else
840 return true;
841 }
842
843 - (NSObject *) cy$getProperty:(NSString *)name {
844 size_t index(CYGetIndex(name));
845 if (index == _not(size_t) || index >= [self count])
846 return [super cy$getProperty:name];
847 else
848 return [self objectAtIndex:index];
849 }
850
851 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
852 CYObjectiveTry_ {
853 if ([name isEqualToString:@"length"])
854 return CYCastJSValue(context, [self count]);
855 } CYObjectiveCatch
856
857 return [super cy$getProperty:name inContext:context];
858 }
859
860 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
861 [super cy$getPropertyNames:names inContext:context];
862
863 for (size_t index(0), count([self count]); index != count; ++index) {
864 id object([self objectAtIndex:index]);
865 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
866 char name[32];
867 sprintf(name, "%zu", index);
868 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
869 }
870 }
871 }
872
873 + (bool) cy$hasImplicitProperties {
874 return false;
875 }
876
877 @end
878 /* }}} */
879 /* Bridge: NSBlock {{{ */
880 #ifdef __APPLE__
881 @interface NSBlock
882 - (void) invoke;
883 @end
884 #endif
885 /* }}} */
886 /* Bridge: NSBoolNumber {{{ */
887 #ifndef __APPLE__
888 @implementation NSBoolNumber (Cycript)
889
890 - (JSType) cy$JSType {
891 return kJSTypeBoolean;
892 }
893
894 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
895 NSString *value([self boolValue] ? @"true" : @"false");
896 return objective ? value : [NSString stringWithFormat:@"@%@", value];
897 }
898
899 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
900 return CYCastJSValue(context, (bool) [self boolValue]);
901 } CYObjectiveCatch }
902
903 @end
904 #endif
905 /* }}} */
906 /* Bridge: NSDictionary {{{ */
907 @implementation NSDictionary (Cycript)
908
909 - (id) cy$box {
910 return [[self mutableCopy] autorelease];
911 }
912
913 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
914 _oassert(objects.insert(self).second);
915
916 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
917 [json appendString:@"@{"];
918
919 bool comma(false);
920 #ifdef __APPLE__
921 for (NSObject *key in self) {
922 #else
923 NSEnumerator *keys([self keyEnumerator]);
924 while (NSObject *key = [keys nextObject]) {
925 #endif
926 if (comma)
927 [json appendString:@","];
928 else
929 comma = true;
930 [json appendString:CYCastNSCYON(key, true, objects)];
931 [json appendString:@":"];
932 NSObject *object([self objectForKey:key]);
933 [json appendString:CYCastNSCYON(object, true, objects)];
934 }
935
936 [json appendString:@"}"];
937 return json;
938 }
939
940 - (bool) cy$hasProperty:(NSString *)name {
941 return [self objectForKey:name] != nil;
942 }
943
944 - (NSObject *) cy$getProperty:(NSString *)name {
945 return [self objectForKey:name];
946 }
947
948 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
949 [super cy$getPropertyNames:names inContext:context];
950
951 #ifdef __APPLE__
952 for (NSObject *key in self) {
953 #else
954 NSEnumerator *keys([self keyEnumerator]);
955 while (NSObject *key = [keys nextObject]) {
956 #endif
957 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
958 }
959 }
960
961 + (bool) cy$hasImplicitProperties {
962 return false;
963 }
964
965 @end
966 /* }}} */
967 /* Bridge: NSMutableArray {{{ */
968 @implementation NSMutableArray (Cycript)
969
970 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
971 if ([name isEqualToString:@"length"]) {
972 // XXX: is this not intelligent?
973 NSNumber *number(reinterpret_cast<NSNumber *>(value));
974 #ifdef __APPLE__
975 NSUInteger size([number unsignedIntegerValue]);
976 #else
977 NSUInteger size([number unsignedIntValue]);
978 #endif
979 NSUInteger count([self count]);
980 if (size < count)
981 [self removeObjectsInRange:NSMakeRange(size, count - size)];
982 else if (size != count) {
983 WebUndefined *undefined([WebUndefined undefined]);
984 for (size_t i(count); i != size; ++i)
985 [self addObject:undefined];
986 }
987 return true;
988 }
989
990 size_t index(CYGetIndex(name));
991 if (index == _not(size_t))
992 return [super cy$setProperty:name to:value];
993
994 id object(value ?: [NSNull null]);
995
996 size_t count([self count]);
997 if (index < count)
998 [self replaceObjectAtIndex:index withObject:object];
999 else {
1000 if (index != count) {
1001 WebUndefined *undefined([WebUndefined undefined]);
1002 for (size_t i(count); i != index; ++i)
1003 [self addObject:undefined];
1004 }
1005
1006 [self addObject:object];
1007 }
1008
1009 return true;
1010 }
1011
1012 - (bool) cy$deleteProperty:(NSString *)name {
1013 size_t index(CYGetIndex(name));
1014 if (index == _not(size_t) || index >= [self count])
1015 return [super cy$deleteProperty:name];
1016 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1017 return true;
1018 }
1019
1020 @end
1021 /* }}} */
1022 /* Bridge: NSMutableDictionary {{{ */
1023 @implementation NSMutableDictionary (Cycript)
1024
1025 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1026 [self setObject:(value ?: [NSNull null]) forKey:name];
1027 return true;
1028 }
1029
1030 - (bool) cy$deleteProperty:(NSString *)name {
1031 if ([self objectForKey:name] == nil)
1032 return false;
1033 else {
1034 [self removeObjectForKey:name];
1035 return true;
1036 }
1037 }
1038
1039 @end
1040 /* }}} */
1041 /* Bridge: NSNumber {{{ */
1042 @implementation NSNumber (Cycript)
1043
1044 - (JSType) cy$JSType {
1045 #ifdef __APPLE__
1046 // XXX: this just seems stupid
1047 if ([self class] == NSCFBoolean_)
1048 return kJSTypeBoolean;
1049 #endif
1050 return kJSTypeNumber;
1051 }
1052
1053 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1054 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1055 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1056 }
1057
1058 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1059 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1060 } CYObjectiveCatch }
1061
1062 @end
1063 /* }}} */
1064 /* Bridge: NSNull {{{ */
1065 @implementation NSNull (Cycript)
1066
1067 - (JSType) cy$JSType {
1068 return kJSTypeNull;
1069 }
1070
1071 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1072 NSString *value(@"null");
1073 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1074 }
1075
1076 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1077 return CYJSNull(context);
1078 } CYObjectiveCatch }
1079
1080 @end
1081 /* }}} */
1082 /* Bridge: NSObject {{{ */
1083 @implementation NSObject (Cycript)
1084
1085 - (id) cy$box {
1086 return self;
1087 }
1088
1089 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1090 return [self cy$valueOfInContext:context];
1091 }
1092
1093 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1094 return NULL;
1095 } CYObjectiveCatch }
1096
1097 - (JSType) cy$JSType {
1098 return kJSTypeObject;
1099 }
1100
1101 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1102 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1103 }
1104
1105 - (bool) cy$hasProperty:(NSString *)name {
1106 return false;
1107 }
1108
1109 - (NSObject *) cy$getProperty:(NSString *)name {
1110 return nil;
1111 }
1112
1113 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1114 if (NSObject *value = [self cy$getProperty:name])
1115 return CYCastJSValue(context, value);
1116 return NULL;
1117 } CYObjectiveCatch }
1118
1119 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1120 return false;
1121 }
1122
1123 - (bool) cy$deleteProperty:(NSString *)name {
1124 return false;
1125 }
1126
1127 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1128 }
1129
1130 + (bool) cy$hasImplicitProperties {
1131 return true;
1132 }
1133
1134 @end
1135 /* }}} */
1136 /* Bridge: NSProxy {{{ */
1137 @implementation NSProxy (Cycript)
1138
1139 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1140 return [[self description] cy$toCYON:objective inSet:objects];
1141 }
1142
1143 @end
1144 /* }}} */
1145 /* Bridge: NSSet {{{ */
1146 @implementation NSSet (Cycript)
1147
1148 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1149 _oassert(objects.insert(self).second);
1150
1151 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1152 [json appendString:@"[NSSet setWithArray:"];
1153 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1154 [json appendString:@"]]"];
1155 return json;
1156 }
1157
1158 @end
1159 /* }}} */
1160 /* Bridge: NSString {{{ */
1161 @implementation NSString (Cycript)
1162
1163 - (id) cy$box {
1164 return [[self copy] autorelease];
1165 }
1166
1167 - (JSType) cy$JSType {
1168 return kJSTypeString;
1169 }
1170
1171 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1172 std::ostringstream str;
1173 if (!objective)
1174 str << '@';
1175 CYUTF8String string(CYCastUTF8String(self));
1176 CYStringify(str, string.data, string.size);
1177 std::string value(str.str());
1178 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1179 }
1180
1181 - (bool) cy$hasProperty:(NSString *)name {
1182 size_t index(CYGetIndex(name));
1183 if (index == _not(size_t) || index >= [self length])
1184 return [super cy$hasProperty:name];
1185 else
1186 return true;
1187 }
1188
1189 - (NSObject *) cy$getProperty:(NSString *)name {
1190 size_t index(CYGetIndex(name));
1191 if (index == _not(size_t) || index >= [self length])
1192 return [super cy$getProperty:name];
1193 else
1194 return [self substringWithRange:NSMakeRange(index, 1)];
1195 }
1196
1197 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1198 [super cy$getPropertyNames:names inContext:context];
1199
1200 for (size_t index(0), length([self length]); index != length; ++index) {
1201 char name[32];
1202 sprintf(name, "%zu", index);
1203 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1204 }
1205 }
1206
1207 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1208 return CYCastJSValue(context, CYJSString(context, self));
1209 } CYObjectiveCatch }
1210
1211 @end
1212 /* }}} */
1213 /* Bridge: WebUndefined {{{ */
1214 @implementation WebUndefined (Cycript)
1215
1216 - (JSType) cy$JSType {
1217 return kJSTypeUndefined;
1218 }
1219
1220 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1221 NSString *value(@"undefined");
1222 return value; // XXX: maybe use the below code, adding @undefined?
1223 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1224 }
1225
1226 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1227 return CYJSUndefined(context);
1228 } CYObjectiveCatch }
1229
1230 @end
1231 /* }}} */
1232
1233 static bool CYIsClass(id self) {
1234 #ifdef __APPLE__
1235 return class_isMetaClass(object_getClass(self));
1236 #else
1237 return GSObjCIsClass(self);
1238 #endif
1239 }
1240
1241 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1242 id self(CYCastNSObject(&pool, context, value));
1243 if (CYIsClass(self))
1244 return (Class) self;
1245 throw CYJSError(context, "got something that is not a Class");
1246 return NULL;
1247 }
1248
1249 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1250 CYPool pool;
1251 size_t size(JSPropertyNameArrayGetCount(names));
1252 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1253 for (size_t index(0); index != size; ++index)
1254 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1255 return array;
1256 }
1257
1258 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1259 if (value == nil)
1260 return CYJSNull(context);
1261 else
1262 return CYMakeInstance(context, value, false);
1263 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1264
1265 @implementation CYJSObject
1266
1267 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1268 if ((self = [super init]) != nil) {
1269 object_ = object;
1270 context_ = CYGetJSContext(context);
1271 JSGlobalContextRetain(context_);
1272 JSValueProtect(context_, object_);
1273 } return self;
1274 } CYObjectiveCatch }
1275
1276 - (void) dealloc { CYObjectiveTry {
1277 JSValueUnprotect(context_, object_);
1278 JSGlobalContextRelease(context_);
1279 [super dealloc];
1280 } CYObjectiveCatch }
1281
1282 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1283 CYPool pool;
1284 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1285 if (cyon == NULL)
1286 return [super cy$toCYON:objective inSet:objects];
1287 else
1288 return [NSString stringWithUTF8String:cyon];
1289 } CYObjectiveCatch }
1290
1291 - (NSUInteger) count { CYObjectiveTry {
1292 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1293 size_t size(JSPropertyNameArrayGetCount(names));
1294 JSPropertyNameArrayRelease(names);
1295 return size;
1296 } CYObjectiveCatch }
1297
1298 - (id) objectForKey:(id)key { CYObjectiveTry {
1299 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1300 if (JSValueIsUndefined(context, value))
1301 return nil;
1302 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1303 } CYObjectiveCatch }
1304
1305 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1306 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1307 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1308 JSPropertyNameArrayRelease(names);
1309 return enumerator;
1310 } CYObjectiveCatch }
1311
1312 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1313 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1314 } CYObjectiveCatch }
1315
1316 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1317 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1318 } CYObjectiveCatch }
1319
1320 @end
1321
1322 @implementation CYJSArray
1323
1324 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1325 CYPool pool;
1326 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1327 } CYObjectiveCatch }
1328
1329 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1330 if ((self = [super init]) != nil) {
1331 object_ = object;
1332 context_ = CYGetJSContext(context);
1333 JSGlobalContextRetain(context_);
1334 JSValueProtect(context_, object_);
1335 } return self;
1336 } CYObjectiveCatch }
1337
1338 - (void) dealloc { CYObjectiveTry {
1339 JSValueUnprotect(context_, object_);
1340 JSGlobalContextRelease(context_);
1341 [super dealloc];
1342 } CYObjectiveCatch }
1343
1344 - (NSUInteger) count { CYObjectiveTry {
1345 return CYArrayLength(context, object_);
1346 } CYObjectiveCatch }
1347
1348 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1349 size_t bounds([self count]);
1350 if (index >= bounds)
1351 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1352 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1353 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1354 } CYObjectiveCatch }
1355
1356 - (void) addObject:(id)object { CYObjectiveTry {
1357 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1358 } CYObjectiveCatch }
1359
1360 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1361 size_t bounds([self count] + 1);
1362 if (index >= bounds)
1363 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1364 JSValueRef arguments[3];
1365 arguments[0] = CYCastJSValue(context, index);
1366 arguments[1] = CYCastJSValue(context, 0);
1367 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1368 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1369 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1370 } CYObjectiveCatch }
1371
1372 - (void) removeLastObject { CYObjectiveTry {
1373 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1374 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1375 } CYObjectiveCatch }
1376
1377 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1378 size_t bounds([self count]);
1379 if (index >= bounds)
1380 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1381 JSValueRef arguments[2];
1382 arguments[0] = CYCastJSValue(context, index);
1383 arguments[1] = CYCastJSValue(context, 1);
1384 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1385 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1386 } CYObjectiveCatch }
1387
1388 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1389 size_t bounds([self count]);
1390 if (index >= bounds)
1391 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1392 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1393 } CYObjectiveCatch }
1394
1395 @end
1396
1397 // XXX: inherit from or replace with CYJSObject
1398 @interface CYInternal : NSObject {
1399 JSGlobalContextRef context_;
1400 JSObjectRef object_;
1401 }
1402
1403 @end
1404
1405 @implementation CYInternal
1406
1407 - (void) dealloc { CYObjectiveTry {
1408 JSValueUnprotect(context_, object_);
1409 JSGlobalContextRelease(context_);
1410 [super dealloc];
1411 } CYObjectiveCatch }
1412
1413 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1414 if ((self = [super init]) != nil) {
1415 context_ = CYGetJSContext(context);
1416 JSGlobalContextRetain(context_);
1417 } return self;
1418 } CYObjectiveCatch }
1419
1420 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1421 if (object_ == NULL)
1422 return false;
1423
1424 return JSObjectHasProperty(context, object_, name);
1425 }
1426
1427 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1428 if (object_ == NULL)
1429 return NULL;
1430
1431 return CYGetProperty(context, object_, name);
1432 }
1433
1434 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1435 @synchronized (self) {
1436 if (object_ == NULL) {
1437 object_ = JSObjectMake(context, NULL, NULL);
1438 JSValueProtect(context, object_);
1439 }
1440 }
1441
1442 CYSetProperty(context, object_, name, value);
1443 }
1444
1445 + (CYInternal *) get:(id)object {
1446 if (&objc_getAssociatedObject == NULL)
1447 return nil;
1448
1449 @synchronized (object) {
1450 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1451 return internal;
1452 }
1453
1454 return nil;
1455 }
1456
1457 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1458 if (&objc_getAssociatedObject == NULL)
1459 return nil;
1460
1461 @synchronized (object) {
1462 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1463 return internal;
1464
1465 if (&objc_setAssociatedObject == NULL)
1466 return nil;
1467
1468 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1469 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1470 return internal;
1471 }
1472
1473 return nil;
1474 }
1475
1476 @end
1477
1478 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1479 Selector_privateData *internal(new Selector_privateData(sel));
1480 return JSObjectMake(context, Selector_, internal);
1481 }
1482
1483 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1484 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1485 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1486 return reinterpret_cast<SEL>(internal->value_);
1487 } else {
1488 CYPool pool;
1489 return sel_registerName(CYPoolCString(pool, context, value));
1490 }
1491 }
1492
1493 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1494 return (void *) [[NSAutoreleasePool alloc] init];
1495 } CYSadCatch(NULL) }
1496
1497 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1498 return [(NSAutoreleasePool *) handle release];
1499 } CYSadCatch() }
1500
1501 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1502 if (name == "nil")
1503 return Instance::Make(context, nil);
1504 if (Class _class = objc_getClass(name.data))
1505 return CYMakeInstance(context, _class, true);
1506 if (Protocol *protocol = objc_getProtocol(name.data))
1507 return CYMakeInstance(context, protocol, true);
1508 return NULL;
1509 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1510
1511 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1512 ffi_call(cif, function, value, values);
1513 } CYSadCatch() }
1514
1515 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, sig::Signature *signature) {
1516 if (JSValueIsNull(context, value))
1517 return nil;
1518 JSObjectRef object(CYCastJSObject(context, value));
1519
1520 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1521 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1522
1523 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1524 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1525 return nil;
1526 }
1527
1528 _assert(JSObjectIsFunction(context, object));
1529
1530 _assert(signature != NULL);
1531 _assert(signature->count != 0);
1532
1533 sig::Signature modified;
1534 modified.count = signature->count + 1;
1535 modified.elements = new(pool) sig::Element[modified.count];
1536
1537 modified.elements[0] = signature->elements[0];
1538 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1539
1540 modified.elements[1].name = NULL;
1541 modified.elements[1].type = new(pool) sig::Type();
1542 modified.elements[1].offset = _not(size_t);
1543
1544 memset(modified.elements[1].type, 0, sizeof(sig::Type));
1545 modified.elements[1].type->primitive = sig::object_P;
1546
1547 return CYMakeBlock(context, object, modified);
1548 }
1549
1550 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1551 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1552
1553 switch (type->primitive) {
1554 case sig::block_P:
1555 // XXX: this function might not handle the idea of a null pool
1556 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &type->data.signature);
1557 break;
1558
1559 case sig::object_P:
1560 case sig::typename_P:
1561 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1562 break;
1563
1564 case sig::selector_P:
1565 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1566 break;
1567
1568 default:
1569 return false;
1570 }
1571
1572 return true;
1573 } CYSadCatch(false) }
1574
1575 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1576 switch (type->primitive) {
1577 // XXX: do something epic about blocks
1578 case sig::block_P:
1579 case sig::object_P:
1580 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1581 JSValueRef value(CYCastJSValue(context, object));
1582 if (initialize)
1583 [object release];
1584 return value;
1585 } else goto null;
1586
1587 case sig::typename_P:
1588 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1589
1590 case sig::selector_P:
1591 if (SEL sel = *reinterpret_cast<SEL *>(data))
1592 return CYMakeSelector(context, sel);
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(Instance::Make(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 if (encoding[0] == 'b') {
2091 unsigned length, shift;
2092 CYBitField(length, shift, self, ivar, encoding, offset);
2093 _assert(shift + length <= sizeof(uintptr_t) * 8);
2094 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2095 uintptr_t mask((1 << length) - 1);
2096 return CYCastJSValue(context, (field >> shift) & mask);
2097 } else {
2098 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2099 return CYFromFFI(context, type->type_, type->GetFFI(), data);
2100 }
2101 }
2102
2103 return NULL;
2104 } CYCatch(NULL) }
2105
2106 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2107 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2108 CYPool pool;
2109
2110 id self(internal->GetValue());
2111 const char *name(CYPoolCString(pool, context, property));
2112
2113 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2114 ptrdiff_t offset(ivar_getOffset(ivar));
2115 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2116
2117 const char *encoding(ivar_getTypeEncoding(ivar));
2118 _assert(encoding != NULL);
2119 if (encoding[0] == 'b') {
2120 unsigned length, shift;
2121 CYBitField(length, shift, self, ivar, encoding, offset);
2122 _assert(shift + length <= sizeof(uintptr_t) * 8);
2123 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2124 uintptr_t mask((1 << length) - 1);
2125 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2126 } else {
2127 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2128 CYPoolFFI(&pool, context, type->type_, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2129 return true;
2130 }
2131 }
2132
2133 return false;
2134 } CYCatch(false) }
2135
2136 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2137 if (Class super = class_getSuperclass(_class))
2138 Internal_getPropertyNames_(super, names);
2139
2140 #if OBJC_API_VERSION >= 2
2141 unsigned int size;
2142 objc_ivar **data(class_copyIvarList(_class, &size));
2143 for (size_t i(0); i != size; ++i)
2144 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2145 free(data);
2146 #else
2147 if (objc_ivar_list *ivars = _class->ivars)
2148 for (int i(0); i != ivars->ivar_count; ++i)
2149 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2150 #endif
2151 }
2152
2153 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2154 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2155 CYPool pool;
2156
2157 id self(internal->GetValue());
2158 Class _class(object_getClass(self));
2159
2160 Internal_getPropertyNames_(_class, names);
2161 }
2162
2163 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2164 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2165 return internal->GetOwner();
2166 } CYCatch(NULL) }
2167
2168 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2169 CYPool pool;
2170 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2171 }
2172
2173 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2174 CYPool pool;
2175 NSString *name(CYCastNSString(&pool, context, property));
2176 if (Class _class = NSClassFromString(name))
2177 return CYMakeInstance(context, _class, true);
2178 return NULL;
2179 } CYCatch(NULL) }
2180
2181 #ifdef __APPLE__
2182 static Class *CYCopyClassList(size_t &size) {
2183 size = objc_getClassList(NULL, 0);
2184 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2185
2186 for (;;) {
2187 size_t writ(objc_getClassList(data, size));
2188 if (writ <= size) {
2189 size = writ;
2190 return data;
2191 }
2192
2193 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2194 if (copy == NULL) {
2195 free(data);
2196 return NULL;
2197 }
2198
2199 data = copy;
2200 size = writ;
2201 }
2202 }
2203 #endif
2204
2205 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2206 #ifdef __APPLE__
2207 size_t size;
2208 if (Class *data = CYCopyClassList(size)) {
2209 for (size_t i(0); i != size; ++i)
2210 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2211 free(data);
2212 }
2213 #else
2214 void *state(NULL);
2215 while (Class _class = objc_next_class(&state))
2216 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2217 #endif
2218 }
2219
2220 #if OBJC_API_VERSION >= 2
2221 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2222 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2223
2224 CYPool pool;
2225 const char *name(CYPoolCString(pool, context, property));
2226 unsigned int size;
2227 const char **data(objc_copyClassNamesForImage(internal, &size));
2228 JSValueRef value;
2229 for (size_t i(0); i != size; ++i)
2230 if (strcmp(name, data[i]) == 0) {
2231 if (Class _class = objc_getClass(name)) {
2232 value = CYMakeInstance(context, _class, true);
2233 goto free;
2234 } else
2235 break;
2236 }
2237 value = NULL;
2238 free:
2239 free(data);
2240 return value;
2241 } CYCatch(NULL) }
2242
2243 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2244 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2245 unsigned int size;
2246 const char **data(objc_copyClassNamesForImage(internal, &size));
2247 for (size_t i(0); i != size; ++i)
2248 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2249 free(data);
2250 }
2251
2252 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2253 CYPool pool;
2254 const char *name(CYPoolCString(pool, context, property));
2255 unsigned int size;
2256 const char **data(objc_copyImageNames(&size));
2257 for (size_t i(0); i != size; ++i)
2258 if (strcmp(name, data[i]) == 0) {
2259 name = data[i];
2260 goto free;
2261 }
2262 name = NULL;
2263 free:
2264 free(data);
2265 if (name == NULL)
2266 return NULL;
2267 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2268 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2269 return value;
2270 } CYCatch(NULL) }
2271
2272 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2273 unsigned int size;
2274 const char **data(objc_copyImageNames(&size));
2275 for (size_t i(0); i != size; ++i)
2276 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2277 free(data);
2278 }
2279 #endif
2280
2281 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2282 CYPool pool;
2283 const char *name(CYPoolCString(pool, context, property));
2284 if (Protocol *protocol = objc_getProtocol(name))
2285 return CYMakeInstance(context, protocol, true);
2286 return NULL;
2287 } CYCatch(NULL) }
2288
2289 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2290 #if OBJC_API_VERSION >= 2
2291 unsigned int size;
2292 Protocol **data(objc_copyProtocolList(&size));
2293 for (size_t i(0); i != size; ++i)
2294 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2295 free(data);
2296 #else
2297 // XXX: fix this!
2298 #endif
2299 }
2300
2301 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2302 CYPool pool;
2303 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2304 if (name == "nil")
2305 return Instance::Make(context, nil);
2306 return NULL;
2307 } CYCatch(NULL) }
2308
2309 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2310 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2311 }
2312
2313 #ifdef __APPLE__
2314 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2315 *data = reinterpret_cast<void *>(address);
2316 return KERN_SUCCESS;
2317 }
2318
2319 struct CYChoice {
2320 std::set<Class> query_;
2321 JSContextRef context_;
2322 JSObjectRef results_;
2323 };
2324
2325 struct CYObjectStruct {
2326 Class isa_;
2327 };
2328
2329 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2330 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2331 JSContextRef context(choice->context_);
2332
2333 for (unsigned i(0); i != count; ++i) {
2334 vm_range_t &range(ranges[i]);
2335 void *data(reinterpret_cast<void *>(range.address));
2336 size_t size(range.size);
2337
2338 if (size < sizeof(CYObjectStruct))
2339 continue;
2340
2341 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2342 #ifdef __arm64__
2343 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2344 #else
2345 Class isa(reinterpret_cast<Class>(pointers[0]));
2346 #endif
2347
2348 std::set<Class>::const_iterator result(choice->query_.find(isa));
2349 if (result == choice->query_.end())
2350 continue;
2351
2352 size_t needed(class_getInstanceSize(*result));
2353 // XXX: if (size < needed)
2354
2355 size_t boundary(496);
2356 #ifdef __LP64__
2357 boundary *= 2;
2358 #endif
2359 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2360 continue;
2361 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2362 }
2363 }
2364
2365 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2366 if (count != 1)
2367 throw CYJSError(context, "choose() takes a class argument");
2368
2369 CYGarbageCollect(context);
2370
2371 CYPool pool;
2372 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2373
2374 vm_address_t *zones(NULL);
2375 unsigned size(0);
2376 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2377 _assert(error == KERN_SUCCESS);
2378
2379 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2380 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2381
2382 CYChoice choice;
2383 choice.context_ = context;
2384 choice.results_ = results;
2385
2386 size_t number;
2387 Class *classes(CYCopyClassList(number));
2388 _assert(classes != NULL);
2389
2390 for (size_t i(0); i != number; ++i)
2391 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2392 if (current == _class) {
2393 choice.query_.insert(classes[i]);
2394 break;
2395 }
2396
2397 free(classes);
2398
2399 for (unsigned i(0); i != size; ++i) {
2400 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2401 if (zone == NULL || zone->introspect == NULL)
2402 continue;
2403
2404 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2405 }
2406
2407 return results;
2408 } CYCatch(NULL) }
2409 #endif
2410
2411 #ifdef __APPLE__
2412 #if defined(__i386__) || defined(__x86_64__)
2413 #define OBJC_MAX_STRUCT_BY_VALUE 8
2414 static int struct_forward_array[] = {
2415 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2416 #elif defined(__arm__)
2417 #define OBJC_MAX_STRUCT_BY_VALUE 1
2418 static int struct_forward_array[] = {
2419 0, 0 };
2420 #elif defined(__arm64__)
2421 #define CY_NO_STRET
2422 #else
2423 #error missing objc-runtime-info
2424 #endif
2425
2426 #ifndef CY_NO_STRET
2427 static bool stret(ffi_type *ffi_type) {
2428 return ffi_type->type == FFI_TYPE_STRUCT && (
2429 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2430 struct_forward_array[ffi_type->size] != 0
2431 );
2432 }
2433 #endif
2434 #endif
2435
2436 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2437 const char *type;
2438
2439 if (_class == NULL)
2440 _class = object_getClass(self);
2441
2442 IMP imp;
2443
2444 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2445 imp = method_getImplementation(method);
2446 type = method_getTypeEncoding(method);
2447 } else {
2448 imp = NULL;
2449
2450 CYPoolTry {
2451 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2452 if (method == nil)
2453 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2454 type = CYPoolCString(pool, context, [method _typeString]);
2455 } CYPoolCatch(NULL)
2456 }
2457
2458 void *setup[2];
2459 setup[0] = &self;
2460 setup[1] = &_cmd;
2461
2462 sig::Signature signature;
2463 sig::Parse(pool, &signature, type, &Structor_);
2464
2465 size_t used(count + 3);
2466 if (used > signature.count) {
2467 sig::Element *elements(new (pool) sig::Element[used]);
2468 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2469
2470 for (size_t index(signature.count); index != used; ++index) {
2471 sig::Element *element(&elements[index]);
2472 element->name = NULL;
2473 element->offset = _not(size_t);
2474
2475 sig::Type *type(new (pool) sig::Type);
2476 memset(type, 0, sizeof(*type));
2477 type->primitive = sig::object_P;
2478 element->type = type;
2479 }
2480
2481 signature.elements = elements;
2482 signature.count = used;
2483 }
2484
2485 ffi_cif cif;
2486 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2487
2488 if (imp == NULL) {
2489 #ifdef __APPLE__
2490 #ifndef CY_NO_STRET
2491 if (stret(cif.rtype))
2492 imp = class_getMethodImplementation_stret(_class, _cmd);
2493 else
2494 #endif
2495 imp = class_getMethodImplementation(_class, _cmd);
2496 #else
2497 objc_super super = {self, _class};
2498 imp = objc_msg_lookup_super(&super, _cmd);
2499 #endif
2500 }
2501
2502 void (*function)() = reinterpret_cast<void (*)()>(imp);
2503 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2504 }
2505
2506 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2507 if (count < 2)
2508 throw CYJSError(context, "too few arguments to objc_msgSend");
2509
2510 CYPool pool;
2511
2512 bool uninitialized;
2513
2514 id self;
2515 SEL _cmd;
2516 Class _class;
2517
2518 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2519 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2520 self = internal->GetValue();
2521 _class = internal->class_;;
2522 uninitialized = false;
2523 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2524 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2525 self = internal->GetValue();
2526 _class = nil;
2527 uninitialized = internal->IsUninitialized();
2528 if (uninitialized)
2529 internal->value_ = nil;
2530 } else {
2531 self = CYCastNSObject(&pool, context, arguments[0]);
2532 _class = nil;
2533 uninitialized = false;
2534 }
2535
2536 if (self == nil)
2537 return CYJSNull(context);
2538
2539 _cmd = CYCastSEL(context, arguments[1]);
2540
2541 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2542 }
2543
2544 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2545 return $objc_msgSend(context, object, _this, count, arguments);
2546 } CYCatch(NULL) }
2547
2548 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2549 JSValueRef setup[count + 2];
2550 setup[0] = _this;
2551 setup[1] = object;
2552 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2553 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2554 } CYCatch(NULL) }
2555
2556 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2557 CYPool pool;
2558 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2559
2560 // XXX: handle Instance::Uninitialized?
2561 id self(CYCastNSObject(&pool, context, _this));
2562
2563 void *setup[2];
2564 setup[0] = &self;
2565 setup[1] = &internal->sel_;
2566
2567 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2568 } CYCatch(NULL) }
2569
2570 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2571 if (count != 2)
2572 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2573 CYPool pool;
2574 id self(CYCastNSObject(&pool, context, arguments[0]));
2575 Class _class(CYCastClass(pool, context, arguments[1]));
2576 return cy::Super::Make(context, self, _class);
2577 } CYCatch(NULL) }
2578
2579 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2580 if (count != 1)
2581 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2582 CYPool pool;
2583 const char *name(CYPoolCString(pool, context, arguments[0]));
2584 return CYMakeSelector(context, sel_registerName(name));
2585 } CYCatch(NULL) }
2586
2587 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2588 if (count > 1)
2589 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2590 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2591 return CYMakeInstance(context, self, false);
2592 } CYCatch(NULL) }
2593
2594 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2595 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2596 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2597 } CYCatch(NULL) }
2598
2599 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2600 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2601 Type_privateData *typical(internal->GetType());
2602
2603 sig::Type *type;
2604 ffi_type *ffi;
2605
2606 if (typical == NULL) {
2607 type = NULL;
2608 ffi = NULL;
2609 } else {
2610 type = typical->type_;
2611 ffi = typical->ffi_;
2612 }
2613
2614 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2615 } CYCatch(NULL) }
2616
2617 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2618 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2619 const char *encoding(CYBlockEncoding(internal->GetValue()));
2620 if (encoding == NULL)
2621 return CYJSNull(context);
2622 // XXX: this should be stored on a FunctionInstance private value subclass
2623 CYPool pool;
2624 sig::Signature signature;
2625 sig::Parse(pool, &signature, encoding, &Structor_);
2626 return CYMakeType(context, &signature);
2627 } CYCatch(NULL) }
2628
2629 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2630 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2631 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2632 } CYCatch(NULL) }
2633
2634 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2635 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2636 id self(internal->GetValue());
2637 if (!CYIsClass(self))
2638 return CYJSUndefined(context);
2639 return CYGetClassPrototype(context, self);
2640 } CYCatch(NULL) }
2641
2642 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2643 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2644 id self(internal->GetValue());
2645 if (!CYIsClass(self))
2646 return CYJSUndefined(context);
2647 return Messages::Make(context, (Class) self);
2648 } CYCatch(NULL) }
2649
2650 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2651 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2652
2653 if (!CYJSValueIsNSObject(context, _this))
2654 return NULL;
2655
2656 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2657 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2658 } CYCatch(NULL) }
2659
2660 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2661 if (!CYJSValueIsNSObject(context, _this))
2662 return NULL;
2663
2664 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2665 id value(internal->GetValue());
2666
2667 CYPoolTry {
2668 NSString *key;
2669 if (count == 0)
2670 key = nil;
2671 else
2672 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2673
2674 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2675 return CYJSUndefined(context);
2676 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2677 return json;
2678 else
2679 return CYCastJSValue(context, CYJSString(context, [value description]));
2680 } CYPoolCatch(NULL)
2681 } CYCatch(NULL) return /*XXX*/ NULL; }
2682
2683 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2684 if (!CYJSValueIsNSObject(context, _this))
2685 return NULL;
2686
2687 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2688 id value(internal->GetValue());
2689
2690 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2691 return _this;
2692
2693 if (JSValueRef result = [value cy$valueOfInContext:context])
2694 return result;
2695
2696 return _this;
2697 } CYCatch(NULL) return /*XXX*/ NULL; }
2698
2699 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2700 if (!CYJSValueIsNSObject(context, _this))
2701 return NULL;
2702
2703 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2704 // XXX: but... but... THIS ISN'T A POINTER! :(
2705 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2706 } CYCatch(NULL) return /*XXX*/ NULL; }
2707
2708 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2709 if (!CYJSValueIsNSObject(context, _this))
2710 return NULL;
2711
2712 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2713 id value(internal->GetValue());
2714
2715 CYPoolTry {
2716 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2717 return CYCastJSValue(context, CYJSString(context, [value description]));
2718 } CYPoolCatch(NULL)
2719 } CYCatch(NULL) return /*XXX*/ NULL; }
2720
2721 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2722 if (!CYJSValueIsNSObject(context, _this))
2723 return NULL;
2724
2725 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2726 id value(internal->GetValue());
2727
2728 if (!CYIsClass(value))
2729 CYThrow("non-Class object cannot be used as Type");
2730
2731 sig::Type type;
2732 memset(&type, 0, sizeof(type));
2733 type.primitive = sig::object_P;
2734 type.name = class_getName(value);
2735 return CYMakeType(context, &type);
2736 } CYCatch(NULL) return /*XXX*/ NULL; }
2737
2738 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2739 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2740 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2741 } CYCatch(NULL) }
2742
2743 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2744 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2745 }
2746
2747 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2748 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2749 const char *name(sel_getName(internal->GetValue()));
2750
2751 CYPoolTry {
2752 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2753 return CYCastJSValue(context, CYJSString(context, string));
2754 } CYPoolCatch(NULL)
2755 } CYCatch(NULL) return /*XXX*/ NULL; }
2756
2757 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2758 if (count != 1)
2759 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2760
2761 CYPool pool;
2762 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2763 SEL sel(internal->GetValue());
2764
2765 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2766 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2767 const char *encoding(method_getTypeEncoding(method));
2768
2769 sig::Signature signature;
2770 sig::Parse(pool, &signature, encoding, &Structor_);
2771 return CYMakeType(context, &signature);
2772 } CYCatch(NULL) }
2773
2774 static JSStaticValue Selector_staticValues[2] = {
2775 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2776 {NULL, NULL, NULL, 0}
2777 };
2778
2779 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2780 static JSStaticValue Instance_staticValues[5] = {
2781 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2782 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2783 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2784 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2785 {NULL, NULL, NULL, 0}
2786 };
2787
2788 static JSStaticValue FunctionInstance_staticValues[6] = {
2789 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2790 // XXX: this is sadly a duplicate of Instance_staticValues
2791 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2792 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2793 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2794 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2795 {NULL, NULL, NULL, 0}
2796 };
2797
2798 static JSStaticFunction Instance_staticFunctions[7] = {
2799 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2800 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2801 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2802 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2803 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2804 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2805 {NULL, NULL, 0}
2806 };
2807
2808 static JSStaticFunction Class_staticFunctions[2] = {
2809 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2810 {NULL, NULL, 0}
2811 };
2812
2813 static JSStaticFunction Internal_staticFunctions[2] = {
2814 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2815 {NULL, NULL, 0}
2816 };
2817
2818 static JSStaticFunction Selector_staticFunctions[5] = {
2819 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2820 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2821 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2822 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2823 {NULL, NULL, 0}
2824 };
2825
2826 #ifdef __APPLE__
2827 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2828 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2829 } CYObjectiveCatch }
2830 #endif
2831
2832 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2833 CYPool &pool(CYGetGlobalPool());
2834
2835 Object_type = new(pool) Type_privateData(sig::object_P);
2836 Selector_type = new(pool) Type_privateData(sig::selector_P);
2837
2838 NSArray_ = objc_getClass("NSArray");
2839 NSBlock_ = objc_getClass("NSBlock");
2840 NSDictionary_ = objc_getClass("NSDictionary");
2841 NSNumber_ = objc_getClass("NSNumber");
2842 NSString_ = objc_getClass("NSString");
2843 Object_ = objc_getClass("Object");
2844
2845 #ifdef __APPLE__
2846 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2847
2848 // XXX: apparently, iOS now has both of these
2849 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2850 if (NSCFBoolean_ == nil)
2851 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2852
2853 NSCFType_ = objc_getClass("NSCFType");
2854
2855 NSZombie_ = objc_getClass("_NSZombie_");
2856 #else
2857 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2858 #endif
2859
2860 JSClassDefinition definition;
2861
2862 definition = kJSClassDefinitionEmpty;
2863 definition.className = "Instance";
2864 definition.staticValues = Instance_staticValues;
2865 definition.staticFunctions = Instance_staticFunctions;
2866 definition.hasProperty = &Instance_hasProperty;
2867 definition.getProperty = &Instance_getProperty;
2868 definition.setProperty = &Instance_setProperty;
2869 definition.deleteProperty = &Instance_deleteProperty;
2870 definition.getPropertyNames = &Instance_getPropertyNames;
2871 definition.callAsConstructor = &Instance_callAsConstructor;
2872 definition.hasInstance = &Instance_hasInstance;
2873 definition.finalize = &CYFinalize;
2874 Instance_ = JSClassCreate(&definition);
2875
2876 definition.className = "ArrayInstance";
2877 ArrayInstance_ = JSClassCreate(&definition);
2878
2879 definition.className = "BooleanInstance";
2880 BooleanInstance_ = JSClassCreate(&definition);
2881
2882 definition.className = "NumberInstance";
2883 NumberInstance_ = JSClassCreate(&definition);
2884
2885 definition.className = "ObjectInstance";
2886 ObjectInstance_ = JSClassCreate(&definition);
2887
2888 definition.className = "StringInstance";
2889 StringInstance_ = JSClassCreate(&definition);
2890
2891 definition.className = "FunctionInstance";
2892 definition.staticValues = FunctionInstance_staticValues;
2893 definition.callAsFunction = &FunctionInstance_callAsFunction;
2894 FunctionInstance_ = JSClassCreate(&definition);
2895
2896 definition = kJSClassDefinitionEmpty;
2897 definition.className = "Class";
2898 definition.staticFunctions = Class_staticFunctions;
2899 Class_ = JSClassCreate(&definition);
2900
2901 definition = kJSClassDefinitionEmpty;
2902 definition.className = "Internal";
2903 definition.staticFunctions = Internal_staticFunctions;
2904 definition.hasProperty = &Internal_hasProperty;
2905 definition.getProperty = &Internal_getProperty;
2906 definition.setProperty = &Internal_setProperty;
2907 definition.getPropertyNames = &Internal_getPropertyNames;
2908 definition.finalize = &CYFinalize;
2909 Internal_ = JSClassCreate(&definition);
2910
2911 definition = kJSClassDefinitionEmpty;
2912 definition.className = "Message";
2913 definition.staticFunctions = cy::Functor::StaticFunctions;
2914 definition.staticValues = cy::Functor::StaticValues;
2915 definition.callAsFunction = &Message_callAsFunction;
2916 definition.finalize = &CYFinalize;
2917 Message_ = JSClassCreate(&definition);
2918
2919 definition = kJSClassDefinitionEmpty;
2920 definition.className = "Messages";
2921 definition.hasProperty = &Messages_hasProperty;
2922 definition.getProperty = &Messages_getProperty;
2923 definition.setProperty = &Messages_setProperty;
2924 #if 0 && OBJC_API_VERSION < 2
2925 definition.deleteProperty = &Messages_deleteProperty;
2926 #endif
2927 definition.getPropertyNames = &Messages_getPropertyNames;
2928 definition.finalize = &CYFinalize;
2929 Messages_ = JSClassCreate(&definition);
2930
2931 definition = kJSClassDefinitionEmpty;
2932 definition.className = "Selector";
2933 definition.staticValues = Selector_staticValues;
2934 definition.staticFunctions = Selector_staticFunctions;
2935 definition.callAsFunction = &Selector_callAsFunction;
2936 definition.finalize = &CYFinalize;
2937 Selector_ = JSClassCreate(&definition);
2938
2939 definition = kJSClassDefinitionEmpty;
2940 definition.className = "Super";
2941 definition.staticFunctions = Internal_staticFunctions;
2942 definition.finalize = &CYFinalize;
2943 Super_ = JSClassCreate(&definition);
2944
2945 definition = kJSClassDefinitionEmpty;
2946 definition.className = "ObjectiveC::Classes";
2947 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2948 definition.getProperty = &ObjectiveC_Classes_getProperty;
2949 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2950 ObjectiveC_Classes_ = JSClassCreate(&definition);
2951
2952 definition = kJSClassDefinitionEmpty;
2953 definition.className = "ObjectiveC::Constants";
2954 definition.getProperty = &ObjectiveC_Constants_getProperty;
2955 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2956 ObjectiveC_Constants_ = JSClassCreate(&definition);
2957
2958 #if OBJC_API_VERSION >= 2
2959 definition = kJSClassDefinitionEmpty;
2960 definition.className = "ObjectiveC::Images";
2961 definition.getProperty = &ObjectiveC_Images_getProperty;
2962 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2963 ObjectiveC_Images_ = JSClassCreate(&definition);
2964
2965 definition = kJSClassDefinitionEmpty;
2966 definition.className = "ObjectiveC::Image::Classes";
2967 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2968 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2969 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2970 #endif
2971
2972 definition = kJSClassDefinitionEmpty;
2973 definition.className = "ObjectiveC::Protocols";
2974 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2975 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2976 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2977
2978 #ifdef __APPLE__
2979 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2980 // XXX: this is horrible; there has to be a better way to do this
2981 #ifdef __LP64__
2982 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2983 #else
2984 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2985 #endif
2986 );
2987 #endif
2988 } CYPoolCatch() }
2989
2990 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2991 JSObjectRef global(CYGetGlobalObject(context));
2992 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2993 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2994 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2995 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2996
2997 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2998 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2999
3000 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3001 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
3002 CYArrayPush(context, alls, protocols);
3003
3004 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
3005 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
3006 CYArrayPush(context, alls, classes);
3007
3008 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
3009 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
3010 CYArrayPush(context, alls, constants);
3011
3012 #if OBJC_API_VERSION >= 2
3013 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3014 #endif
3015
3016 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
3017 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3018 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3019 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3020 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
3021
3022 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
3023 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3024
3025 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
3026 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
3027 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
3028 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
3029 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
3030
3031 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
3032 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
3033 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
3034 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
3035 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
3036
3037 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
3038 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
3039 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
3040 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
3041 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
3042
3043 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
3044 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
3045 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
3046 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
3047 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
3048
3049 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3050 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3051 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3052 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3053 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3054
3055 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3056 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3057 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3058 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3059 CYSetPrototype(context, StringInstance_prototype, String_prototype);
3060
3061 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
3062 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
3063 CYSetPrototype(context, Class_prototype, Instance_prototype);
3064
3065 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3066 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3067 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3068
3069 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3070 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3071
3072 #ifdef __APPLE__
3073 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3074 #endif
3075
3076 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3077
3078 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3079 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3080 } CYPoolCatch() }
3081
3082 static CYHook CYObjectiveCHook = {
3083 &CYObjectiveC_ExecuteStart,
3084 &CYObjectiveC_ExecuteEnd,
3085 &CYObjectiveC_CallFunction,
3086 &CYObjectiveC_Initialize,
3087 &CYObjectiveC_SetupContext,
3088 &CYObjectiveC_PoolFFI,
3089 &CYObjectiveC_FromFFI,
3090 };
3091
3092 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3093
3094 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3095 CYSetupContext(context);
3096 } CYObjectiveCatch }
3097
3098 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3099 CYPool pool;
3100
3101 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3102 CYStream stream(utf8.data, utf8.data + utf8.size);
3103 utf8 = CYPoolCode(pool, stream);
3104
3105 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3106 size_t bytes(utf16.size * sizeof(uint16_t));
3107 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3108 memcpy(copy, utf16.data, bytes);
3109
3110 *data = copy;
3111 *size = utf16.size;
3112 } catch (const CYException &exception) {
3113 CYPool pool;
3114 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];
3115 } }