]> git.saurik.com Git - cycript.git/blob - ObjectiveC/Library.mm
Upgrade to Bison 3.0.4 (Apple is never upgrading).
[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 if (encoding[0] == 'b') {
2081 unsigned length, shift;
2082 CYBitField(length, shift, self, ivar, encoding, offset);
2083 _assert(shift + length <= sizeof(uintptr_t) * 8);
2084 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2085 uintptr_t mask((1 << length) - 1);
2086 return CYCastJSValue(context, (field >> shift) & mask);
2087 } else {
2088 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2089 return CYFromFFI(context, type->type_, type->GetFFI(), data);
2090 }
2091 }
2092
2093 return NULL;
2094 } CYCatch(NULL) }
2095
2096 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2097 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2098 CYPool pool;
2099
2100 id self(internal->GetValue());
2101 const char *name(CYPoolCString(pool, context, property));
2102
2103 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2104 ptrdiff_t offset(ivar_getOffset(ivar));
2105 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2106
2107 const char *encoding(ivar_getTypeEncoding(ivar));
2108 _assert(encoding != NULL);
2109 if (encoding[0] == 'b') {
2110 unsigned length, shift;
2111 CYBitField(length, shift, self, ivar, encoding, offset);
2112 _assert(shift + length <= sizeof(uintptr_t) * 8);
2113 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2114 uintptr_t mask((1 << length) - 1);
2115 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2116 } else {
2117 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2118 CYPoolFFI(&pool, context, type->type_, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2119 return true;
2120 }
2121 }
2122
2123 return false;
2124 } CYCatch(false) }
2125
2126 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2127 if (Class super = class_getSuperclass(_class))
2128 Internal_getPropertyNames_(super, names);
2129
2130 #if OBJC_API_VERSION >= 2
2131 unsigned int size;
2132 objc_ivar **data(class_copyIvarList(_class, &size));
2133 for (size_t i(0); i != size; ++i)
2134 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2135 free(data);
2136 #else
2137 if (objc_ivar_list *ivars = _class->ivars)
2138 for (int i(0); i != ivars->ivar_count; ++i)
2139 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2140 #endif
2141 }
2142
2143 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2144 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2145 CYPool pool;
2146
2147 id self(internal->GetValue());
2148 Class _class(object_getClass(self));
2149
2150 Internal_getPropertyNames_(_class, names);
2151 }
2152
2153 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2154 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2155 return internal->GetOwner();
2156 } CYCatch(NULL) }
2157
2158 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2159 CYPool pool;
2160 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2161 }
2162
2163 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2164 CYPool pool;
2165 NSString *name(CYCastNSString(&pool, context, property));
2166 if (Class _class = NSClassFromString(name))
2167 return CYMakeInstance(context, _class, true);
2168 return NULL;
2169 } CYCatch(NULL) }
2170
2171 #ifdef __APPLE__
2172 static Class *CYCopyClassList(size_t &size) {
2173 size = objc_getClassList(NULL, 0);
2174 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2175
2176 for (;;) {
2177 size_t writ(objc_getClassList(data, size));
2178 if (writ <= size) {
2179 size = writ;
2180 return data;
2181 }
2182
2183 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2184 if (copy == NULL) {
2185 free(data);
2186 return NULL;
2187 }
2188
2189 data = copy;
2190 size = writ;
2191 }
2192 }
2193 #endif
2194
2195 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2196 #ifdef __APPLE__
2197 size_t size;
2198 if (Class *data = CYCopyClassList(size)) {
2199 for (size_t i(0); i != size; ++i)
2200 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2201 free(data);
2202 }
2203 #else
2204 void *state(NULL);
2205 while (Class _class = objc_next_class(&state))
2206 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2207 #endif
2208 }
2209
2210 #if OBJC_API_VERSION >= 2
2211 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2212 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2213
2214 CYPool pool;
2215 const char *name(CYPoolCString(pool, context, property));
2216 unsigned int size;
2217 const char **data(objc_copyClassNamesForImage(internal, &size));
2218 JSValueRef value;
2219 for (size_t i(0); i != size; ++i)
2220 if (strcmp(name, data[i]) == 0) {
2221 if (Class _class = objc_getClass(name)) {
2222 value = CYMakeInstance(context, _class, true);
2223 goto free;
2224 } else
2225 break;
2226 }
2227 value = NULL;
2228 free:
2229 free(data);
2230 return value;
2231 } CYCatch(NULL) }
2232
2233 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2234 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2235 unsigned int size;
2236 const char **data(objc_copyClassNamesForImage(internal, &size));
2237 for (size_t i(0); i != size; ++i)
2238 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2239 free(data);
2240 }
2241
2242 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2243 CYPool pool;
2244 const char *name(CYPoolCString(pool, context, property));
2245 unsigned int size;
2246 const char **data(objc_copyImageNames(&size));
2247 for (size_t i(0); i != size; ++i)
2248 if (strcmp(name, data[i]) == 0) {
2249 name = data[i];
2250 goto free;
2251 }
2252 name = NULL;
2253 free:
2254 free(data);
2255 if (name == NULL)
2256 return NULL;
2257 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2258 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2259 return value;
2260 } CYCatch(NULL) }
2261
2262 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2263 unsigned int size;
2264 const char **data(objc_copyImageNames(&size));
2265 for (size_t i(0); i != size; ++i)
2266 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2267 free(data);
2268 }
2269 #endif
2270
2271 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2272 CYPool pool;
2273 const char *name(CYPoolCString(pool, context, property));
2274 if (Protocol *protocol = objc_getProtocol(name))
2275 return CYMakeInstance(context, protocol, true);
2276 return NULL;
2277 } CYCatch(NULL) }
2278
2279 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2280 #if OBJC_API_VERSION >= 2
2281 unsigned int size;
2282 Protocol **data(objc_copyProtocolList(&size));
2283 for (size_t i(0); i != size; ++i)
2284 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2285 free(data);
2286 #else
2287 // XXX: fix this!
2288 #endif
2289 }
2290
2291 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2292 CYPool pool;
2293 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2294 if (name == "nil")
2295 return Instance::Make(context, nil);
2296 return NULL;
2297 } CYCatch(NULL) }
2298
2299 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2300 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2301 }
2302
2303 #ifdef __APPLE__
2304 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2305 *data = reinterpret_cast<void *>(address);
2306 return KERN_SUCCESS;
2307 }
2308
2309 struct CYChoice {
2310 std::set<Class> query_;
2311 JSContextRef context_;
2312 JSObjectRef results_;
2313 };
2314
2315 struct CYObjectStruct {
2316 Class isa_;
2317 };
2318
2319 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2320 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2321 JSContextRef context(choice->context_);
2322
2323 for (unsigned i(0); i != count; ++i) {
2324 vm_range_t &range(ranges[i]);
2325 void *data(reinterpret_cast<void *>(range.address));
2326 size_t size(range.size);
2327
2328 if (size < sizeof(CYObjectStruct))
2329 continue;
2330
2331 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2332 #ifdef __arm64__
2333 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2334 #else
2335 Class isa(reinterpret_cast<Class>(pointers[0]));
2336 #endif
2337
2338 std::set<Class>::const_iterator result(choice->query_.find(isa));
2339 if (result == choice->query_.end())
2340 continue;
2341
2342 size_t needed(class_getInstanceSize(*result));
2343 // XXX: if (size < needed)
2344
2345 size_t boundary(496);
2346 #ifdef __LP64__
2347 boundary *= 2;
2348 #endif
2349 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2350 continue;
2351 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2352 }
2353 }
2354
2355 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2356 if (count != 1)
2357 throw CYJSError(context, "choose() takes a class argument");
2358
2359 CYGarbageCollect(context);
2360
2361 CYPool pool;
2362 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2363
2364 vm_address_t *zones(NULL);
2365 unsigned size(0);
2366 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2367 _assert(error == KERN_SUCCESS);
2368
2369 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2370 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2371
2372 CYChoice choice;
2373 choice.context_ = context;
2374 choice.results_ = results;
2375
2376 size_t number;
2377 Class *classes(CYCopyClassList(number));
2378 _assert(classes != NULL);
2379
2380 for (size_t i(0); i != number; ++i)
2381 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2382 if (current == _class) {
2383 choice.query_.insert(classes[i]);
2384 break;
2385 }
2386
2387 free(classes);
2388
2389 for (unsigned i(0); i != size; ++i) {
2390 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2391 if (zone == NULL || zone->introspect == NULL)
2392 continue;
2393
2394 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2395 }
2396
2397 return results;
2398 } CYCatch(NULL) }
2399 #endif
2400
2401 #ifdef __APPLE__
2402 #if defined(__i386__) || defined(__x86_64__)
2403 #define OBJC_MAX_STRUCT_BY_VALUE 8
2404 static int struct_forward_array[] = {
2405 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2406 #elif defined(__arm__)
2407 #define OBJC_MAX_STRUCT_BY_VALUE 1
2408 static int struct_forward_array[] = {
2409 0, 0 };
2410 #elif defined(__arm64__)
2411 #define CY_NO_STRET
2412 #else
2413 #error missing objc-runtime-info
2414 #endif
2415
2416 #ifndef CY_NO_STRET
2417 static bool stret(ffi_type *ffi_type) {
2418 return ffi_type->type == FFI_TYPE_STRUCT && (
2419 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2420 struct_forward_array[ffi_type->size] != 0
2421 );
2422 }
2423 #endif
2424 #endif
2425
2426 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2427 const char *type;
2428
2429 if (_class == NULL)
2430 _class = object_getClass(self);
2431
2432 IMP imp;
2433
2434 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2435 imp = method_getImplementation(method);
2436 type = method_getTypeEncoding(method);
2437 } else {
2438 imp = NULL;
2439
2440 CYPoolTry {
2441 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2442 if (method == nil)
2443 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2444 type = CYPoolCString(pool, context, [method _typeString]);
2445 } CYPoolCatch(NULL)
2446 }
2447
2448 void *setup[2];
2449 setup[0] = &self;
2450 setup[1] = &_cmd;
2451
2452 sig::Signature signature;
2453 sig::Parse(pool, &signature, type, &Structor_);
2454
2455 size_t used(count + 3);
2456 if (used > signature.count) {
2457 sig::Element *elements(new (pool) sig::Element[used]);
2458 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2459
2460 for (size_t index(signature.count); index != used; ++index) {
2461 sig::Element *element(&elements[index]);
2462 element->name = NULL;
2463 element->offset = _not(size_t);
2464
2465 sig::Type *type(new (pool) sig::Type);
2466 memset(type, 0, sizeof(*type));
2467 type->primitive = sig::object_P;
2468 element->type = type;
2469 }
2470
2471 signature.elements = elements;
2472 signature.count = used;
2473 }
2474
2475 ffi_cif cif;
2476 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2477
2478 if (imp == NULL) {
2479 #ifdef __APPLE__
2480 #ifndef CY_NO_STRET
2481 if (stret(cif.rtype))
2482 imp = class_getMethodImplementation_stret(_class, _cmd);
2483 else
2484 #endif
2485 imp = class_getMethodImplementation(_class, _cmd);
2486 #else
2487 objc_super super = {self, _class};
2488 imp = objc_msg_lookup_super(&super, _cmd);
2489 #endif
2490 }
2491
2492 void (*function)() = reinterpret_cast<void (*)()>(imp);
2493 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2494 }
2495
2496 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2497 if (count < 2)
2498 throw CYJSError(context, "too few arguments to objc_msgSend");
2499
2500 CYPool pool;
2501
2502 bool uninitialized;
2503
2504 id self;
2505 SEL _cmd;
2506 Class _class;
2507
2508 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2509 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2510 self = internal->GetValue();
2511 _class = internal->class_;;
2512 uninitialized = false;
2513 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2514 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2515 self = internal->GetValue();
2516 _class = nil;
2517 uninitialized = internal->IsUninitialized();
2518 if (uninitialized)
2519 internal->value_ = nil;
2520 } else {
2521 self = CYCastNSObject(&pool, context, arguments[0]);
2522 _class = nil;
2523 uninitialized = false;
2524 }
2525
2526 if (self == nil)
2527 return CYJSNull(context);
2528
2529 _cmd = CYCastSEL(context, arguments[1]);
2530
2531 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2532 }
2533
2534 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2535 return $objc_msgSend(context, object, _this, count, arguments);
2536 } CYCatch(NULL) }
2537
2538 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2539 JSValueRef setup[count + 2];
2540 setup[0] = _this;
2541 setup[1] = object;
2542 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2543 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2544 } CYCatch(NULL) }
2545
2546 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2547 CYPool pool;
2548 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2549
2550 // XXX: handle Instance::Uninitialized?
2551 id self(CYCastNSObject(&pool, context, _this));
2552
2553 void *setup[2];
2554 setup[0] = &self;
2555 setup[1] = &internal->sel_;
2556
2557 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2558 } CYCatch(NULL) }
2559
2560 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2561 if (count != 2)
2562 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2563 CYPool pool;
2564 id self(CYCastNSObject(&pool, context, arguments[0]));
2565 Class _class(CYCastClass(pool, context, arguments[1]));
2566 return cy::Super::Make(context, self, _class);
2567 } CYCatch(NULL) }
2568
2569 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2570 if (count != 1)
2571 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2572 CYPool pool;
2573 const char *name(CYPoolCString(pool, context, arguments[0]));
2574 return CYMakeSelector(context, sel_registerName(name));
2575 } CYCatch(NULL) }
2576
2577 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2578 if (count > 1)
2579 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2580 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2581 return CYMakeInstance(context, self, false);
2582 } CYCatch(NULL) }
2583
2584 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2585 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2586 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2587 } CYCatch(NULL) }
2588
2589 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2590 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2591 Type_privateData *typical(internal->GetType());
2592
2593 sig::Type *type;
2594 ffi_type *ffi;
2595
2596 if (typical == NULL) {
2597 type = NULL;
2598 ffi = NULL;
2599 } else {
2600 type = typical->type_;
2601 ffi = typical->ffi_;
2602 }
2603
2604 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2605 } CYCatch(NULL) }
2606
2607 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2608 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2609 const char *encoding(CYBlockEncoding(internal->GetValue()));
2610 if (encoding == NULL)
2611 return CYJSNull(context);
2612 // XXX: this should be stored on a FunctionInstance private value subclass
2613 CYPool pool;
2614 sig::Signature signature;
2615 sig::Parse(pool, &signature, encoding, &Structor_);
2616 return CYMakeType(context, &signature);
2617 } CYCatch(NULL) }
2618
2619 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2620 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2621 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2622 } CYCatch(NULL) }
2623
2624 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2625 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2626 id self(internal->GetValue());
2627 if (!CYIsClass(self))
2628 return CYJSUndefined(context);
2629 return CYGetClassPrototype(context, self);
2630 } CYCatch(NULL) }
2631
2632 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2633 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2634 id self(internal->GetValue());
2635 if (!CYIsClass(self))
2636 return CYJSUndefined(context);
2637 return Messages::Make(context, (Class) self);
2638 } CYCatch(NULL) }
2639
2640 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2641 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2642
2643 if (!CYJSValueIsNSObject(context, _this))
2644 return NULL;
2645
2646 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2647 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2648 } CYCatch(NULL) }
2649
2650 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2651 if (!CYJSValueIsNSObject(context, _this))
2652 return NULL;
2653
2654 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2655 id value(internal->GetValue());
2656
2657 CYPoolTry {
2658 NSString *key;
2659 if (count == 0)
2660 key = nil;
2661 else
2662 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2663
2664 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2665 return CYJSUndefined(context);
2666 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2667 return json;
2668 else
2669 return CYCastJSValue(context, CYJSString(context, [value description]));
2670 } CYPoolCatch(NULL)
2671 } CYCatch(NULL) return /*XXX*/ NULL; }
2672
2673 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2674 if (!CYJSValueIsNSObject(context, _this))
2675 return NULL;
2676
2677 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2678 id value(internal->GetValue());
2679
2680 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2681 return _this;
2682
2683 if (JSValueRef result = [value cy$valueOfInContext:context])
2684 return result;
2685
2686 return _this;
2687 } CYCatch(NULL) return /*XXX*/ NULL; }
2688
2689 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2690 if (!CYJSValueIsNSObject(context, _this))
2691 return NULL;
2692
2693 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2694 // XXX: but... but... THIS ISN'T A POINTER! :(
2695 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2696 } CYCatch(NULL) return /*XXX*/ NULL; }
2697
2698 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2699 if (!CYJSValueIsNSObject(context, _this))
2700 return NULL;
2701
2702 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2703 id value(internal->GetValue());
2704
2705 CYPoolTry {
2706 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2707 return CYCastJSValue(context, CYJSString(context, [value description]));
2708 } CYPoolCatch(NULL)
2709 } CYCatch(NULL) return /*XXX*/ NULL; }
2710
2711 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2712 if (!CYJSValueIsNSObject(context, _this))
2713 return NULL;
2714
2715 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2716 id value(internal->GetValue());
2717
2718 if (!CYIsClass(value))
2719 CYThrow("non-Class object cannot be used as Type");
2720
2721 sig::Type type;
2722 memset(&type, 0, sizeof(type));
2723 type.primitive = sig::object_P;
2724 type.name = class_getName(value);
2725 return CYMakeType(context, &type);
2726 } CYCatch(NULL) return /*XXX*/ NULL; }
2727
2728 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2729 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2730 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2731 } CYCatch(NULL) }
2732
2733 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2734 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2735 }
2736
2737 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2738 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2739 const char *name(sel_getName(internal->GetValue()));
2740
2741 CYPoolTry {
2742 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2743 return CYCastJSValue(context, CYJSString(context, string));
2744 } CYPoolCatch(NULL)
2745 } CYCatch(NULL) return /*XXX*/ NULL; }
2746
2747 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2748 if (count != 1)
2749 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2750
2751 CYPool pool;
2752 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2753 SEL sel(internal->GetValue());
2754
2755 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2756 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2757 const char *encoding(method_getTypeEncoding(method));
2758
2759 sig::Signature signature;
2760 sig::Parse(pool, &signature, encoding, &Structor_);
2761 return CYMakeType(context, &signature);
2762 } CYCatch(NULL) }
2763
2764 static JSStaticValue Selector_staticValues[2] = {
2765 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2766 {NULL, NULL, NULL, 0}
2767 };
2768
2769 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2770 static JSStaticValue Instance_staticValues[5] = {
2771 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2772 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2773 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2774 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2775 {NULL, NULL, NULL, 0}
2776 };
2777
2778 static JSStaticValue FunctionInstance_staticValues[6] = {
2779 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2780 // XXX: this is sadly a duplicate of Instance_staticValues
2781 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2782 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2783 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2784 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2785 {NULL, NULL, NULL, 0}
2786 };
2787
2788 static JSStaticFunction Instance_staticFunctions[7] = {
2789 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2790 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2791 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2792 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2793 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2794 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2795 {NULL, NULL, 0}
2796 };
2797
2798 static JSStaticFunction Class_staticFunctions[2] = {
2799 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2800 {NULL, NULL, 0}
2801 };
2802
2803 static JSStaticFunction Internal_staticFunctions[2] = {
2804 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2805 {NULL, NULL, 0}
2806 };
2807
2808 static JSStaticFunction Selector_staticFunctions[5] = {
2809 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2810 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2811 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2812 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2813 {NULL, NULL, 0}
2814 };
2815
2816 #ifdef __APPLE__
2817 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2818 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2819 } CYObjectiveCatch }
2820 #endif
2821
2822 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2823 CYPool &pool(CYGetGlobalPool());
2824
2825 Object_type = new(pool) Type_privateData(sig::object_P);
2826 Selector_type = new(pool) Type_privateData(sig::selector_P);
2827
2828 NSArray_ = objc_getClass("NSArray");
2829 NSBlock_ = objc_getClass("NSBlock");
2830 NSDictionary_ = objc_getClass("NSDictionary");
2831 NSNumber_ = objc_getClass("NSNumber");
2832 NSString_ = objc_getClass("NSString");
2833 Object_ = objc_getClass("Object");
2834
2835 #ifdef __APPLE__
2836 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2837
2838 // XXX: apparently, iOS now has both of these
2839 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2840 if (NSCFBoolean_ == nil)
2841 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2842
2843 NSCFType_ = objc_getClass("NSCFType");
2844
2845 NSZombie_ = objc_getClass("_NSZombie_");
2846 #else
2847 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2848 #endif
2849
2850 JSClassDefinition definition;
2851
2852 definition = kJSClassDefinitionEmpty;
2853 definition.className = "Instance";
2854 definition.staticValues = Instance_staticValues;
2855 definition.staticFunctions = Instance_staticFunctions;
2856 definition.hasProperty = &Instance_hasProperty;
2857 definition.getProperty = &Instance_getProperty;
2858 definition.setProperty = &Instance_setProperty;
2859 definition.deleteProperty = &Instance_deleteProperty;
2860 definition.getPropertyNames = &Instance_getPropertyNames;
2861 definition.callAsConstructor = &Instance_callAsConstructor;
2862 definition.hasInstance = &Instance_hasInstance;
2863 definition.finalize = &CYFinalize;
2864 Instance_ = JSClassCreate(&definition);
2865
2866 definition.className = "ArrayInstance";
2867 ArrayInstance_ = JSClassCreate(&definition);
2868
2869 definition.className = "BooleanInstance";
2870 BooleanInstance_ = JSClassCreate(&definition);
2871
2872 definition.className = "NumberInstance";
2873 NumberInstance_ = JSClassCreate(&definition);
2874
2875 definition.className = "ObjectInstance";
2876 ObjectInstance_ = JSClassCreate(&definition);
2877
2878 definition.className = "StringInstance";
2879 StringInstance_ = JSClassCreate(&definition);
2880
2881 definition.className = "FunctionInstance";
2882 definition.staticValues = FunctionInstance_staticValues;
2883 definition.callAsFunction = &FunctionInstance_callAsFunction;
2884 FunctionInstance_ = JSClassCreate(&definition);
2885
2886 definition = kJSClassDefinitionEmpty;
2887 definition.className = "Class";
2888 definition.staticFunctions = Class_staticFunctions;
2889 Class_ = JSClassCreate(&definition);
2890
2891 definition = kJSClassDefinitionEmpty;
2892 definition.className = "Internal";
2893 definition.staticFunctions = Internal_staticFunctions;
2894 definition.hasProperty = &Internal_hasProperty;
2895 definition.getProperty = &Internal_getProperty;
2896 definition.setProperty = &Internal_setProperty;
2897 definition.getPropertyNames = &Internal_getPropertyNames;
2898 definition.finalize = &CYFinalize;
2899 Internal_ = JSClassCreate(&definition);
2900
2901 definition = kJSClassDefinitionEmpty;
2902 definition.className = "Message";
2903 definition.staticFunctions = cy::Functor::StaticFunctions;
2904 definition.staticValues = cy::Functor::StaticValues;
2905 definition.callAsFunction = &Message_callAsFunction;
2906 definition.finalize = &CYFinalize;
2907 Message_ = JSClassCreate(&definition);
2908
2909 definition = kJSClassDefinitionEmpty;
2910 definition.className = "Messages";
2911 definition.hasProperty = &Messages_hasProperty;
2912 definition.getProperty = &Messages_getProperty;
2913 definition.setProperty = &Messages_setProperty;
2914 #if 0 && OBJC_API_VERSION < 2
2915 definition.deleteProperty = &Messages_deleteProperty;
2916 #endif
2917 definition.getPropertyNames = &Messages_getPropertyNames;
2918 definition.finalize = &CYFinalize;
2919 Messages_ = JSClassCreate(&definition);
2920
2921 definition = kJSClassDefinitionEmpty;
2922 definition.className = "Selector";
2923 definition.staticValues = Selector_staticValues;
2924 definition.staticFunctions = Selector_staticFunctions;
2925 definition.callAsFunction = &Selector_callAsFunction;
2926 definition.finalize = &CYFinalize;
2927 Selector_ = JSClassCreate(&definition);
2928
2929 definition = kJSClassDefinitionEmpty;
2930 definition.className = "Super";
2931 definition.staticFunctions = Internal_staticFunctions;
2932 definition.finalize = &CYFinalize;
2933 Super_ = JSClassCreate(&definition);
2934
2935 definition = kJSClassDefinitionEmpty;
2936 definition.className = "ObjectiveC::Classes";
2937 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2938 definition.getProperty = &ObjectiveC_Classes_getProperty;
2939 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2940 ObjectiveC_Classes_ = JSClassCreate(&definition);
2941
2942 definition = kJSClassDefinitionEmpty;
2943 definition.className = "ObjectiveC::Constants";
2944 definition.getProperty = &ObjectiveC_Constants_getProperty;
2945 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2946 ObjectiveC_Constants_ = JSClassCreate(&definition);
2947
2948 #if OBJC_API_VERSION >= 2
2949 definition = kJSClassDefinitionEmpty;
2950 definition.className = "ObjectiveC::Images";
2951 definition.getProperty = &ObjectiveC_Images_getProperty;
2952 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2953 ObjectiveC_Images_ = JSClassCreate(&definition);
2954
2955 definition = kJSClassDefinitionEmpty;
2956 definition.className = "ObjectiveC::Image::Classes";
2957 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2958 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2959 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2960 #endif
2961
2962 definition = kJSClassDefinitionEmpty;
2963 definition.className = "ObjectiveC::Protocols";
2964 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2965 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2966 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2967
2968 #ifdef __APPLE__
2969 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2970 // XXX: this is horrible; there has to be a better way to do this
2971 #ifdef __LP64__
2972 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2973 #else
2974 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2975 #endif
2976 );
2977 #endif
2978 } CYPoolCatch() }
2979
2980 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2981 JSObjectRef global(CYGetGlobalObject(context));
2982 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2983 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2984 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2985 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2986
2987 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2988 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2989
2990 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2991 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2992 CYArrayPush(context, alls, protocols);
2993
2994 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2995 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2996 CYArrayPush(context, alls, classes);
2997
2998 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2999 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
3000 CYArrayPush(context, alls, constants);
3001
3002 #if OBJC_API_VERSION >= 2
3003 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3004 #endif
3005
3006 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
3007 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3008 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3009 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3010 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
3011
3012 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
3013 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
3014
3015 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
3016 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
3017 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
3018 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
3019 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
3020
3021 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
3022 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
3023 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
3024 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
3025 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
3026
3027 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
3028 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
3029 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
3030 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
3031 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
3032
3033 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
3034 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
3035 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
3036 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
3037 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
3038
3039 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
3040 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
3041 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
3042 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
3043 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
3044
3045 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
3046 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
3047 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
3048 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
3049 CYSetPrototype(context, StringInstance_prototype, String_prototype);
3050
3051 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
3052 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
3053 CYSetPrototype(context, Class_prototype, Instance_prototype);
3054
3055 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
3056 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
3057 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
3058
3059 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
3060 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
3061
3062 #ifdef __APPLE__
3063 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
3064 #endif
3065
3066 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
3067
3068 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
3069 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
3070 } CYPoolCatch() }
3071
3072 static CYHook CYObjectiveCHook = {
3073 &CYObjectiveC_ExecuteStart,
3074 &CYObjectiveC_ExecuteEnd,
3075 &CYObjectiveC_CallFunction,
3076 &CYObjectiveC_Initialize,
3077 &CYObjectiveC_SetupContext,
3078 &CYObjectiveC_PoolFFI,
3079 &CYObjectiveC_FromFFI,
3080 };
3081
3082 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3083
3084 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3085 CYSetupContext(context);
3086 } CYObjectiveCatch }
3087
3088 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3089 CYPool pool;
3090
3091 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3092 CYStream stream(utf8.data, utf8.data + utf8.size);
3093 utf8 = CYPoolCode(pool, stream);
3094
3095 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3096 size_t bytes(utf16.size * sizeof(uint16_t));
3097 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3098 memcpy(copy, utf16.data, bytes);
3099
3100 *data = copy;
3101 *size = utf16.size;
3102 } catch (const CYException &exception) {
3103 CYPool pool;
3104 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];
3105 } }