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