]> git.saurik.com Git - cycript.git/blob - ObjectiveC/Library.mm
Make Instance() consistent with "no nil Instance".
[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 // XXX: maybe move this id check into Decode's implementation for block_P
865 _assert(signature->count >= 2);
866 _assert(signature->elements[1].type->primitive == sig::object_P);
867
868 sig::Type type;
869 type.name = NULL;
870 type.flags = 0;
871
872 type.primitive = sig::function_P; // XXX: sig::block_P
873 sig::Copy(pool, type.data.signature, *signature);
874
875 CYTypedIdentifier *typed((new(pool) CYTypeExpression(Decode(pool, &type)))->typed_);
876 CYTypeFunctionWith *function(typed->Function());
877 _assert(function != NULL);
878
879 _assert(function->parameters_ != NULL);
880 CYObjCBlock *block(new(pool) CYObjCBlock(typed, function->parameters_->next_, NULL));
881
882 std::ostringstream str;
883 CYOptions options;
884 CYOutput out(*str.rdbuf(), options);
885 block->Output(out, CYNoFlags);
886
887 std::string value(str.str());
888 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
889 }
890
891 @end
892 #endif
893 /* }}} */
894 /* Bridge: NSBoolNumber {{{ */
895 #ifndef __APPLE__
896 @implementation NSBoolNumber (Cycript)
897
898 - (JSType) cy$JSType {
899 return kJSTypeBoolean;
900 }
901
902 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
903 NSString *value([self boolValue] ? @"true" : @"false");
904 return objective ? value : [NSString stringWithFormat:@"@%@", value];
905 }
906
907 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
908 return CYCastJSValue(context, (bool) [self boolValue]);
909 } CYObjectiveCatch }
910
911 @end
912 #endif
913 /* }}} */
914 /* Bridge: NSDictionary {{{ */
915 @implementation NSDictionary (Cycript)
916
917 - (id) cy$box {
918 return [[self mutableCopy] autorelease];
919 }
920
921 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
922 _oassert(objects.insert(self).second);
923
924 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
925 [json appendString:@"@{"];
926
927 bool comma(false);
928 #ifdef __clang__
929 for (NSObject *key in self) {
930 #else
931 NSEnumerator *keys([self keyEnumerator]);
932 while (NSObject *key = [keys nextObject]) {
933 #endif
934 if (comma)
935 [json appendString:@","];
936 else
937 comma = true;
938 [json appendString:CYCastNSCYON(key, true, objects)];
939 [json appendString:@":"];
940 NSObject *object([self objectForKey:key]);
941 [json appendString:CYCastNSCYON(object, true, objects)];
942 }
943
944 [json appendString:@"}"];
945 return json;
946 }
947
948 - (bool) cy$hasProperty:(NSString *)name {
949 return [self objectForKey:name] != nil;
950 }
951
952 - (NSObject *) cy$getProperty:(NSString *)name {
953 return [self objectForKey:name];
954 }
955
956 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
957 [super cy$getPropertyNames:names inContext:context];
958
959 #ifdef __clang__
960 for (NSObject *key in self) {
961 #else
962 NSEnumerator *keys([self keyEnumerator]);
963 while (NSObject *key = [keys nextObject]) {
964 #endif
965 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
966 }
967 }
968
969 + (bool) cy$hasImplicitProperties {
970 return false;
971 }
972
973 @end
974 /* }}} */
975 /* Bridge: NSMutableArray {{{ */
976 @implementation NSMutableArray (Cycript)
977
978 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
979 if ([name isEqualToString:@"length"]) {
980 // XXX: is this not intelligent?
981 NSNumber *number(reinterpret_cast<NSNumber *>(value));
982 NSUInteger size([number unsignedIntegerValue]);
983 NSUInteger count([self count]);
984 if (size < count)
985 [self removeObjectsInRange:NSMakeRange(size, count - size)];
986 else if (size != count) {
987 WebUndefined *undefined([WebUndefined undefined]);
988 for (size_t i(count); i != size; ++i)
989 [self addObject:undefined];
990 }
991 return true;
992 }
993
994 size_t index(CYGetIndex(name));
995 if (index == _not(size_t))
996 return [super cy$setProperty:name to:value];
997
998 id object(value ?: [NSNull null]);
999
1000 size_t count([self count]);
1001 if (index < count)
1002 [self replaceObjectAtIndex:index withObject:object];
1003 else {
1004 if (index != count) {
1005 WebUndefined *undefined([WebUndefined undefined]);
1006 for (size_t i(count); i != index; ++i)
1007 [self addObject:undefined];
1008 }
1009
1010 [self addObject:object];
1011 }
1012
1013 return true;
1014 }
1015
1016 - (bool) cy$deleteProperty:(NSString *)name {
1017 size_t index(CYGetIndex(name));
1018 if (index == _not(size_t) || index >= [self count])
1019 return [super cy$deleteProperty:name];
1020 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1021 return true;
1022 }
1023
1024 @end
1025 /* }}} */
1026 /* Bridge: NSMutableDictionary {{{ */
1027 @implementation NSMutableDictionary (Cycript)
1028
1029 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1030 [self setObject:(value ?: [NSNull null]) forKey:name];
1031 return true;
1032 }
1033
1034 - (bool) cy$deleteProperty:(NSString *)name {
1035 if ([self objectForKey:name] == nil)
1036 return false;
1037 else {
1038 [self removeObjectForKey:name];
1039 return true;
1040 }
1041 }
1042
1043 @end
1044 /* }}} */
1045 /* Bridge: NSNumber {{{ */
1046 @implementation NSNumber (Cycript)
1047
1048 - (JSType) cy$JSType {
1049 #ifdef __APPLE__
1050 // XXX: this just seems stupid
1051 if ([self class] == NSCFBoolean_)
1052 return kJSTypeBoolean;
1053 #endif
1054 return kJSTypeNumber;
1055 }
1056
1057 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1058 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1059 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1060 }
1061
1062 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1063 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1064 } CYObjectiveCatch }
1065
1066 @end
1067 /* }}} */
1068 /* Bridge: NSNull {{{ */
1069 @implementation NSNull (Cycript)
1070
1071 - (JSType) cy$JSType {
1072 return kJSTypeNull;
1073 }
1074
1075 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1076 NSString *value(@"null");
1077 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1078 }
1079
1080 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1081 return CYJSNull(context);
1082 } CYObjectiveCatch }
1083
1084 @end
1085 /* }}} */
1086 /* Bridge: NSObject {{{ */
1087 @implementation NSObject (Cycript)
1088
1089 - (id) cy$box {
1090 return self;
1091 }
1092
1093 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1094 return [self cy$valueOfInContext:context];
1095 }
1096
1097 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1098 return NULL;
1099 } CYObjectiveCatch }
1100
1101 - (JSType) cy$JSType {
1102 return kJSTypeObject;
1103 }
1104
1105 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1106 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1107 }
1108
1109 - (bool) cy$hasProperty:(NSString *)name {
1110 return false;
1111 }
1112
1113 - (NSObject *) cy$getProperty:(NSString *)name {
1114 return nil;
1115 }
1116
1117 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1118 if (NSObject *value = [self cy$getProperty:name])
1119 return CYCastJSValue(context, value);
1120 return NULL;
1121 } CYObjectiveCatch }
1122
1123 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1124 return false;
1125 }
1126
1127 - (bool) cy$deleteProperty:(NSString *)name {
1128 return false;
1129 }
1130
1131 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1132 }
1133
1134 + (bool) cy$hasImplicitProperties {
1135 return true;
1136 }
1137
1138 @end
1139 /* }}} */
1140 /* Bridge: NSOrderedSet {{{ */
1141 #ifdef __APPLE__
1142 @implementation NSOrderedSet (Cycript)
1143
1144 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1145 _oassert(objects.insert(self).second);
1146
1147 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1148 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1149 [json appendString:CYCastNSCYON([self array], true, objects)];
1150 [json appendString:@"]]"];
1151 return json;
1152 }
1153
1154 @end
1155 #endif
1156 /* }}} */
1157 /* Bridge: NSProxy {{{ */
1158 @implementation NSProxy (Cycript)
1159
1160 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1161 return [[self description] cy$toCYON:objective inSet:objects];
1162 }
1163
1164 @end
1165 /* }}} */
1166 /* Bridge: NSSet {{{ */
1167 @implementation NSSet (Cycript)
1168
1169 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1170 _oassert(objects.insert(self).second);
1171
1172 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1173 [json appendString:@"[NSSet setWithArray:"];
1174 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1175 [json appendString:@"]]"];
1176 return json;
1177 }
1178
1179 @end
1180 /* }}} */
1181 /* Bridge: NSString {{{ */
1182 @implementation NSString (Cycript)
1183
1184 - (id) cy$box {
1185 return [[self copy] autorelease];
1186 }
1187
1188 - (JSType) cy$JSType {
1189 return kJSTypeString;
1190 }
1191
1192 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1193 std::ostringstream str;
1194 if (!objective)
1195 str << '@';
1196 CYUTF8String string(CYCastUTF8String(self));
1197 CYStringify(str, string.data, string.size, true);
1198 std::string value(str.str());
1199 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1200 }
1201
1202 - (bool) cy$hasProperty:(NSString *)name {
1203 size_t index(CYGetIndex(name));
1204 if (index == _not(size_t) || index >= [self length])
1205 return [super cy$hasProperty:name];
1206 else
1207 return true;
1208 }
1209
1210 - (NSObject *) cy$getProperty:(NSString *)name {
1211 size_t index(CYGetIndex(name));
1212 if (index == _not(size_t) || index >= [self length])
1213 return [super cy$getProperty:name];
1214 else
1215 return [self substringWithRange:NSMakeRange(index, 1)];
1216 }
1217
1218 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1219 [super cy$getPropertyNames:names inContext:context];
1220
1221 for (size_t index(0), length([self length]); index != length; ++index) {
1222 char name[32];
1223 sprintf(name, "%zu", index);
1224 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1225 }
1226 }
1227
1228 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1229 return CYCastJSValue(context, CYJSString(context, self));
1230 } CYObjectiveCatch }
1231
1232 @end
1233 /* }}} */
1234 /* Bridge: WebUndefined {{{ */
1235 @implementation WebUndefined (Cycript)
1236
1237 - (JSType) cy$JSType {
1238 return kJSTypeUndefined;
1239 }
1240
1241 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1242 NSString *value(@"undefined");
1243 return value; // XXX: maybe use the below code, adding @undefined?
1244 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1245 }
1246
1247 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1248 return CYJSUndefined(context);
1249 } CYObjectiveCatch }
1250
1251 @end
1252 /* }}} */
1253
1254 static bool CYIsClass(id self) {
1255 return class_isMetaClass(object_getClass(self));
1256 }
1257
1258 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1259 id self(CYCastNSObject(&pool, context, value));
1260 if (CYIsClass(self))
1261 return (Class) self;
1262 throw CYJSError(context, "got something that is not a Class");
1263 return NULL;
1264 }
1265
1266 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1267 CYPool pool;
1268 size_t size(JSPropertyNameArrayGetCount(names));
1269 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1270 for (size_t index(0); index != size; ++index)
1271 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1272 return array;
1273 }
1274
1275 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1276 if (value == nil)
1277 return CYJSNull(context);
1278 else
1279 return CYMakeInstance(context, value);
1280 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1281
1282 @implementation CYJSObject
1283
1284 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1285 if ((self = [super init]) != nil) {
1286 object_ = object;
1287 context_ = CYGetJSContext(context);
1288 JSGlobalContextRetain(context_);
1289 JSValueProtect(context_, object_);
1290 } return self;
1291 } CYObjectiveCatch }
1292
1293 - (void) dealloc { CYObjectiveTry {
1294 JSValueUnprotect(context_, object_);
1295 JSGlobalContextRelease(context_);
1296 [super dealloc];
1297 } CYObjectiveCatch }
1298
1299 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1300 CYPool pool;
1301 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1302 if (cyon == NULL)
1303 return [super cy$toCYON:objective inSet:objects];
1304 else
1305 return [NSString stringWithUTF8String:cyon];
1306 } CYObjectiveCatch }
1307
1308 - (NSUInteger) count { CYObjectiveTry {
1309 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1310 size_t size(JSPropertyNameArrayGetCount(names));
1311 JSPropertyNameArrayRelease(names);
1312 return size;
1313 } CYObjectiveCatch }
1314
1315 - (id) objectForKey:(id)key { CYObjectiveTry {
1316 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1317 if (JSValueIsUndefined(context, value))
1318 return nil;
1319 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1320 } CYObjectiveCatch }
1321
1322 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1323 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1324 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1325 JSPropertyNameArrayRelease(names);
1326 return enumerator;
1327 } CYObjectiveCatch }
1328
1329 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1330 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1331 } CYObjectiveCatch }
1332
1333 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1334 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1335 } CYObjectiveCatch }
1336
1337 @end
1338
1339 @implementation CYJSArray
1340
1341 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1342 CYPool pool;
1343 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1344 } CYObjectiveCatch }
1345
1346 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1347 if ((self = [super init]) != nil) {
1348 object_ = object;
1349 context_ = CYGetJSContext(context);
1350 JSGlobalContextRetain(context_);
1351 JSValueProtect(context_, object_);
1352 } return self;
1353 } CYObjectiveCatch }
1354
1355 - (void) dealloc { CYObjectiveTry {
1356 JSValueUnprotect(context_, object_);
1357 JSGlobalContextRelease(context_);
1358 [super dealloc];
1359 } CYObjectiveCatch }
1360
1361 - (NSUInteger) count { CYObjectiveTry {
1362 return CYArrayLength(context, object_);
1363 } CYObjectiveCatch }
1364
1365 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1366 size_t bounds([self count]);
1367 if (index >= bounds)
1368 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1369 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1370 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1371 } CYObjectiveCatch }
1372
1373 - (void) addObject:(id)object { CYObjectiveTry {
1374 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1375 } CYObjectiveCatch }
1376
1377 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1378 size_t bounds([self count] + 1);
1379 if (index >= bounds)
1380 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1381 JSValueRef arguments[3];
1382 arguments[0] = CYCastJSValue(context, index);
1383 arguments[1] = CYCastJSValue(context, 0);
1384 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1385 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1386 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1387 } CYObjectiveCatch }
1388
1389 - (void) removeLastObject { CYObjectiveTry {
1390 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1391 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1392 } CYObjectiveCatch }
1393
1394 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1395 size_t bounds([self count]);
1396 if (index >= bounds)
1397 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1398 JSValueRef arguments[2];
1399 arguments[0] = CYCastJSValue(context, index);
1400 arguments[1] = CYCastJSValue(context, 1);
1401 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1402 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1403 } CYObjectiveCatch }
1404
1405 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1406 size_t bounds([self count]);
1407 if (index >= bounds)
1408 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1409 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1410 } CYObjectiveCatch }
1411
1412 @end
1413
1414 // XXX: inherit from or replace with CYJSObject
1415 @interface CYInternal : NSObject {
1416 JSGlobalContextRef context_;
1417 JSObjectRef object_;
1418 }
1419
1420 @end
1421
1422 @implementation CYInternal
1423
1424 - (void) dealloc { CYObjectiveTry {
1425 JSValueUnprotect(context_, object_);
1426 JSGlobalContextRelease(context_);
1427 [super dealloc];
1428 } CYObjectiveCatch }
1429
1430 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1431 if ((self = [super init]) != nil) {
1432 context_ = CYGetJSContext(context);
1433 JSGlobalContextRetain(context_);
1434 } return self;
1435 } CYObjectiveCatch }
1436
1437 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1438 if (object_ == NULL)
1439 return false;
1440
1441 return JSObjectHasProperty(context, object_, name);
1442 }
1443
1444 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1445 if (object_ == NULL)
1446 return NULL;
1447
1448 return CYGetProperty(context, object_, name);
1449 }
1450
1451 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1452 @synchronized (self) {
1453 if (object_ == NULL) {
1454 object_ = JSObjectMake(context, NULL, NULL);
1455 JSValueProtect(context, object_);
1456 }
1457 }
1458
1459 CYSetProperty(context, object_, name, value);
1460 }
1461
1462 + (CYInternal *) get:(id)object {
1463 #ifdef __APPLE__
1464 if (&objc_getAssociatedObject == NULL)
1465 return nil;
1466
1467 @synchronized (object) {
1468 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1469 return internal;
1470 }
1471 #endif
1472
1473 return nil;
1474 }
1475
1476 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1477 #ifdef __APPLE__
1478 if (&objc_getAssociatedObject == NULL)
1479 return nil;
1480
1481 @synchronized (object) {
1482 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1483 return internal;
1484
1485 if (&objc_setAssociatedObject == NULL)
1486 return nil;
1487
1488 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1489 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1490 return internal;
1491 }
1492 #endif
1493
1494 return nil;
1495 }
1496
1497 @end
1498
1499 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1500 Selector_privateData *internal(new Selector_privateData(sel));
1501 return JSObjectMake(context, Selector_, internal);
1502 }
1503
1504 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1505 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1506 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1507 return reinterpret_cast<SEL>(internal->value_);
1508 } else {
1509 CYPool pool;
1510 return sel_registerName(CYPoolCString(pool, context, value));
1511 }
1512 }
1513
1514 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1515 return (void *) [[NSAutoreleasePool alloc] init];
1516 } CYSadCatch(NULL) }
1517
1518 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1519 return [(NSAutoreleasePool *) handle release];
1520 } CYSadCatch() }
1521
1522 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1523 CYCallFunction(pool, context, cif, function, value, values);
1524 } CYSadCatch() }
1525
1526 #ifdef __APPLE__
1527 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, sig::Signature *signature) {
1528 if (JSValueIsNull(context, value))
1529 return nil;
1530 JSObjectRef object(CYCastJSObject(context, value));
1531
1532 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1533 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1534
1535 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1536 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1537 return nil;
1538 }
1539
1540 _assert(JSObjectIsFunction(context, object));
1541
1542 _assert(signature != NULL);
1543 _assert(signature->count != 0);
1544
1545 sig::Signature modified;
1546 modified.count = signature->count + 1;
1547 modified.elements = new(pool) sig::Element[modified.count];
1548
1549 modified.elements[0] = signature->elements[0];
1550 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1551
1552 modified.elements[1].name = NULL;
1553 modified.elements[1].type = new(pool) sig::Type();
1554 modified.elements[1].offset = _not(size_t);
1555
1556 memset(modified.elements[1].type, 0, sizeof(sig::Type));
1557 modified.elements[1].type->primitive = sig::object_P;
1558
1559 return CYMakeBlock(context, object, modified);
1560 }
1561 #endif
1562
1563 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1564 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1565
1566 switch (type->primitive) {
1567 #ifdef __APPLE__
1568 case sig::block_P:
1569 // XXX: this function might not handle the idea of a null pool
1570 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &type->data.signature);
1571 break;
1572 #endif
1573
1574 case sig::object_P:
1575 case sig::typename_P:
1576 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1577 break;
1578
1579 case sig::selector_P:
1580 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1581 break;
1582
1583 default:
1584 return false;
1585 }
1586
1587 return true;
1588 } CYSadCatch(false) }
1589
1590 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1591 switch (type->primitive) {
1592 // XXX: do something epic about blocks
1593 case sig::block_P:
1594 case sig::object_P:
1595 if (NSObject *value = *reinterpret_cast<NSObject **>(data)) {
1596 JSObjectRef object(CYMakeInstance(context, value));
1597
1598 if (initialize) {
1599 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1600
1601 if ((internal->flags_ & Instance::Uninitialized) != 0) {
1602 internal->flags_ = static_cast<Instance::Flags>(internal->flags_ & ~Instance::Uninitialized);
1603 _assert(internal->value_ == nil);
1604 internal->value_ = value;
1605 }
1606
1607 [value release];
1608 }
1609
1610 return object;
1611 } else goto null;
1612
1613 case sig::typename_P:
1614 if (Class value = *reinterpret_cast<Class *>(data))
1615 return CYMakeInstance(context, value, Instance::Permanent);
1616 else goto null;
1617
1618 case sig::selector_P:
1619 if (SEL value = *reinterpret_cast<SEL *>(data))
1620 return CYMakeSelector(context, value);
1621 else goto null;
1622
1623 null:
1624 return CYJSNull(context);
1625 default:
1626 return NULL;
1627 }
1628 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1629
1630 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1631 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1632 if (!devoid)
1633 return true;
1634 char type[16];
1635 method_getReturnType(method, type, sizeof(type));
1636 if (type[0] != 'v')
1637 return true;
1638 }
1639
1640 // XXX: possibly use a more "awesome" check?
1641 return false;
1642 }
1643
1644 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1645 JSObjectRef _this(CYCastJSObject(context, values[0]));
1646 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1647 }
1648
1649 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1650 Message_privateData *internal(new Message_privateData(sel, type, imp));
1651 return JSObjectMake(context, Message_, internal);
1652 }
1653
1654 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1655 JSObjectRef function(CYCastJSObject(context, value));
1656 CYPool pool;
1657 sig::Signature signature;
1658 sig::Parse(pool, &signature, encoding, &Structor_);
1659 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1660 // XXX: see notes in Library.cpp about needing to leak
1661 return reinterpret_cast<IMP>(internal->GetValue());
1662 }
1663
1664 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
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 (class_getInstanceMethod(_class, sel) != NULL)
1673 return true;
1674
1675 return false;
1676 }
1677
1678 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, 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
1685 if (SEL sel = sel_getUid(name))
1686 if (objc_method *method = class_getInstanceMethod(_class, sel))
1687 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1688
1689 return NULL;
1690 } CYCatch(NULL) }
1691
1692 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1693 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1694 Class _class(internal->GetValue());
1695
1696 CYPool pool;
1697 const char *name(CYPoolCString(pool, context, property));
1698 SEL sel(sel_registerName(name));
1699
1700 const char *type;
1701 IMP imp;
1702
1703 if (JSValueIsObjectOfClass(context, value, Message_)) {
1704 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1705 type = sig::Unparse(pool, &message->signature_);
1706 imp = reinterpret_cast<IMP>(message->GetValue());
1707 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1708 type = method_getTypeEncoding(method);
1709 imp = CYMakeMessage(context, value, type);
1710 } else _assert(false);
1711
1712 objc_method *method(NULL);
1713 unsigned int size;
1714 objc_method **methods(class_copyMethodList(_class, &size));
1715 for (size_t i(0); i != size; ++i)
1716 if (sel_isEqual(method_getName(methods[i]), sel)) {
1717 method = methods[i];
1718 break;
1719 }
1720 free(methods);
1721
1722 if (method != NULL)
1723 method_setImplementation(method, imp);
1724 else
1725 class_addMethod(_class, sel, imp, type);
1726
1727 return true;
1728 } CYCatch(false) }
1729
1730 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1731 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1732 Class _class(internal->GetValue());
1733
1734 unsigned int size;
1735 objc_method **data(class_copyMethodList(_class, &size));
1736 for (size_t i(0); i != size; ++i)
1737 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1738 free(data);
1739 }
1740
1741 static bool CYHasImplicitProperties(Class _class) {
1742 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1743 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1744 return true;
1745 return [_class cy$hasImplicitProperties];
1746 }
1747
1748 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1749 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1750 id self(internal->GetValue());
1751
1752 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1753 return true;
1754
1755 CYPool pool;
1756 NSString *name(CYCastNSString(&pool, context, property));
1757
1758 if (CYInternal *internal = [CYInternal get:self])
1759 if ([internal hasProperty:property inContext:context])
1760 return true;
1761
1762 Class _class(object_getClass(self));
1763
1764 CYPoolTry {
1765 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1766 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1767 if ([self cy$hasProperty:name])
1768 return true;
1769 } CYPoolCatch(false)
1770
1771 const char *string(CYPoolCString(pool, context, name));
1772
1773 if (class_getProperty(_class, string) != NULL)
1774 return true;
1775
1776 if (CYHasImplicitProperties(_class))
1777 if (SEL sel = sel_getUid(string))
1778 if (CYImplements(self, _class, sel, true))
1779 return true;
1780
1781 return false;
1782 }
1783
1784 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1785 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1786 id self(internal->GetValue());
1787
1788 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1789 return Internal::Make(context, self, object);
1790
1791 CYPool pool;
1792 NSString *name(CYCastNSString(&pool, context, property));
1793
1794 if (CYInternal *internal = [CYInternal get:self])
1795 if (JSValueRef value = [internal getProperty:property inContext:context])
1796 return value;
1797
1798 CYPoolTry {
1799 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1800 return value;
1801 } CYPoolCatch(NULL)
1802
1803 const char *string(CYPoolCString(pool, context, name));
1804 Class _class(object_getClass(self));
1805
1806 if (objc_property_t property = class_getProperty(_class, string)) {
1807 PropertyAttributes attributes(property);
1808 SEL sel(sel_registerName(attributes.Getter()));
1809 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1810 }
1811
1812 if (CYHasImplicitProperties(_class))
1813 if (SEL sel = sel_getUid(string))
1814 if (CYImplements(self, _class, sel, true))
1815 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1816
1817 return NULL;
1818 } CYCatch(NULL) }
1819
1820 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1821 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1822 id self(internal->GetValue());
1823
1824 CYPool pool;
1825
1826 NSString *name(CYCastNSString(&pool, context, property));
1827 NSObject *data(CYCastNSObject(&pool, context, value));
1828
1829 CYPoolTry {
1830 if ([self cy$setProperty:name to:data])
1831 return true;
1832 } CYPoolCatch(false)
1833
1834 const char *string(CYPoolCString(pool, context, name));
1835 Class _class(object_getClass(self));
1836
1837 if (objc_property_t property = class_getProperty(_class, string)) {
1838 PropertyAttributes attributes(property);
1839 if (const char *setter = attributes.Setter()) {
1840 SEL sel(sel_registerName(setter));
1841 JSValueRef arguments[1] = {value};
1842 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1843 return true;
1844 }
1845 }
1846
1847 size_t length(strlen(string));
1848
1849 char set[length + 5];
1850
1851 set[0] = 's';
1852 set[1] = 'e';
1853 set[2] = 't';
1854
1855 if (string[0] != '\0') {
1856 set[3] = toupper(string[0]);
1857 memcpy(set + 4, string + 1, length - 1);
1858 }
1859
1860 set[length + 3] = ':';
1861 set[length + 4] = '\0';
1862
1863 if (SEL sel = sel_getUid(set))
1864 if (CYImplements(self, _class, sel)) {
1865 JSValueRef arguments[1] = {value};
1866 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1867 return true;
1868 }
1869
1870 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1871 [internal setProperty:property toValue:value inContext:context];
1872 return true;
1873 }
1874
1875 return false;
1876 } CYCatch(false) }
1877
1878 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1879 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1880 id self(internal->GetValue());
1881
1882 CYPoolTry {
1883 NSString *name(CYCastNSString(NULL, context, property));
1884 return [self cy$deleteProperty:name];
1885 } CYPoolCatch(false)
1886 } CYCatch(false) return /*XXX*/ false; }
1887
1888 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1889 const char *name(sel_getName(method_getName(method)));
1890 if (strchr(name, ':') != NULL)
1891 return;
1892
1893 const char *type(method_getTypeEncoding(method));
1894 if (type == NULL || *type == '\0' || *type == 'v')
1895 return;
1896
1897 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1898 }
1899
1900 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1901 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1902 id self(internal->GetValue());
1903
1904 CYPool pool;
1905 Class _class(object_getClass(self));
1906
1907 {
1908 unsigned int size;
1909 objc_property_t *data(class_copyPropertyList(_class, &size));
1910 for (size_t i(0); i != size; ++i)
1911 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1912 free(data);
1913 }
1914
1915 if (CYHasImplicitProperties(_class))
1916 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1917 unsigned int size;
1918 objc_method **data(class_copyMethodList(current, &size));
1919 for (size_t i(0); i != size; ++i)
1920 Instance_getPropertyNames_message(names, data[i]);
1921 free(data);
1922 }
1923
1924 CYPoolTry {
1925 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1926 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1927 [self cy$getPropertyNames:names inContext:context];
1928 } CYPoolCatch()
1929 }
1930
1931 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1932 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1933 JSObjectRef value(CYMakeInstance(context, [internal->GetValue() alloc], Instance::Uninitialized));
1934 return value;
1935 } CYCatch(NULL) }
1936
1937 static const char *CYBlockEncoding(NSBlock *self) {
1938 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1939 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1940 return NULL;
1941 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1942 descriptor += sizeof(BlockDescriptor1);
1943 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1944 descriptor += sizeof(BlockDescriptor2);
1945 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1946 return descriptor3->signature;
1947 }
1948
1949 static sig::Signature *CYBlockSignature(CYPool &pool, NSBlock *self) {
1950 const char *encoding(CYBlockEncoding(self));
1951 if (encoding == NULL)
1952 return NULL;
1953 // XXX: this should be stored on a FunctionInstance private value subclass
1954 sig::Signature *signature(new(pool) sig::Signature());
1955 sig::Parse(pool, signature, encoding, &Structor_);
1956 return signature;
1957 }
1958
1959 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1960 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1961 id self(internal->GetValue());
1962
1963 if (const char *encoding = CYBlockEncoding(self)) {
1964 CYPool pool;
1965
1966 void *setup[1];
1967 setup[0] = &self;
1968
1969 sig::Signature signature;
1970 sig::Parse(pool, &signature, encoding, &Structor_);
1971
1972 ffi_cif cif;
1973 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1974
1975 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1976 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1977 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1978 }
1979
1980 if (count != 0)
1981 CYThrow("NSBlock without signature field passed arguments");
1982
1983 CYPoolTry {
1984 [self invoke];
1985 } CYPoolCatch(NULL);
1986
1987 return NULL;
1988 } CYCatch(NULL) }
1989
1990 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1991 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1992 Class _class(internal->GetValue());
1993 if (!CYIsClass(_class))
1994 return false;
1995
1996 if (CYJSValueIsNSObject(context, instance)) {
1997 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1998 // XXX: this isn't always safe
1999 return [linternal->GetValue() isKindOfClass:_class];
2000 }
2001
2002 return false;
2003 } CYCatch(false) }
2004
2005 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2006 if (count == 0)
2007 throw CYJSError(context, "incorrect number of arguments to Instance");
2008 CYPool pool;
2009 id value(CYCastNSObject(&pool, context, arguments[0]));
2010 if (value == nil)
2011 value = [NSNull null];
2012 return CYCastJSValue(context, [value cy$box]);
2013 } CYCatch(NULL) }
2014
2015 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2016 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2017 CYPool pool;
2018
2019 id self(internal->GetValue());
2020 const char *name(CYPoolCString(pool, context, property));
2021
2022 if (object_getInstanceVariable(self, name, NULL) != NULL)
2023 return true;
2024
2025 return false;
2026 }
2027
2028 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
2029 length = CYCastDouble(encoding + 1);
2030 shift = 0;
2031
2032 unsigned int size;
2033 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2034 for (size_t i(0); i != size; ++i)
2035 if (ivars[i] == ivar)
2036 break;
2037 else if (ivar_getOffset(ivars[i]) == offset) {
2038 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2039 _assert(encoding != NULL);
2040 _assert(encoding[0] == 'b');
2041 shift += CYCastDouble(encoding + 1);
2042 }
2043 free(ivars);
2044 }
2045
2046 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2047 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2048 CYPool pool;
2049
2050 id self(internal->GetValue());
2051 const char *name(CYPoolCString(pool, context, property));
2052
2053 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2054 ptrdiff_t offset(ivar_getOffset(ivar));
2055 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2056
2057 const char *encoding(ivar_getTypeEncoding(ivar));
2058 _assert(encoding != NULL);
2059 _assert(encoding[0] != '\0');
2060 if (encoding[0] == 'b') {
2061 unsigned length, shift;
2062 CYBitField(length, shift, self, ivar, encoding, offset);
2063 _assert(shift + length <= sizeof(uintptr_t) * 8);
2064 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2065 uintptr_t mask((1 << length) - 1);
2066 return CYCastJSValue(context, (field >> shift) & mask);
2067 } else {
2068 #if defined(__APPLE__) && defined(__LP64__)
2069 // XXX: maybe do even more verifications here
2070 if (strcmp(name, "isa") == 0)
2071 return CYCastJSValue(context, object_getClass(self));
2072 #endif
2073
2074 auto type(new(pool) Type_privateData(encoding));
2075 return CYFromFFI(context, type->type_, type->GetFFI(), data);
2076 }
2077 }
2078
2079 return NULL;
2080 } CYCatch(NULL) }
2081
2082 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2083 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2084 CYPool pool;
2085
2086 id self(internal->GetValue());
2087 const char *name(CYPoolCString(pool, context, property));
2088
2089 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2090 ptrdiff_t offset(ivar_getOffset(ivar));
2091 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2092
2093 const char *encoding(ivar_getTypeEncoding(ivar));
2094 _assert(encoding != NULL);
2095 if (encoding[0] == 'b') {
2096 unsigned length, shift;
2097 CYBitField(length, shift, self, ivar, encoding, offset);
2098 _assert(shift + length <= sizeof(uintptr_t) * 8);
2099 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2100 uintptr_t mask((1 << length) - 1);
2101 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2102 } else {
2103 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2104 CYPoolFFI(&pool, context, type->type_, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2105 return true;
2106 }
2107 }
2108
2109 return false;
2110 } CYCatch(false) }
2111
2112 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2113 if (Class super = class_getSuperclass(_class))
2114 Internal_getPropertyNames_(super, names);
2115
2116 unsigned int size;
2117 objc_ivar **data(class_copyIvarList(_class, &size));
2118 for (size_t i(0); i != size; ++i)
2119 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2120 free(data);
2121 }
2122
2123 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2124 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2125 CYPool pool;
2126
2127 id self(internal->GetValue());
2128 Class _class(object_getClass(self));
2129
2130 Internal_getPropertyNames_(_class, names);
2131 }
2132
2133 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2134 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2135 return internal->GetOwner();
2136 } CYCatch(NULL) }
2137
2138 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2139 CYPool pool;
2140 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2141 }
2142
2143 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2144 CYPool pool;
2145 NSString *name(CYCastNSString(&pool, context, property));
2146 if (Class _class = NSClassFromString(name))
2147 return CYMakeInstance(context, _class, Instance::Permanent);
2148 return NULL;
2149 } CYCatch(NULL) }
2150
2151 static Class *CYCopyClassList(size_t &size) {
2152 size = objc_getClassList(NULL, 0);
2153 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2154
2155 for (;;) {
2156 size_t writ(objc_getClassList(data, size));
2157 if (writ <= size) {
2158 size = writ;
2159 return data;
2160 }
2161
2162 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2163 if (copy == NULL) {
2164 free(data);
2165 return NULL;
2166 }
2167
2168 data = copy;
2169 size = writ;
2170 }
2171 }
2172
2173 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2174 size_t size;
2175 if (Class *data = CYCopyClassList(size)) {
2176 for (size_t i(0); i != size; ++i)
2177 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2178 free(data);
2179 }
2180 }
2181
2182 #ifdef __APPLE__
2183 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2184 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2185
2186 CYPool pool;
2187 const char *name(CYPoolCString(pool, context, property));
2188 unsigned int size;
2189 const char **data(objc_copyClassNamesForImage(internal, &size));
2190 JSValueRef value;
2191 for (size_t i(0); i != size; ++i)
2192 if (strcmp(name, data[i]) == 0) {
2193 if (Class _class = objc_getClass(name)) {
2194 value = CYMakeInstance(context, _class, Instance::Permanent);
2195 goto free;
2196 } else
2197 break;
2198 }
2199 value = NULL;
2200 free:
2201 free(data);
2202 return value;
2203 } CYCatch(NULL) }
2204
2205 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2206 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2207 unsigned int size;
2208 const char **data(objc_copyClassNamesForImage(internal, &size));
2209 for (size_t i(0); i != size; ++i)
2210 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2211 free(data);
2212 }
2213
2214 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2215 CYPool pool;
2216 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2217
2218 unsigned int size;
2219 const char **data(objc_copyImageNames(&size));
2220 pool.atexit(free, data);
2221
2222 for (size_t i(0); i != size; ++i)
2223 if (name == data[i]) {
2224 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2225 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(data[i])));
2226 return value;
2227 }
2228
2229 return NULL;
2230 } CYCatch(NULL) }
2231
2232 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2233 unsigned int size;
2234 const char **data(objc_copyImageNames(&size));
2235 for (size_t i(0); i != size; ++i)
2236 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2237 free(data);
2238 }
2239 #endif
2240
2241 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2242 CYPool pool;
2243 const char *name(CYPoolCString(pool, context, property));
2244 if (Protocol *protocol = objc_getProtocol(name))
2245 return CYMakeInstance(context, protocol, Instance::Permanent);
2246 return NULL;
2247 } CYCatch(NULL) }
2248
2249 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2250 unsigned int size;
2251 Protocol **data(objc_copyProtocolList(&size));
2252 for (size_t i(0); i != size; ++i)
2253 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2254 free(data);
2255 }
2256
2257 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2258 CYPool pool;
2259 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2260 if (name == "nil")
2261 return CYJSNull(context);
2262 return NULL;
2263 } CYCatch(NULL) }
2264
2265 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2266 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2267 }
2268
2269 #ifdef __APPLE__
2270 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2271 *data = reinterpret_cast<void *>(address);
2272 return KERN_SUCCESS;
2273 }
2274
2275 struct CYChoice {
2276 std::set<Class> query_;
2277 JSContextRef context_;
2278 JSObjectRef results_;
2279 };
2280
2281 struct CYObjectStruct {
2282 Class isa_;
2283 };
2284
2285 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2286 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2287 JSContextRef context(choice->context_);
2288
2289 for (unsigned i(0); i != count; ++i) {
2290 vm_range_t &range(ranges[i]);
2291 void *data(reinterpret_cast<void *>(range.address));
2292 size_t size(range.size);
2293
2294 if (size < sizeof(CYObjectStruct))
2295 continue;
2296
2297 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2298 #if defined(__APPLE__) && defined(__LP64__)
2299 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2300 #else
2301 Class isa(reinterpret_cast<Class>(pointers[0]));
2302 #endif
2303
2304 std::set<Class>::const_iterator result(choice->query_.find(isa));
2305 if (result == choice->query_.end())
2306 continue;
2307
2308 size_t needed(class_getInstanceSize(*result));
2309 // XXX: if (size < needed)
2310
2311 size_t boundary(496);
2312 #ifdef __LP64__
2313 boundary *= 2;
2314 #endif
2315 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2316 continue;
2317 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2318 }
2319 }
2320
2321 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2322 if (count != 1)
2323 throw CYJSError(context, "choose() takes a class argument");
2324
2325 CYGarbageCollect(context);
2326
2327 CYPool pool;
2328 id _class(CYCastNSObject(&pool, context, arguments[0]));
2329
2330 vm_address_t *zones(NULL);
2331 unsigned size(0);
2332 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2333 _assert(error == KERN_SUCCESS);
2334
2335 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2336 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2337
2338 CYChoice choice;
2339 choice.context_ = context;
2340 choice.results_ = results;
2341
2342 size_t number;
2343 Class *classes(CYCopyClassList(number));
2344 _assert(classes != NULL);
2345
2346 for (size_t i(0); i != number; ++i)
2347 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2348 if (current == _class) {
2349 choice.query_.insert(classes[i]);
2350 break;
2351 }
2352
2353 free(classes);
2354
2355 for (unsigned i(0); i != size; ++i) {
2356 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2357 if (zone == NULL || zone->introspect == NULL)
2358 continue;
2359
2360 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2361 }
2362
2363 return results;
2364 } CYCatch(NULL) }
2365 #endif
2366
2367 #ifdef __APPLE__
2368 #if defined(__i386__) || defined(__x86_64__)
2369 #define OBJC_MAX_STRUCT_BY_VALUE 8
2370 static int struct_forward_array[] = {
2371 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2372 #elif defined(__arm__)
2373 #define OBJC_MAX_STRUCT_BY_VALUE 1
2374 static int struct_forward_array[] = {
2375 0, 0 };
2376 #elif defined(__arm64__)
2377 #define CY_NO_STRET
2378 #else
2379 #error missing objc-runtime-info
2380 #endif
2381
2382 #ifndef CY_NO_STRET
2383 static bool stret(ffi_type *ffi_type) {
2384 return ffi_type->type == FFI_TYPE_STRUCT && (
2385 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2386 struct_forward_array[ffi_type->size] != 0
2387 );
2388 }
2389 #endif
2390 #else
2391 #define CY_NO_STRET
2392 #endif
2393
2394 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2395 const char *type;
2396
2397 if (_class == NULL)
2398 _class = object_getClass(self);
2399
2400 IMP imp;
2401
2402 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2403 imp = method_getImplementation(method);
2404 type = method_getTypeEncoding(method);
2405 } else {
2406 imp = NULL;
2407
2408 CYPoolTry {
2409 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2410 type = CYPoolCString(pool, context, [method _typeString]);
2411 else
2412 type = NULL;
2413 } CYPoolCatch(NULL)
2414
2415 if (type == NULL)
2416 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2417 }
2418
2419 void *setup[2];
2420 setup[0] = &self;
2421 setup[1] = &_cmd;
2422
2423 sig::Signature signature;
2424 sig::Parse(pool, &signature, type, &Structor_);
2425
2426 size_t used(count + 3);
2427 if (used > signature.count) {
2428 sig::Element *elements(new (pool) sig::Element[used]);
2429 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2430
2431 for (size_t index(signature.count); index != used; ++index) {
2432 sig::Element *element(&elements[index]);
2433 element->name = NULL;
2434 element->offset = _not(size_t);
2435
2436 sig::Type *type(new (pool) sig::Type);
2437 memset(type, 0, sizeof(*type));
2438 type->primitive = sig::object_P;
2439 element->type = type;
2440 }
2441
2442 signature.elements = elements;
2443 signature.count = used;
2444 }
2445
2446 ffi_cif cif;
2447 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2448
2449 if (imp == NULL) {
2450 #ifndef CY_NO_STRET
2451 if (stret(cif.rtype))
2452 imp = class_getMethodImplementation_stret(_class, _cmd);
2453 else
2454 #endif
2455 imp = class_getMethodImplementation(_class, _cmd);
2456 }
2457
2458 void (*function)() = reinterpret_cast<void (*)()>(imp);
2459 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2460 }
2461
2462 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2463 if (count < 2)
2464 throw CYJSError(context, "too few arguments to objc_msgSend");
2465
2466 CYPool pool;
2467
2468 bool uninitialized;
2469
2470 id self;
2471 SEL _cmd;
2472 Class _class;
2473
2474 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2475 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2476 self = internal->GetValue();
2477 _class = internal->class_;;
2478 uninitialized = false;
2479 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2480 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2481 self = internal->GetValue();
2482 _class = nil;
2483 uninitialized = internal->IsUninitialized();
2484 if (uninitialized)
2485 internal->value_ = nil;
2486 } else {
2487 self = CYCastNSObject(&pool, context, arguments[0]);
2488 _class = nil;
2489 uninitialized = false;
2490 }
2491
2492 if (self == nil)
2493 return CYJSNull(context);
2494
2495 _cmd = CYCastSEL(context, arguments[1]);
2496
2497 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2498 }
2499
2500 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2501 return $objc_msgSend(context, object, _this, count, arguments);
2502 } CYCatch(NULL) }
2503
2504 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2505 JSValueRef setup[count + 2];
2506 setup[0] = _this;
2507 setup[1] = object;
2508 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2509 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2510 } CYCatch(NULL) }
2511
2512 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2513 CYPool pool;
2514 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2515
2516 // XXX: handle Instance::Uninitialized?
2517 id self(CYCastNSObject(&pool, context, _this));
2518
2519 void *setup[2];
2520 setup[0] = &self;
2521 setup[1] = &internal->sel_;
2522
2523 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2524 } CYCatch(NULL) }
2525
2526 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2527 if (count != 2)
2528 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2529 CYPool pool;
2530 id self(CYCastNSObject(&pool, context, arguments[0]));
2531 Class _class(CYCastClass(pool, context, arguments[1]));
2532 return cy::Super::Make(context, self, _class);
2533 } CYCatch(NULL) }
2534
2535 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2536 if (count != 1)
2537 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2538 CYPool pool;
2539 const char *name(CYPoolCString(pool, context, arguments[0]));
2540 return CYMakeSelector(context, sel_registerName(name));
2541 } CYCatch(NULL) }
2542
2543 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2544 if (count != 1)
2545 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2546 return CYMakeInstance(context, CYCastPointer<id>(context, arguments[0]));
2547 } CYCatch(NULL) }
2548
2549 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2550 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2551 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2552 } CYCatch(NULL) }
2553
2554 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2555 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2556 Type_privateData *typical(internal->GetType());
2557
2558 sig::Type *type;
2559 ffi_type *ffi;
2560
2561 if (typical == NULL) {
2562 type = NULL;
2563 ffi = NULL;
2564 } else {
2565 type = typical->type_;
2566 ffi = typical->ffi_;
2567 }
2568
2569 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2570 } CYCatch(NULL) }
2571
2572 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2573 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2574 CYPool pool;
2575 sig::Signature *signature(CYBlockSignature(pool, internal->GetValue()));
2576 if (signature == NULL)
2577 return CYJSNull(context);
2578 return CYMakeType(context, signature);
2579 } CYCatch(NULL) }
2580
2581 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2582 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2583 return CYMakeInstance(context, object_getClass(internal->GetValue()), Instance::Permanent);
2584 } CYCatch(NULL) }
2585
2586 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2587 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2588 id self(internal->GetValue());
2589 if (!CYIsClass(self))
2590 return CYJSUndefined(context);
2591 return CYGetClassPrototype(context, self);
2592 } CYCatch(NULL) }
2593
2594 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2595 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2596 id self(internal->GetValue());
2597 if (!CYIsClass(self))
2598 return CYJSUndefined(context);
2599 return Messages::Make(context, (Class) self);
2600 } CYCatch(NULL) }
2601
2602 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2603 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2604
2605 if (!CYJSValueIsNSObject(context, _this))
2606 return NULL;
2607
2608 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2609 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2610 } CYCatch(NULL) }
2611
2612 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2613 if (!CYJSValueIsNSObject(context, _this))
2614 return NULL;
2615
2616 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2617 id value(internal->GetValue());
2618
2619 CYPoolTry {
2620 NSString *key;
2621 if (count == 0)
2622 key = nil;
2623 else
2624 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2625
2626 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2627 return CYJSUndefined(context);
2628 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2629 return json;
2630 else
2631 return CYCastJSValue(context, CYJSString(context, [value description]));
2632 } CYPoolCatch(NULL)
2633 } CYCatch(NULL) return /*XXX*/ NULL; }
2634
2635 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2636 if (!CYJSValueIsNSObject(context, _this))
2637 return NULL;
2638
2639 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2640 id value(internal->GetValue());
2641 _assert(value != nil);
2642
2643 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2644 return _this;
2645
2646 if (JSValueRef result = [value cy$valueOfInContext:context])
2647 return result;
2648
2649 return _this;
2650 } CYCatch(NULL) return /*XXX*/ NULL; }
2651
2652 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2653 if (!CYJSValueIsNSObject(context, _this))
2654 return NULL;
2655
2656 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2657 // XXX: but... but... THIS ISN'T A POINTER! :(
2658 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2659 } CYCatch(NULL) return /*XXX*/ NULL; }
2660
2661 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2662 if (!CYJSValueIsNSObject(context, _this))
2663 return NULL;
2664
2665 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2666 id value(internal->GetValue());
2667
2668 CYPoolTry {
2669 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2670 return CYCastJSValue(context, CYJSString(context, [value description]));
2671 } CYPoolCatch(NULL)
2672 } CYCatch(NULL) return /*XXX*/ NULL; }
2673
2674 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2675 if (!CYJSValueIsNSObject(context, _this))
2676 return NULL;
2677
2678 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2679 id value(internal->GetValue());
2680
2681 if (!CYIsClass(value))
2682 CYThrow("non-Class object cannot be used as Type");
2683
2684 sig::Type type;
2685 memset(&type, 0, sizeof(type));
2686 type.primitive = sig::object_P;
2687 type.name = class_getName(value);
2688 return CYMakeType(context, &type);
2689 } CYCatch(NULL) return /*XXX*/ NULL; }
2690
2691 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2692 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2693 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2694 } CYCatch(NULL) }
2695
2696 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2697 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2698 }
2699
2700 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2701 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2702 const char *name(sel_getName(internal->GetValue()));
2703
2704 CYPoolTry {
2705 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2706 return CYCastJSValue(context, CYJSString(context, string));
2707 } CYPoolCatch(NULL)
2708 } CYCatch(NULL) return /*XXX*/ NULL; }
2709
2710 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2711 if (count != 1)
2712 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2713
2714 CYPool pool;
2715 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2716 SEL sel(internal->GetValue());
2717
2718 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2719 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2720 const char *encoding(method_getTypeEncoding(method));
2721
2722 sig::Signature signature;
2723 sig::Parse(pool, &signature, encoding, &Structor_);
2724 return CYMakeType(context, &signature);
2725 } CYCatch(NULL) }
2726
2727 static JSStaticValue Selector_staticValues[2] = {
2728 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2729 {NULL, NULL, NULL, 0}
2730 };
2731
2732 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2733 static JSStaticValue Instance_staticValues[5] = {
2734 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2735 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2736 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2737 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2738 {NULL, NULL, NULL, 0}
2739 };
2740
2741 static JSStaticValue FunctionInstance_staticValues[6] = {
2742 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2743 // XXX: this is sadly a duplicate of Instance_staticValues
2744 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2745 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2746 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2747 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2748 {NULL, NULL, NULL, 0}
2749 };
2750
2751 static JSStaticFunction Instance_staticFunctions[7] = {
2752 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2753 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2754 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2755 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2756 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2757 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2758 {NULL, NULL, 0}
2759 };
2760
2761 static JSStaticFunction Class_staticFunctions[2] = {
2762 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2763 {NULL, NULL, 0}
2764 };
2765
2766 static JSStaticFunction Internal_staticFunctions[2] = {
2767 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2768 {NULL, NULL, 0}
2769 };
2770
2771 static JSStaticFunction Selector_staticFunctions[5] = {
2772 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2773 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2774 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2775 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2776 {NULL, NULL, 0}
2777 };
2778
2779 #ifdef __APPLE__
2780 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2781 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2782 } CYObjectiveCatch }
2783 #endif
2784
2785 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2786 CYPool &pool(CYGetGlobalPool());
2787
2788 Object_type = new(pool) Type_privateData(sig::object_P);
2789 Selector_type = new(pool) Type_privateData(sig::selector_P);
2790
2791 NSArray_ = objc_getClass("NSArray");
2792 NSBlock_ = objc_getClass("NSBlock");
2793 NSDictionary_ = objc_getClass("NSDictionary");
2794 NSNumber_ = objc_getClass("NSNumber");
2795 NSString_ = objc_getClass("NSString");
2796 Object_ = objc_getClass("Object");
2797
2798 #ifdef __APPLE__
2799 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2800
2801 // XXX: apparently, iOS now has both of these
2802 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2803 if (NSCFBoolean_ == nil)
2804 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2805
2806 NSCFType_ = objc_getClass("NSCFType");
2807
2808 NSZombie_ = objc_getClass("_NSZombie_");
2809 #else
2810 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2811 NSZombie_ = objc_getClass("NSZombie");
2812 #endif
2813
2814 JSClassDefinition definition;
2815
2816 definition = kJSClassDefinitionEmpty;
2817 definition.className = "Instance";
2818 definition.staticValues = Instance_staticValues;
2819 definition.staticFunctions = Instance_staticFunctions;
2820 definition.hasProperty = &Instance_hasProperty;
2821 definition.getProperty = &Instance_getProperty;
2822 definition.setProperty = &Instance_setProperty;
2823 definition.deleteProperty = &Instance_deleteProperty;
2824 definition.getPropertyNames = &Instance_getPropertyNames;
2825 definition.callAsConstructor = &Instance_callAsConstructor;
2826 definition.hasInstance = &Instance_hasInstance;
2827 definition.finalize = &CYFinalize;
2828 Instance_ = JSClassCreate(&definition);
2829
2830 definition.className = "ArrayInstance";
2831 ArrayInstance_ = JSClassCreate(&definition);
2832
2833 definition.className = "BooleanInstance";
2834 BooleanInstance_ = JSClassCreate(&definition);
2835
2836 definition.className = "NumberInstance";
2837 NumberInstance_ = JSClassCreate(&definition);
2838
2839 definition.className = "ObjectInstance";
2840 ObjectInstance_ = JSClassCreate(&definition);
2841
2842 definition.className = "StringInstance";
2843 StringInstance_ = JSClassCreate(&definition);
2844
2845 definition.className = "FunctionInstance";
2846 definition.staticValues = FunctionInstance_staticValues;
2847 definition.callAsFunction = &FunctionInstance_callAsFunction;
2848 FunctionInstance_ = JSClassCreate(&definition);
2849
2850 definition = kJSClassDefinitionEmpty;
2851 definition.className = "Class";
2852 definition.staticFunctions = Class_staticFunctions;
2853 Class_ = JSClassCreate(&definition);
2854
2855 definition = kJSClassDefinitionEmpty;
2856 definition.className = "Internal";
2857 definition.staticFunctions = Internal_staticFunctions;
2858 definition.hasProperty = &Internal_hasProperty;
2859 definition.getProperty = &Internal_getProperty;
2860 definition.setProperty = &Internal_setProperty;
2861 definition.getPropertyNames = &Internal_getPropertyNames;
2862 definition.finalize = &CYFinalize;
2863 Internal_ = JSClassCreate(&definition);
2864
2865 definition = kJSClassDefinitionEmpty;
2866 definition.className = "Message";
2867 definition.staticFunctions = cy::Functor::StaticFunctions;
2868 definition.staticValues = cy::Functor::StaticValues;
2869 definition.callAsFunction = &Message_callAsFunction;
2870 definition.finalize = &CYFinalize;
2871 Message_ = JSClassCreate(&definition);
2872
2873 definition = kJSClassDefinitionEmpty;
2874 definition.className = "Messages";
2875 definition.hasProperty = &Messages_hasProperty;
2876 definition.getProperty = &Messages_getProperty;
2877 definition.setProperty = &Messages_setProperty;
2878 definition.getPropertyNames = &Messages_getPropertyNames;
2879 definition.finalize = &CYFinalize;
2880 Messages_ = JSClassCreate(&definition);
2881
2882 definition = kJSClassDefinitionEmpty;
2883 definition.className = "Selector";
2884 definition.staticValues = Selector_staticValues;
2885 definition.staticFunctions = Selector_staticFunctions;
2886 definition.callAsFunction = &Selector_callAsFunction;
2887 definition.finalize = &CYFinalize;
2888 Selector_ = JSClassCreate(&definition);
2889
2890 definition = kJSClassDefinitionEmpty;
2891 definition.className = "Super";
2892 definition.staticFunctions = Internal_staticFunctions;
2893 definition.finalize = &CYFinalize;
2894 Super_ = JSClassCreate(&definition);
2895
2896 definition = kJSClassDefinitionEmpty;
2897 definition.className = "ObjectiveC::Classes";
2898 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2899 definition.getProperty = &ObjectiveC_Classes_getProperty;
2900 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2901 ObjectiveC_Classes_ = JSClassCreate(&definition);
2902
2903 definition = kJSClassDefinitionEmpty;
2904 definition.className = "ObjectiveC::Constants";
2905 definition.getProperty = &ObjectiveC_Constants_getProperty;
2906 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2907 ObjectiveC_Constants_ = JSClassCreate(&definition);
2908
2909 #ifdef __APPLE__
2910 definition = kJSClassDefinitionEmpty;
2911 definition.className = "ObjectiveC::Images";
2912 definition.getProperty = &ObjectiveC_Images_getProperty;
2913 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2914 ObjectiveC_Images_ = JSClassCreate(&definition);
2915
2916 definition = kJSClassDefinitionEmpty;
2917 definition.className = "ObjectiveC::Image::Classes";
2918 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2919 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2920 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2921 #endif
2922
2923 definition = kJSClassDefinitionEmpty;
2924 definition.className = "ObjectiveC::Protocols";
2925 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2926 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2927 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2928
2929 #ifdef __APPLE__
2930 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2931 // XXX: this is horrible; there has to be a better way to do this
2932 #ifdef __LP64__
2933 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2934 #else
2935 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2936 #endif
2937 );
2938 #endif
2939 } CYPoolCatch() }
2940
2941 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2942 JSObjectRef global(CYGetGlobalObject(context));
2943 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2944 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2945 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2946 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2947
2948 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2949 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2950
2951 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2952 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2953 CYArrayPush(context, alls, protocols);
2954
2955 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2956 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2957 CYArrayPush(context, alls, classes);
2958
2959 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2960 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2961 CYArrayPush(context, alls, constants);
2962
2963 #ifdef __APPLE__
2964 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2965 #endif
2966
2967 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2968 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2969 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2970 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2971 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2972
2973 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2974 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2975
2976 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2977 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2978 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2979 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2980 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2981
2982 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2983 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2984 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2985 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2986 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2987
2988 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2989 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2990 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2991 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2992 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2993
2994 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2995 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2996 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2997 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2998 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2999
3000 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3001 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3002 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3003 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3004 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3005
3006 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3007 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3008 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3009 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3010 CYSetPrototype(context, StringInstance_prototype, String_prototype);
3011
3012 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
3013 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
3014 CYSetPrototype(context, Class_prototype, Instance_prototype);
3015
3016 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3017 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3018 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3019
3020 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3021 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3022
3023 #ifdef __APPLE__
3024 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3025 #endif
3026
3027 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3028
3029 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3030 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3031
3032 JSObjectRef cache(CYGetCachedObject(context, CYJSString("cache")));
3033 CYSetProperty(context, cache, CYJSString("YES"), JSValueMakeBoolean(context, true), kJSPropertyAttributeDontEnum);
3034 CYSetProperty(context, cache, CYJSString("NO"), JSValueMakeBoolean(context, false), kJSPropertyAttributeDontEnum);
3035 CYSetProperty(context, cache, CYJSString("id"), CYMakeType(context, sig::object_P), kJSPropertyAttributeDontEnum);
3036 CYSetProperty(context, cache, CYJSString("Class"), CYMakeType(context, sig::typename_P), kJSPropertyAttributeDontEnum);
3037 CYSetProperty(context, cache, CYJSString("SEL"), CYMakeType(context, sig::selector_P), kJSPropertyAttributeDontEnum);
3038 } CYPoolCatch() }
3039
3040 static void *CYObjectiveC_CastSymbol(const char *name) {
3041 if (false);
3042 #ifdef __GNU_LIBOBJC__
3043 else if (strcmp(name, "object_getClass") == 0)
3044 return reinterpret_cast<void *>(&object_getClass);
3045 #endif
3046 return NULL;
3047 }
3048
3049 static CYHook CYObjectiveCHook = {
3050 &CYObjectiveC_ExecuteStart,
3051 &CYObjectiveC_ExecuteEnd,
3052 &CYObjectiveC_CallFunction,
3053 &CYObjectiveC_Initialize,
3054 &CYObjectiveC_SetupContext,
3055 &CYObjectiveC_PoolFFI,
3056 &CYObjectiveC_FromFFI,
3057 &CYObjectiveC_CastSymbol,
3058 };
3059
3060 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3061
3062 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3063 CYSetupContext(context);
3064 } CYObjectiveCatch }
3065
3066 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3067 CYPool pool;
3068
3069 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3070 utf8 = CYPoolCode(pool, utf8);
3071
3072 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3073 size_t bytes(utf16.size * sizeof(uint16_t));
3074 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3075 memcpy(copy, utf16.data, bytes);
3076
3077 *data = copy;
3078 *size = utf16.size;
3079 } catch (const CYException &exception) {
3080 CYPool pool;
3081 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];
3082 } }