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