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