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