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