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