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