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