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