]> git.saurik.com Git - cycript.git/blame_incremental - ObjectiveC/Library.mm
Split JavaScript Array utility functions into Library.
[cycript.git] / ObjectiveC / Library.mm
... / ...
CommitLineData
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
125JSValueRef 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 {{{ */
128apr_status_t CYPoolRelease_(void *data) {
129 id object(reinterpret_cast<id>(data));
130 [object release];
131 return APR_SUCCESS;
132}
133
134id 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
145template <typename Type_>
146Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
147 return (Type_) CYPoolRelease_(pool, (id) object);
148}
149/* }}} */
150/* Objective-C Strings {{{ */
151const 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
163JSStringRef 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
172JSStringRef 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
180NSString *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
188NSString *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
197NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
198 return CYCopyNSString(context, CYJSString(context, value));
199}
200
201NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
202 return CYPoolRelease(pool, CYCopyNSString(value));
203}
204
205NSString *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
210NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
211 return CYPoolRelease(pool, CYCopyNSString(context, value));
212}
213
214CYUTF8String 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
220JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
221
222void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
223 if (exception == NULL)
224 throw error;
225 *exception = CYCastJSValue(context, error);
226}
227
228size_t CYGetIndex(NSString *value) {
229 return CYGetIndex(CYCastUTF8String(value));
230}
231
232bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
233 return CYGetOffset(CYPoolCString(pool, context, value), index);
234}
235
236static JSClassRef Instance_;
237static JSClassRef Internal_;
238static JSClassRef Message_;
239static JSClassRef Messages_;
240static JSClassRef Selector_;
241static JSClassRef StringInstance_;
242static JSClassRef Super_;
243
244static JSClassRef ObjectiveC_Classes_;
245static JSClassRef ObjectiveC_Protocols_;
246
247#ifdef __APPLE__
248static JSClassRef ObjectiveC_Image_Classes_;
249static JSClassRef ObjectiveC_Images_;
250#endif
251
252#ifdef __APPLE__
253static Class NSCFBoolean_;
254static Class NSCFType_;
255static Class NSGenericDeallocHandler_;
256static Class NSMessageBuilder_;
257static Class NSZombie_;
258#else
259static Class NSBoolNumber_;
260#endif
261
262static Class NSArray_;
263static Class NSDictionary_;
264static Class NSString_;
265static Class Object_;
266
267static Type_privateData *Object_type;
268static Type_privateData *Selector_type;
269
270Type_privateData *Instance::GetType() const {
271 return Object_type;
272}
273
274Type_privateData *Selector_privateData::GetType() const {
275 return Selector_type;
276}
277
278static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
279
280JSValueRef 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("Array_prototype"));
300 else if (self == NSDictionary_)
301 prototype = CYGetCachedObject(context, CYJSString("Object_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
314JSObjectRef 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
325JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
326 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
327}
328
329namespace cy {
330JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
331 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
332 return value;
333} }
334
335JSObjectRef 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
341Instance::~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
348struct 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
360JSObjectRef 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
400NSString *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__
439struct 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__
527NSObject *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
590NSObject *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
599NSObject *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
608NSNumber *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
618id 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
671NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
672 return CYNSObject(pool, context, value, true);
673}
674
675NSObject *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 ? [self stringValue] : [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 CYMakeInstance(context, self, false);
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 CYUTF8String string(CYCastUTF8String(self));
1026 CYStringify(str, string.data, string.size);
1027 std::string value(str.str());
1028 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1029}
1030
1031- (NSString *) cy$toKey {
1032 if (CYIsKey(CYCastUTF8String(self)))
1033 return self;
1034 return [self cy$toCYON];
1035}
1036
1037- (bool) cy$hasProperty:(NSString *)name {
1038 if ([name isEqualToString:@"length"])
1039 return true;
1040
1041 size_t index(CYGetIndex(name));
1042 if (index == _not(size_t) || index >= [self length])
1043 return [super cy$hasProperty:name];
1044 else
1045 return true;
1046}
1047
1048- (NSObject *) cy$getProperty:(NSString *)name {
1049 if ([name isEqualToString:@"length"]) {
1050 NSUInteger count([self length]);
1051#ifdef __APPLE__
1052 return [NSNumber numberWithUnsignedInteger:count];
1053#else
1054 return [NSNumber numberWithUnsignedInt:count];
1055#endif
1056 }
1057
1058 size_t index(CYGetIndex(name));
1059 if (index == _not(size_t) || index >= [self length])
1060 return [super cy$getProperty:name];
1061 else
1062 return [self substringWithRange:NSMakeRange(index, 1)];
1063}
1064
1065- (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1066 [super cy$getPropertyNames:names inContext:context];
1067
1068 for (size_t index(0), length([self length]); index != length; ++index) {
1069 char name[32];
1070 sprintf(name, "%zu", index);
1071 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1072 }
1073}
1074
1075// XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1076+ (bool) cy$hasImplicitProperties {
1077 return false;
1078}
1079
1080@end
1081/* }}} */
1082/* Bridge: WebUndefined {{{ */
1083@implementation WebUndefined (Cycript)
1084
1085- (JSType) cy$JSType {
1086 return kJSTypeUndefined;
1087}
1088
1089- (NSObject *) cy$toJSON:(NSString *)key {
1090 return self;
1091}
1092
1093- (NSString *) cy$toCYON {
1094 return @"undefined";
1095}
1096
1097- (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1098 return CYJSUndefined(context);
1099} CYObjectiveCatch }
1100
1101@end
1102/* }}} */
1103
1104static bool CYIsClass(id self) {
1105#ifdef __APPLE__
1106 // XXX: this is a lame object_isClass
1107 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1108#else
1109 return GSObjCIsClass(self);
1110#endif
1111}
1112
1113Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1114 id self(CYCastNSObject(pool, context, value));
1115 if (CYIsClass(self))
1116 return (Class) self;
1117 throw CYJSError(context, "got something that is not a Class");
1118 return NULL;
1119}
1120
1121NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1122 CYPool pool;
1123 size_t size(JSPropertyNameArrayGetCount(names));
1124 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1125 for (size_t index(0); index != size; ++index)
1126 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1127 return array;
1128}
1129
1130JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1131 if (value == nil)
1132 return CYJSNull(context);
1133 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1134 return [value cy$JSValueInContext:context];
1135 else
1136 return CYMakeInstance(context, value, false);
1137} CYPoolCatch(NULL) return /*XXX*/ NULL; }
1138
1139@implementation CYJSObject
1140
1141- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1142 if ((self = [super init]) != nil) {
1143 object_ = object;
1144 context_ = CYGetJSContext(context);
1145 //XXX:JSGlobalContextRetain(context_);
1146 JSValueProtect(context_, object_);
1147 } return self;
1148} CYObjectiveCatch }
1149
1150- (void) dealloc { CYObjectiveTry {
1151 JSValueUnprotect(context_, object_);
1152 //XXX:JSGlobalContextRelease(context_);
1153 [super dealloc];
1154} CYObjectiveCatch }
1155
1156- (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1157 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1158 if (!CYIsCallable(context_, toJSON))
1159 return [super cy$toJSON:key];
1160 else {
1161 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1162 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1163 // XXX: do I really want an NSNull here?!
1164 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1165 }
1166} CYObjectiveCatch }
1167
1168- (NSString *) cy$toCYON { CYObjectiveTry {
1169 CYPool pool;
1170 JSValueRef exception(NULL);
1171 const char *cyon(CYPoolCCYON(pool, context_, object_));
1172 CYThrow(context_, exception);
1173 if (cyon == NULL)
1174 return [super cy$toCYON];
1175 else
1176 return [NSString stringWithUTF8String:cyon];
1177} CYObjectiveCatch }
1178
1179- (NSUInteger) count { CYObjectiveTry {
1180 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1181 size_t size(JSPropertyNameArrayGetCount(names));
1182 JSPropertyNameArrayRelease(names);
1183 return size;
1184} CYObjectiveCatch }
1185
1186- (id) objectForKey:(id)key { CYObjectiveTry {
1187 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1188 if (JSValueIsUndefined(context_, value))
1189 return nil;
1190 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1191} CYObjectiveCatch }
1192
1193- (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1194 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1195 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1196 JSPropertyNameArrayRelease(names);
1197 return enumerator;
1198} CYObjectiveCatch }
1199
1200- (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1201 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1202} CYObjectiveCatch }
1203
1204- (void) removeObjectForKey:(id)key { CYObjectiveTry {
1205 JSValueRef exception(NULL);
1206 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1207 CYThrow(context_, exception);
1208} CYObjectiveCatch }
1209
1210@end
1211
1212@implementation CYJSArray
1213
1214- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1215 if ((self = [super init]) != nil) {
1216 object_ = object;
1217 context_ = CYGetJSContext(context);
1218 //XXX:JSGlobalContextRetain(context_);
1219 JSValueProtect(context_, object_);
1220 } return self;
1221} CYObjectiveCatch }
1222
1223- (void) dealloc { CYObjectiveTry {
1224 JSValueUnprotect(context_, object_);
1225 //XXX:JSGlobalContextRelease(context_);
1226 [super dealloc];
1227} CYObjectiveCatch }
1228
1229- (NSUInteger) count { CYObjectiveTry {
1230 return CYArrayLength(context_, object_);
1231} CYObjectiveCatch }
1232
1233- (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1234 size_t bounds([self count]);
1235 if (index >= bounds)
1236 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1237 JSValueRef exception(NULL);
1238 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1239 CYThrow(context_, exception);
1240 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1241} CYObjectiveCatch }
1242
1243- (void) addObject:(id)object { CYObjectiveTry {
1244 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1245} CYObjectiveCatch }
1246
1247- (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1248 size_t bounds([self count] + 1);
1249 if (index >= bounds)
1250 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1251 JSValueRef exception(NULL);
1252 JSValueRef arguments[3];
1253 arguments[0] = CYCastJSValue(context_, index);
1254 arguments[1] = CYCastJSValue(context_, 0);
1255 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1256 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1257 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1258 CYThrow(context_, exception);
1259} CYObjectiveCatch }
1260
1261- (void) removeLastObject { CYObjectiveTry {
1262 JSValueRef exception(NULL);
1263 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1264 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1265 CYThrow(context_, exception);
1266} CYObjectiveCatch }
1267
1268- (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1269 size_t bounds([self count]);
1270 if (index >= bounds)
1271 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1272 JSValueRef exception(NULL);
1273 JSValueRef arguments[2];
1274 arguments[0] = CYCastJSValue(context_, index);
1275 arguments[1] = CYCastJSValue(context_, 1);
1276 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1277 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1278 CYThrow(context_, exception);
1279} CYObjectiveCatch }
1280
1281- (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1282 size_t bounds([self count]);
1283 if (index >= bounds)
1284 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1285 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1286} CYObjectiveCatch }
1287
1288@end
1289
1290// XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1291struct CYInternal :
1292 CYData
1293{
1294 JSObjectRef object_;
1295
1296 CYInternal() :
1297 object_(NULL)
1298 {
1299 }
1300
1301 ~CYInternal() {
1302 // XXX: delete object_? ;(
1303 }
1304
1305 static CYInternal *Get(id self) {
1306 CYInternal *internal(NULL);
1307 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1308 // XXX: do something epic? ;P
1309 }
1310
1311 return internal;
1312 }
1313
1314 static CYInternal *Set(id self) {
1315 CYInternal *internal(NULL);
1316 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1317 if (internal == NULL) {
1318 internal = new CYInternal();
1319 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1320 }
1321 } else {
1322 // XXX: do something epic? ;P
1323 }
1324
1325 return internal;
1326 }
1327
1328 bool HasProperty(JSContextRef context, JSStringRef name) {
1329 if (object_ == NULL)
1330 return false;
1331 return JSObjectHasProperty(context, object_, name);
1332 }
1333
1334 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1335 if (object_ == NULL)
1336 return NULL;
1337 return CYGetProperty(context, object_, name);
1338 }
1339
1340 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1341 if (object_ == NULL)
1342 object_ = JSObjectMake(context, NULL, NULL);
1343 CYSetProperty(context, object_, name, value);
1344 }
1345};
1346
1347static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1348 Selector_privateData *internal(new Selector_privateData(sel));
1349 return JSObjectMake(context, Selector_, internal);
1350}
1351
1352static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1353 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1354 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1355 return reinterpret_cast<SEL>(internal->value_);
1356 } else
1357 return CYCastPointer<SEL>(context, value);
1358}
1359
1360void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1361 return (void *) [[NSAutoreleasePool alloc] init];
1362} CYSadCatch(NULL) }
1363
1364void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1365 return [(NSAutoreleasePool *) handle release];
1366} CYSadCatch() }
1367
1368JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1369 if (name == "nil")
1370 return Instance::Make(context, nil);
1371 if (Class _class = objc_getClass(name.data))
1372 return CYMakeInstance(context, _class, true);
1373 if (Protocol *protocol = objc_getProtocol(name.data))
1374 return CYMakeInstance(context, protocol, true);
1375 return NULL;
1376} CYPoolCatch(NULL) return /*XXX*/ NULL; }
1377
1378static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1379 ffi_call(cif, function, value, values);
1380} CYSadCatch() }
1381
1382static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1383 switch (type->primitive) {
1384 // XXX: do something epic about blocks
1385 case sig::block_P:
1386 case sig::object_P:
1387 case sig::typename_P:
1388 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1389 break;
1390
1391 case sig::selector_P:
1392 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1393 break;
1394
1395 default:
1396 return false;
1397 }
1398
1399 return true;
1400} CYSadCatch(false) }
1401
1402static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1403 switch (type->primitive) {
1404 // XXX: do something epic about blocks
1405 case sig::block_P:
1406 case sig::object_P:
1407 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1408 JSValueRef value(CYCastJSValue(context, object));
1409 if (initialize)
1410 [object release];
1411 return value;
1412 } else goto null;
1413
1414 case sig::typename_P:
1415 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1416
1417 case sig::selector_P:
1418 if (SEL sel = *reinterpret_cast<SEL *>(data))
1419 return CYMakeSelector(context, sel);
1420 else goto null;
1421
1422 null:
1423 return CYJSNull(context);
1424 default:
1425 return NULL;
1426 }
1427} CYPoolCatch(NULL) return /*XXX*/ NULL; }
1428
1429static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1430 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1431 if (!devoid)
1432 return true;
1433#if OBJC_API_VERSION >= 2
1434 char type[16];
1435 method_getReturnType(method, type, sizeof(type));
1436#else
1437 const char *type(method_getTypeEncoding(method));
1438#endif
1439 if (type[0] != 'v')
1440 return true;
1441 }
1442
1443 // XXX: possibly use a more "awesome" check?
1444 return false;
1445}
1446
1447static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1448 if (method != NULL)
1449 return method_getTypeEncoding(method);
1450
1451 const char *name(sel_getName(sel));
1452 size_t length(strlen(name));
1453
1454 char keyed[length + 2];
1455 keyed[0] = '6';
1456 keyed[length + 1] = '\0';
1457 memcpy(keyed + 1, name, length);
1458
1459 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1460 return entry->value_;
1461
1462 return NULL;
1463}
1464
1465static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1466 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1467
1468 JSContextRef context(internal->context_);
1469
1470 size_t count(internal->cif_.nargs);
1471 JSValueRef values[count];
1472
1473 for (size_t index(0); index != count; ++index)
1474 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1475
1476 JSObjectRef _this(CYCastJSObject(context, values[0]));
1477
1478 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1479 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1480}
1481
1482static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1483 Message_privateData *internal(new Message_privateData(sel, type, imp));
1484 return JSObjectMake(context, Message_, internal);
1485}
1486
1487static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1488 JSObjectRef function(CYCastJSObject(context, value));
1489 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1490 // XXX: see notes in Library.cpp about needing to leak
1491 return reinterpret_cast<IMP>(internal->GetValue());
1492}
1493
1494static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1495 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1496 Class _class(internal->GetValue());
1497
1498 CYPool pool;
1499 const char *name(CYPoolCString(pool, context, property));
1500
1501 if (SEL sel = sel_getUid(name))
1502 if (class_getInstanceMethod(_class, sel) != NULL)
1503 return true;
1504
1505 return false;
1506}
1507
1508static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1509 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1510 Class _class(internal->GetValue());
1511
1512 CYPool pool;
1513 const char *name(CYPoolCString(pool, context, property));
1514
1515 if (SEL sel = sel_getUid(name))
1516 if (objc_method *method = class_getInstanceMethod(_class, sel))
1517 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1518
1519 return NULL;
1520}
1521
1522static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1523 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1524 Class _class(internal->GetValue());
1525
1526 CYPool pool;
1527 const char *name(CYPoolCString(pool, context, property));
1528
1529 SEL sel(sel_registerName(name));
1530
1531 objc_method *method(class_getInstanceMethod(_class, sel));
1532
1533 const char *type;
1534 IMP imp;
1535
1536 if (JSValueIsObjectOfClass(context, value, Message_)) {
1537 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1538 type = sig::Unparse(pool, &message->signature_);
1539 imp = reinterpret_cast<IMP>(message->GetValue());
1540 } else {
1541 type = CYPoolTypeEncoding(pool, context, sel, method);
1542 imp = CYMakeMessage(context, value, type);
1543 }
1544
1545 if (method != NULL)
1546 method_setImplementation(method, imp);
1547 else {
1548#ifdef GNU_RUNTIME
1549 GSMethodList list(GSAllocMethodList(1));
1550 GSAppendMethodToList(list, sel, type, imp, YES);
1551 GSAddMethodList(_class, list, YES);
1552 GSFlushMethodCacheForClass(_class);
1553#else
1554 class_addMethod(_class, sel, imp, type);
1555#endif
1556 }
1557
1558 return true;
1559}
1560
1561#if 0 && OBJC_API_VERSION < 2
1562static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1563 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1564 Class _class(internal->GetValue());
1565
1566 CYPool pool;
1567 const char *name(CYPoolCString(pool, context, property));
1568
1569 if (SEL sel = sel_getUid(name))
1570 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1571 objc_method_list list = {NULL, 1, {method}};
1572 class_removeMethods(_class, &list);
1573 return true;
1574 }
1575
1576 return false;
1577}
1578#endif
1579
1580static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1581 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1582 Class _class(internal->GetValue());
1583
1584#if OBJC_API_VERSION >= 2
1585 unsigned int size;
1586 objc_method **data(class_copyMethodList(_class, &size));
1587 for (size_t i(0); i != size; ++i)
1588 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1589 free(data);
1590#else
1591 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1592 for (int i(0); i != methods->method_count; ++i)
1593 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1594#endif
1595}
1596
1597static bool CYHasImplicitProperties(Class _class) {
1598 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1599 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1600 return true;
1601 return [_class cy$hasImplicitProperties];
1602}
1603
1604static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1605 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1606 id self(internal->GetValue());
1607
1608 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1609 return true;
1610
1611 CYPool pool;
1612 NSString *name(CYCastNSString(pool, context, property));
1613
1614 if (CYInternal *internal = CYInternal::Get(self))
1615 if (internal->HasProperty(context, property))
1616 return true;
1617
1618 Class _class(object_getClass(self));
1619
1620 CYPoolTry {
1621 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1622 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1623 if ([self cy$hasProperty:name])
1624 return true;
1625 } CYPoolCatch(false)
1626
1627 const char *string(CYPoolCString(pool, context, name));
1628
1629#ifdef __APPLE__
1630 if (class_getProperty(_class, string) != NULL)
1631 return true;
1632#endif
1633
1634 if (CYHasImplicitProperties(_class))
1635 if (SEL sel = sel_getUid(string))
1636 if (CYImplements(self, _class, sel, true))
1637 return true;
1638
1639 return false;
1640}
1641
1642static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1643 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1644 id self(internal->GetValue());
1645
1646 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1647 return Internal::Make(context, self, object);
1648
1649 CYPool pool;
1650 NSString *name(CYCastNSString(pool, context, property));
1651
1652 if (CYInternal *internal = CYInternal::Get(self))
1653 if (JSValueRef value = internal->GetProperty(context, property))
1654 return value;
1655
1656 CYPoolTry {
1657 if (NSObject *data = [self cy$getProperty:name])
1658 return CYCastJSValue(context, data);
1659 } CYPoolCatch(NULL)
1660
1661 const char *string(CYPoolCString(pool, context, name));
1662 Class _class(object_getClass(self));
1663
1664#ifdef __APPLE__
1665 if (objc_property_t property = class_getProperty(_class, string)) {
1666 PropertyAttributes attributes(property);
1667 SEL sel(sel_registerName(attributes.Getter()));
1668 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1669 }
1670#endif
1671
1672 if (CYHasImplicitProperties(_class))
1673 if (SEL sel = sel_getUid(string))
1674 if (CYImplements(self, _class, sel, true))
1675 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1676
1677 return NULL;
1678} CYCatch }
1679
1680static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1681 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1682 id self(internal->GetValue());
1683
1684 CYPool pool;
1685
1686 NSString *name(CYCastNSString(pool, context, property));
1687 NSObject *data(CYCastNSObject(pool, context, value));
1688
1689 CYPoolTry {
1690 if ([self cy$setProperty:name to:data])
1691 return true;
1692 } CYPoolCatch(NULL)
1693
1694 const char *string(CYPoolCString(pool, context, name));
1695 Class _class(object_getClass(self));
1696
1697#ifdef __APPLE__
1698 if (objc_property_t property = class_getProperty(_class, string)) {
1699 PropertyAttributes attributes(property);
1700 if (const char *setter = attributes.Setter()) {
1701 SEL sel(sel_registerName(setter));
1702 JSValueRef arguments[1] = {value};
1703 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1704 return true;
1705 }
1706 }
1707#endif
1708
1709 size_t length(strlen(string));
1710
1711 char set[length + 5];
1712
1713 set[0] = 's';
1714 set[1] = 'e';
1715 set[2] = 't';
1716
1717 if (string[0] != '\0') {
1718 set[3] = toupper(string[0]);
1719 memcpy(set + 4, string + 1, length - 1);
1720 }
1721
1722 set[length + 3] = ':';
1723 set[length + 4] = '\0';
1724
1725 if (SEL sel = sel_getUid(set))
1726 if (CYImplements(self, _class, sel, false)) {
1727 JSValueRef arguments[1] = {value};
1728 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1729 }
1730
1731 if (CYInternal *internal = CYInternal::Set(self)) {
1732 internal->SetProperty(context, property, value);
1733 return true;
1734 }
1735
1736 return false;
1737} CYCatch }
1738
1739static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1740 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1741 id self(internal->GetValue());
1742
1743 CYPoolTry {
1744 NSString *name(CYCastNSString(NULL, context, property));
1745 return [self cy$deleteProperty:name];
1746 } CYPoolCatch(NULL)
1747} CYCatch return /*XXX*/ NULL; }
1748
1749static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1750 const char *name(sel_getName(method_getName(method)));
1751 if (strchr(name, ':') != NULL)
1752 return;
1753
1754 const char *type(method_getTypeEncoding(method));
1755 if (type == NULL || *type == '\0' || *type == 'v')
1756 return;
1757
1758 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1759}
1760
1761static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1762 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1763 id self(internal->GetValue());
1764
1765 CYPool pool;
1766 Class _class(object_getClass(self));
1767
1768#ifdef __APPLE__
1769 {
1770 unsigned int size;
1771 objc_property_t *data(class_copyPropertyList(_class, &size));
1772 for (size_t i(0); i != size; ++i)
1773 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1774 free(data);
1775 }
1776#endif
1777
1778 if (CYHasImplicitProperties(_class))
1779 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1780#if OBJC_API_VERSION >= 2
1781 unsigned int size;
1782 objc_method **data(class_copyMethodList(current, &size));
1783 for (size_t i(0); i != size; ++i)
1784 Instance_getPropertyNames_message(names, data[i]);
1785 free(data);
1786#else
1787 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1788 for (int i(0); i != methods->method_count; ++i)
1789 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1790#endif
1791 }
1792
1793 CYPoolTry {
1794 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1795 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1796 [self cy$getPropertyNames:names inContext:context];
1797 } CYPoolCatch()
1798}
1799
1800static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1801 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1802 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1803 return value;
1804} CYCatch }
1805
1806static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1807 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1808 Class _class(internal->GetValue());
1809 if (!CYIsClass(_class))
1810 return false;
1811
1812 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1813 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1814 // XXX: this isn't always safe
1815 return [linternal->GetValue() isKindOfClass:_class];
1816 }
1817
1818 return false;
1819} CYCatch }
1820
1821static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1822 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1823 CYPool pool;
1824
1825 id self(internal->GetValue());
1826 const char *name(CYPoolCString(pool, context, property));
1827
1828 if (object_getInstanceVariable(self, name, NULL) != NULL)
1829 return true;
1830
1831 return false;
1832}
1833
1834static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1835 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1836 CYPool pool;
1837
1838 id self(internal->GetValue());
1839 const char *name(CYPoolCString(pool, context, property));
1840
1841 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1842 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1843 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1844 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1845 }
1846
1847 return NULL;
1848} CYCatch }
1849
1850static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1851 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1852 CYPool pool;
1853
1854 id self(internal->GetValue());
1855 const char *name(CYPoolCString(pool, context, property));
1856
1857 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1858 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1859 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1860 return true;
1861 }
1862
1863 return false;
1864} CYCatch }
1865
1866static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1867 if (Class super = class_getSuperclass(_class))
1868 Internal_getPropertyNames_(super, names);
1869
1870#if OBJC_API_VERSION >= 2
1871 unsigned int size;
1872 objc_ivar **data(class_copyIvarList(_class, &size));
1873 for (size_t i(0); i != size; ++i)
1874 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1875 free(data);
1876#else
1877 if (objc_ivar_list *ivars = _class->ivars)
1878 for (int i(0); i != ivars->ivar_count; ++i)
1879 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1880#endif
1881}
1882
1883static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1884 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1885 CYPool pool;
1886
1887 id self(internal->GetValue());
1888 Class _class(object_getClass(self));
1889
1890 Internal_getPropertyNames_(_class, names);
1891}
1892
1893static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1894 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1895 return internal->GetOwner();
1896}
1897
1898static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1899 CYPool pool;
1900 NSString *name(CYCastNSString(pool, context, property));
1901 if (Class _class = NSClassFromString(name))
1902 return CYMakeInstance(context, _class, true);
1903 return NULL;
1904} CYCatch }
1905
1906static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1907#ifdef __APPLE__
1908 size_t size(objc_getClassList(NULL, 0));
1909 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1910
1911 get:
1912 size_t writ(objc_getClassList(data, size));
1913 if (size < writ) {
1914 size = writ;
1915 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1916 data = copy;
1917 goto get;
1918 } else goto done;
1919 }
1920
1921 for (size_t i(0); i != writ; ++i)
1922 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1923
1924 done:
1925 free(data);
1926#else
1927 void *state(NULL);
1928 while (Class _class = objc_next_class(&state))
1929 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1930#endif
1931}
1932
1933#if OBJC_API_VERSION >= 2
1934static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1935 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1936
1937 CYPool pool;
1938 const char *name(CYPoolCString(pool, context, property));
1939 unsigned int size;
1940 const char **data(objc_copyClassNamesForImage(internal, &size));
1941 JSValueRef value;
1942 for (size_t i(0); i != size; ++i)
1943 if (strcmp(name, data[i]) == 0) {
1944 if (Class _class = objc_getClass(name)) {
1945 value = CYMakeInstance(context, _class, true);
1946 goto free;
1947 } else
1948 break;
1949 }
1950 value = NULL;
1951 free:
1952 free(data);
1953 return value;
1954} CYCatch }
1955
1956static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1957 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1958 unsigned int size;
1959 const char **data(objc_copyClassNamesForImage(internal, &size));
1960 for (size_t i(0); i != size; ++i)
1961 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1962 free(data);
1963}
1964
1965static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1966 CYPool pool;
1967 const char *name(CYPoolCString(pool, context, property));
1968 unsigned int size;
1969 const char **data(objc_copyImageNames(&size));
1970 for (size_t i(0); i != size; ++i)
1971 if (strcmp(name, data[i]) == 0) {
1972 name = data[i];
1973 goto free;
1974 }
1975 name = NULL;
1976 free:
1977 free(data);
1978 if (name == NULL)
1979 return NULL;
1980 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1981 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1982 return value;
1983} CYCatch }
1984
1985static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1986 unsigned int size;
1987 const char **data(objc_copyImageNames(&size));
1988 for (size_t i(0); i != size; ++i)
1989 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1990 free(data);
1991}
1992#endif
1993
1994static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1995 CYPool pool;
1996 const char *name(CYPoolCString(pool, context, property));
1997 if (Protocol *protocol = objc_getProtocol(name))
1998 return CYMakeInstance(context, protocol, true);
1999 return NULL;
2000} CYCatch }
2001
2002static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2003#if OBJC_API_VERSION >= 2
2004 unsigned int size;
2005 Protocol **data(objc_copyProtocolList(&size));
2006 for (size_t i(0); i != size; ++i)
2007 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2008 free(data);
2009#else
2010 // XXX: fix this!
2011#endif
2012}
2013
2014#ifdef __APPLE__
2015static bool stret(ffi_type *ffi_type) {
2016 return ffi_type->type == FFI_TYPE_STRUCT && (
2017 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2018 struct_forward_array[ffi_type->size] != 0
2019 );
2020}
2021#endif
2022
2023JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) { CYTry {
2024 const char *type;
2025
2026 if (_class == NULL)
2027 _class = object_getClass(self);
2028
2029 IMP imp;
2030
2031 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2032 imp = method_getImplementation(method);
2033 type = method_getTypeEncoding(method);
2034 } else {
2035 imp = NULL;
2036
2037 CYPoolTry {
2038 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2039 if (method == nil)
2040 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2041 type = CYPoolCString(pool, context, [method _typeString]);
2042 } CYPoolCatch(NULL)
2043 }
2044
2045 void *setup[2];
2046 setup[0] = &self;
2047 setup[1] = &_cmd;
2048
2049 sig::Signature signature;
2050 sig::Parse(pool, &signature, type, &Structor_);
2051
2052 ffi_cif cif;
2053 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2054
2055 if (imp == NULL) {
2056#ifdef __APPLE__
2057 if (stret(cif.rtype))
2058 imp = class_getMethodImplementation_stret(_class, _cmd);
2059 else
2060 imp = class_getMethodImplementation(_class, _cmd);
2061#else
2062 objc_super super = {self, _class};
2063 imp = objc_msg_lookup_super(&super, _cmd);
2064#endif
2065 }
2066
2067 void (*function)() = reinterpret_cast<void (*)()>(imp);
2068 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2069} CYCatch }
2070
2071static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2072 if (count < 2)
2073 throw CYJSError(context, "too few arguments to objc_msgSend");
2074
2075 CYPool pool;
2076
2077 bool uninitialized;
2078
2079 id self;
2080 SEL _cmd;
2081 Class _class;
2082
2083 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2084 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2085 self = internal->GetValue();
2086 _class = internal->class_;;
2087 uninitialized = false;
2088 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2089 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2090 self = internal->GetValue();
2091 _class = nil;
2092 uninitialized = internal->IsUninitialized();
2093 if (uninitialized)
2094 internal->value_ = nil;
2095 } else {
2096 self = CYCastNSObject(pool, context, arguments[0]);
2097 _class = nil;
2098 uninitialized = false;
2099 }
2100
2101 if (self == nil)
2102 return CYJSNull(context);
2103
2104 _cmd = CYCastSEL(context, arguments[1]);
2105
2106 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2107} CYCatch }
2108
2109/* Hook: objc_registerClassPair {{{ */
2110#if defined(__APPLE__) && defined(__arm__) && 0
2111// XXX: replace this with associated objects
2112
2113MSHook(void, CYDealloc, id self, SEL sel) {
2114 CYInternal *internal;
2115 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2116 if (internal != NULL)
2117 delete internal;
2118 _CYDealloc(self, sel);
2119}
2120
2121MSHook(void, objc_registerClassPair, Class _class) {
2122 Class super(class_getSuperclass(_class));
2123 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2124 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2125 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2126 }
2127
2128 _objc_registerClassPair(_class);
2129}
2130
2131static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2132 if (count != 1)
2133 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2134 CYPool pool;
2135 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2136 if (value == NULL || !CYIsClass(value))
2137 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2138 Class _class((Class) value);
2139 $objc_registerClassPair(_class);
2140 return CYJSUndefined(context);
2141} CYCatch }
2142#endif
2143/* }}} */
2144
2145static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2146 JSValueRef setup[count + 2];
2147 setup[0] = _this;
2148 setup[1] = object;
2149 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2150 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2151}
2152
2153static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2154 CYPool pool;
2155 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2156
2157 // XXX: handle Instance::Uninitialized?
2158 id self(CYCastNSObject(pool, context, _this));
2159
2160 void *setup[2];
2161 setup[0] = &self;
2162 setup[1] = &internal->sel_;
2163
2164 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2165}
2166
2167static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2168 if (count != 2)
2169 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2170 CYPool pool;
2171 id self(CYCastNSObject(pool, context, arguments[0]));
2172 Class _class(CYCastClass(pool, context, arguments[1]));
2173 return cy::Super::Make(context, self, _class);
2174} CYCatch }
2175
2176static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2177 if (count != 1)
2178 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2179 CYPool pool;
2180 const char *name(CYPoolCString(pool, context, arguments[0]));
2181 return CYMakeSelector(context, sel_registerName(name));
2182} CYCatch }
2183
2184static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2185 if (count > 1)
2186 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2187 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2188 return CYMakeInstance(context, self, false);
2189} CYCatch }
2190
2191static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2192 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2193 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2194}
2195
2196static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2197 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2198 Type_privateData *typical(internal->GetType());
2199
2200 sig::Type *type;
2201 ffi_type *ffi;
2202
2203 if (typical == NULL) {
2204 type = NULL;
2205 ffi = NULL;
2206 } else {
2207 type = typical->type_;
2208 ffi = typical->ffi_;
2209 }
2210
2211 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2212}
2213
2214static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2215 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2216 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2217}
2218
2219static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2220 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2221 id self(internal->GetValue());
2222 if (!CYIsClass(self))
2223 return CYJSUndefined(context);
2224 return CYGetClassPrototype(context, self);
2225} CYCatch }
2226
2227static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2228 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2229 id self(internal->GetValue());
2230 if (!CYIsClass(self))
2231 return CYJSUndefined(context);
2232 return Messages::Make(context, (Class) self);
2233}
2234
2235static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2236 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2237 return NULL;
2238
2239 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2240 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2241} CYCatch }
2242
2243static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2244 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2245 return NULL;
2246
2247 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2248
2249 CYPoolTry {
2250 NSString *key;
2251 if (count == 0)
2252 key = nil;
2253 else
2254 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2255 // XXX: check for support of cy$toJSON?
2256 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2257 } CYPoolCatch(NULL)
2258} CYCatch return /*XXX*/ NULL; }
2259
2260#if 0
2261static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2262 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2263 return NULL;
2264
2265 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2266 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2267} CYCatch return /*XXX*/ NULL; }
2268#endif
2269
2270static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2271 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2272 return NULL;
2273
2274 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2275 // XXX: but... but... THIS ISN'T A POINTER! :(
2276 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2277} CYCatch return /*XXX*/ NULL; }
2278
2279static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2280 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2281 return NULL;
2282
2283 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2284
2285 id value(internal->GetValue());
2286 if (value == nil)
2287 return CYCastJSValue(context, "nil");
2288
2289 CYPoolTry {
2290 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2291 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2292 } CYPoolCatch(NULL)
2293} CYCatch return /*XXX*/ NULL; }
2294
2295static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2296 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2297 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2298} CYCatch }
2299
2300static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2301 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2302}
2303
2304static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2305 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2306 const char *name(sel_getName(internal->GetValue()));
2307
2308 CYPoolTry {
2309 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2310 return CYCastJSValue(context, CYJSString(context, string));
2311 } CYPoolCatch(NULL)
2312} CYCatch return /*XXX*/ NULL; }
2313
2314static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2315 if (count != 1)
2316 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2317
2318 CYPool pool;
2319 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2320 SEL sel(internal->GetValue());
2321
2322 objc_method *method;
2323 if (Class _class = CYCastClass(pool, context, arguments[0]))
2324 method = class_getInstanceMethod(_class, sel);
2325 else
2326 method = NULL;
2327
2328 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2329 return CYCastJSValue(context, CYJSString(type));
2330
2331 return CYJSNull(context);
2332} CYCatch }
2333
2334static JSStaticValue Selector_staticValues[2] = {
2335 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2336 {NULL, NULL, NULL, 0}
2337};
2338
2339static JSStaticValue Instance_staticValues[5] = {
2340 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2341 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2342 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2343 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2344 {NULL, NULL, NULL, 0}
2345};
2346
2347static JSStaticFunction Instance_staticFunctions[6] = {
2348 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2349 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2350 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2351 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2352 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2353 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2354 {NULL, NULL, 0}
2355};
2356
2357static JSStaticFunction Internal_staticFunctions[2] = {
2358 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2359 {NULL, NULL, 0}
2360};
2361
2362static JSStaticFunction Selector_staticFunctions[5] = {
2363 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2364 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2365 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2366 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2367 {NULL, NULL, 0}
2368};
2369
2370static JSStaticFunction StringInstance_staticFunctions[2] = {
2371 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2372 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2373 {NULL, NULL, 0}
2374};
2375
2376void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2377 apr_pool_t *pool(CYGetGlobalPool());
2378
2379 Object_type = new(pool) Type_privateData("@");
2380 Selector_type = new(pool) Type_privateData(":");
2381
2382#ifdef __APPLE__
2383 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2384 NSCFType_ = objc_getClass("NSCFType");
2385 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2386 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2387 NSZombie_ = objc_getClass("_NSZombie_");
2388#else
2389 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2390#endif
2391
2392 NSArray_ = objc_getClass("NSArray");
2393 NSDictionary_ = objc_getClass("NSDictionary");
2394 NSString_ = objc_getClass("NSString");
2395 Object_ = objc_getClass("Object");
2396
2397 JSClassDefinition definition;
2398
2399 definition = kJSClassDefinitionEmpty;
2400 definition.className = "Instance";
2401 definition.staticValues = Instance_staticValues;
2402 definition.staticFunctions = Instance_staticFunctions;
2403 definition.hasProperty = &Instance_hasProperty;
2404 definition.getProperty = &Instance_getProperty;
2405 definition.setProperty = &Instance_setProperty;
2406 definition.deleteProperty = &Instance_deleteProperty;
2407 definition.getPropertyNames = &Instance_getPropertyNames;
2408 definition.callAsConstructor = &Instance_callAsConstructor;
2409 definition.hasInstance = &Instance_hasInstance;
2410 definition.finalize = &CYFinalize;
2411 Instance_ = JSClassCreate(&definition);
2412
2413 definition = kJSClassDefinitionEmpty;
2414 definition.className = "Internal";
2415 definition.staticFunctions = Internal_staticFunctions;
2416 definition.hasProperty = &Internal_hasProperty;
2417 definition.getProperty = &Internal_getProperty;
2418 definition.setProperty = &Internal_setProperty;
2419 definition.getPropertyNames = &Internal_getPropertyNames;
2420 definition.finalize = &CYFinalize;
2421 Internal_ = JSClassCreate(&definition);
2422
2423 definition = kJSClassDefinitionEmpty;
2424 definition.className = "Message";
2425 definition.staticFunctions = cy::Functor::StaticFunctions;
2426 definition.callAsFunction = &Message_callAsFunction;
2427 definition.finalize = &CYFinalize;
2428 Message_ = JSClassCreate(&definition);
2429
2430 definition = kJSClassDefinitionEmpty;
2431 definition.className = "Messages";
2432 definition.hasProperty = &Messages_hasProperty;
2433 definition.getProperty = &Messages_getProperty;
2434 definition.setProperty = &Messages_setProperty;
2435#if 0 && OBJC_API_VERSION < 2
2436 definition.deleteProperty = &Messages_deleteProperty;
2437#endif
2438 definition.getPropertyNames = &Messages_getPropertyNames;
2439 definition.finalize = &CYFinalize;
2440 Messages_ = JSClassCreate(&definition);
2441
2442 definition = kJSClassDefinitionEmpty;
2443 definition.className = "Selector";
2444 definition.staticValues = Selector_staticValues;
2445 definition.staticFunctions = Selector_staticFunctions;
2446 definition.callAsFunction = &Selector_callAsFunction;
2447 definition.finalize = &CYFinalize;
2448 Selector_ = JSClassCreate(&definition);
2449
2450 definition = kJSClassDefinitionEmpty;
2451 definition.className = "StringInstance";
2452 definition.staticFunctions = StringInstance_staticFunctions;
2453 StringInstance_ = JSClassCreate(&definition);
2454
2455 definition = kJSClassDefinitionEmpty;
2456 definition.className = "Super";
2457 definition.staticFunctions = Internal_staticFunctions;
2458 definition.finalize = &CYFinalize;
2459 Super_ = JSClassCreate(&definition);
2460
2461 definition = kJSClassDefinitionEmpty;
2462 definition.className = "ObjectiveC::Classes";
2463 definition.getProperty = &ObjectiveC_Classes_getProperty;
2464 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2465 ObjectiveC_Classes_ = JSClassCreate(&definition);
2466
2467#if OBJC_API_VERSION >= 2
2468 definition = kJSClassDefinitionEmpty;
2469 definition.className = "ObjectiveC::Images";
2470 definition.getProperty = &ObjectiveC_Images_getProperty;
2471 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2472 ObjectiveC_Images_ = JSClassCreate(&definition);
2473
2474 definition = kJSClassDefinitionEmpty;
2475 definition.className = "ObjectiveC::Image::Classes";
2476 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2477 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2478 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2479#endif
2480
2481 definition = kJSClassDefinitionEmpty;
2482 definition.className = "ObjectiveC::Protocols";
2483 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2484 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2485 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2486
2487#if defined(__APPLE__) && defined(__arm__) && 0
2488 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2489#endif
2490
2491#ifdef __APPLE__
2492 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2493#endif
2494} CYPoolCatch() }
2495
2496void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2497 JSObjectRef global(CYGetGlobalObject(context));
2498 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2499 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2500 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2501
2502 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2503 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2504
2505 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2506 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2507
2508#if OBJC_API_VERSION >= 2
2509 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2510#endif
2511
2512 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2513 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2514 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2515 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2516 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2517
2518 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2519 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2520
2521 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2522 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2523
2524 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2525 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2526
2527 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2528 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2529 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2530
2531#if defined(__APPLE__) && defined(__arm__) && 0
2532 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2533#endif
2534
2535 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2536
2537 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2538 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2539 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2540} CYPoolCatch() }
2541
2542static CYHooks CYObjectiveCHooks = {
2543 &CYObjectiveC_ExecuteStart,
2544 &CYObjectiveC_ExecuteEnd,
2545 &CYObjectiveC_RuntimeProperty,
2546 &CYObjectiveC_CallFunction,
2547 &CYObjectiveC_Initialize,
2548 &CYObjectiveC_SetupContext,
2549 &CYObjectiveC_PoolFFI,
2550 &CYObjectiveC_FromFFI,
2551};
2552
2553struct CYObjectiveC {
2554 CYObjectiveC() {
2555 hooks_ = &CYObjectiveCHooks;
2556 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2557 _assert(hooks_ != NULL);
2558 }
2559} CYObjectiveC;