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