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