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