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