]> git.saurik.com Git - cycript.git/blob - Library.mm
a9a0ae4d29c3137e8b36765bf18c13feda595f95
[cycript.git] / Library.mm
1 /* Cycript - Remote Execution Server and Disassembler
2 * Copyright (C) 2009 Jay Freeman (saurik)
3 */
4
5 /* Modified BSD License {{{ */
6 /*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38 /* }}} */
39
40 #include <substrate.h>
41
42 #include <dlfcn.h>
43 #include <iconv.h>
44
45 #include "cycript.hpp"
46
47 #include "sig/parse.hpp"
48 #include "sig/ffi_type.hpp"
49
50 #include "Pooling.hpp"
51 #include "Struct.hpp"
52
53 #ifdef __APPLE__
54 #include <CoreFoundation/CoreFoundation.h>
55 #include <CoreFoundation/CFLogUtilities.h>
56 #include <JavaScriptCore/JSStringRefCF.h>
57 #endif
58
59 #ifdef __OBJC__
60 #ifdef __APPLE__
61 #include <WebKit/WebScriptObject.h>
62 #endif
63 #include <Foundation/Foundation.h>
64 #endif
65
66 #include <sys/mman.h>
67
68 #include <iostream>
69 #include <ext/stdio_filebuf.h>
70 #include <set>
71 #include <map>
72 #include <iomanip>
73 #include <sstream>
74 #include <cmath>
75
76 #include "Parser.hpp"
77 #include "Cycript.tab.hh"
78
79 #undef _assert
80 #undef _trace
81
82 #ifdef __OBJC__
83 #define _throw(name, args...) \
84 @throw [NSException exceptionWithName:name reason:[NSString stringWithFormat:@args] userInfo:nil]
85 #else
86 #define _throw(name, args...) \
87 throw "_throw()"
88 #endif
89
90 #define _assert(test) do { \
91 if (!(test)) \
92 _throw(NSInternalInconsistencyException, "*** _assert(%s):%s(%u):%s [errno=%d]", #test, __FILE__, __LINE__, __FUNCTION__, errno); \
93 } while (false)
94
95 #define _trace() do { \
96 fprintf(stderr, "_trace():%u\n", __LINE__); \
97 } while (false)
98
99 #define CYTry \
100 @try
101 #define CYCatch \
102 @catch (NSException *error) { \
103 CYThrow(context, error, exception); \
104 return NULL; \
105 }
106
107 #if 0
108 #define CYTry \
109 try
110 #define CYCatch \
111 catch (NSException *error) { \
112 CYThrow(context, error, exception); \
113 return NULL; \
114 } catch (...) { \
115 *exception = CYCastJSValue(context, "catch(...)"); \
116 return NULL; \
117 }
118 #endif
119
120 #ifdef __OBJC__
121 #define CYPoolTry { \
122 id _saved(nil); \
123 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
124 @try
125 #define CYPoolCatch(value) \
126 @catch (NSException *error) { \
127 _saved = [error retain]; \
128 @throw; \
129 return value; \
130 } @finally { \
131 [_pool release]; \
132 if (_saved != nil) \
133 [_saved autorelease]; \
134 } \
135 }
136 #else
137 #define CYPoolTry {
138 #define CYPoolCatch }
139 #endif
140
141 #ifndef __APPLE__
142 #define class_getSuperclass GSObjCSuper
143 #define object_getClass GSObjCClass
144 #endif
145
146 void CYThrow(JSContextRef context, JSValueRef value);
147
148 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception);
149 JSStringRef CYCopyJSString(const char *value);
150
151 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value);
152
153 JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)());
154 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
155
156 struct CYUTF8String {
157 const char *data;
158 size_t size;
159
160 CYUTF8String(const char *data, size_t size) :
161 data(data),
162 size(size)
163 {
164 }
165 };
166
167 struct CYUTF16String {
168 const uint16_t *data;
169 size_t size;
170
171 CYUTF16String(const uint16_t *data, size_t size) :
172 data(data),
173 size(size)
174 {
175 }
176 };
177
178 /* JavaScript Properties {{{ */
179 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
180 JSValueRef exception(NULL);
181 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
182 CYThrow(context, exception);
183 return value;
184 }
185
186 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
187 JSValueRef exception(NULL);
188 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
189 CYThrow(context, exception);
190 return value;
191 }
192
193 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
194 JSValueRef exception(NULL);
195 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
196 CYThrow(context, exception);
197 }
198
199 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
200 JSValueRef exception(NULL);
201 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
202 CYThrow(context, exception);
203 }
204 /* }}} */
205 /* JavaScript Strings {{{ */
206 JSStringRef CYCopyJSString(const char *value) {
207 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
208 }
209
210 JSStringRef CYCopyJSString(JSStringRef value) {
211 return value == NULL ? NULL : JSStringRetain(value);
212 }
213
214 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
215 if (JSValueIsNull(context, value))
216 return NULL;
217 JSValueRef exception(NULL);
218 JSStringRef string(JSValueToStringCopy(context, value, &exception));
219 CYThrow(context, exception);
220 return string;
221 }
222
223 class CYJSString {
224 private:
225 JSStringRef string_;
226
227 void Clear_() {
228 if (string_ != NULL)
229 JSStringRelease(string_);
230 }
231
232 public:
233 CYJSString(const CYJSString &rhs) :
234 string_(CYCopyJSString(rhs.string_))
235 {
236 }
237
238 template <typename Arg0_>
239 CYJSString(Arg0_ arg0) :
240 string_(CYCopyJSString(arg0))
241 {
242 }
243
244 template <typename Arg0_, typename Arg1_>
245 CYJSString(Arg0_ arg0, Arg1_ arg1) :
246 string_(CYCopyJSString(arg0, arg1))
247 {
248 }
249
250 CYJSString &operator =(const CYJSString &rhs) {
251 Clear_();
252 string_ = CYCopyJSString(rhs.string_);
253 return *this;
254 }
255
256 ~CYJSString() {
257 Clear_();
258 }
259
260 void Clear() {
261 Clear_();
262 string_ = NULL;
263 }
264
265 operator JSStringRef() const {
266 return string_;
267 }
268 };
269 /* }}} */
270 /* C Strings {{{ */
271 // XXX: this macro is unhygenic
272 #define CYCastCString_(string) ({ \
273 char *utf8; \
274 if (string == NULL) \
275 utf8 = NULL; \
276 else { \
277 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
278 utf8 = reinterpret_cast<char *>(alloca(size)); \
279 JSStringGetUTF8CString(string, utf8, size); \
280 } \
281 utf8; \
282 })
283
284 // XXX: this macro is unhygenic
285 #define CYCastCString(context, value) ({ \
286 char *utf8; \
287 if (value == NULL) \
288 utf8 = NULL; \
289 else if (JSStringRef string = CYCopyJSString(context, value)) { \
290 utf8 = CYCastCString_(string); \
291 JSStringRelease(string); \
292 } else \
293 utf8 = NULL; \
294 utf8; \
295 })
296
297 /* }}} */
298
299 #ifdef __OBJC__
300 /* Objective-C Pool Release {{{ */
301 apr_status_t CYPoolRelease_(void *data) {
302 id object(reinterpret_cast<id>(data));
303 [object release];
304 return APR_SUCCESS;
305 }
306
307 id CYPoolRelease_(apr_pool_t *pool, id object) {
308 if (object == nil)
309 return nil;
310 else if (pool == NULL)
311 return [object autorelease];
312 else {
313 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
314 return object;
315 }
316 }
317
318 template <typename Type_>
319 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
320 return (Type_) CYPoolRelease_(pool, (id) object);
321 }
322 /* }}} */
323 /* Objective-C Strings {{{ */
324 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
325 if (pool == NULL)
326 return [value UTF8String];
327 else {
328 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
329 char *string(new(pool) char[size]);
330 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
331 _throw(NSInternalInconsistencyException, "[NSString getCString:maxLength:encoding:] == NO");
332 return string;
333 }
334 }
335
336 JSStringRef CYCopyJSString_(NSString *value) {
337 #ifdef __APPLE__
338 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
339 #else
340 CYPool pool;
341 return CYCopyJSString(CYPoolCString(pool, value));
342 #endif
343 }
344
345 JSStringRef CYCopyJSString(id value) {
346 if (value == nil)
347 return NULL;
348 // XXX: this definition scares me; is anyone using this?!
349 NSString *string([value description]);
350 return CYCopyJSString_(string);
351 }
352
353 NSString *CYCopyNSString(const CYUTF8String &value) {
354 #ifdef __APPLE__
355 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
356 #else
357 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
358 #endif
359 }
360
361 NSString *CYCopyNSString(JSStringRef value) {
362 #ifdef __APPLE__
363 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
364 #else
365 return CYCopyNSString(CYCastCString_(value));
366 #endif
367 }
368
369 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
370 return CYCopyNSString(CYJSString(context, value));
371 }
372
373 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
374 return CYPoolRelease(pool, CYCopyNSString(value));
375 }
376
377 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
378 const char *name(sel_getName(sel));
379 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
380 }
381
382 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
383 return CYPoolRelease(pool, CYCopyNSString(value));
384 }
385 /* }}} */
386 #endif
387
388 CYUTF8String CYCastUTF8String(NSString *value) {
389 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
390 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
391 }
392
393 /* JavaScript Stringify {{{ */
394 void CYStringify(std::ostringstream &str, const char *data, size_t size) {
395 unsigned quot(0), apos(0);
396 for (const char *value(data), *end(data + size); value != end; ++value)
397 if (*value == '"')
398 ++quot;
399 else if (*value == '\'')
400 ++apos;
401
402 bool single(quot > apos);
403
404 str << (single ? '\'' : '"');
405
406 for (const char *value(data), *end(data + size); value != end; ++value)
407 switch (*value) {
408 case '\\': str << "\\\\"; break;
409 case '\b': str << "\\b"; break;
410 case '\f': str << "\\f"; break;
411 case '\n': str << "\\n"; break;
412 case '\r': str << "\\r"; break;
413 case '\t': str << "\\t"; break;
414 case '\v': str << "\\v"; break;
415
416 case '"':
417 if (!single)
418 str << "\\\"";
419 else goto simple;
420 break;
421
422 case '\'':
423 if (single)
424 str << "\\'";
425 else goto simple;
426 break;
427
428 default:
429 if (*value < 0x20 || *value >= 0x7f)
430 str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(*value);
431 else simple:
432 str << *value;
433 }
434
435 str << (single ? '\'' : '"');
436 }
437 /* }}} */
438
439 static JSGlobalContextRef Context_;
440 static JSObjectRef System_;
441 static JSObjectRef ObjectiveC_;
442
443 static JSClassRef Functor_;
444 static JSClassRef Instance_;
445 static JSClassRef Internal_;
446 static JSClassRef Message_;
447 static JSClassRef Messages_;
448 static JSClassRef Pointer_;
449 static JSClassRef Runtime_;
450 static JSClassRef Selector_;
451 static JSClassRef Struct_;
452
453 static JSClassRef ObjectiveC_Classes_;
454 static JSClassRef ObjectiveC_Image_Classes_;
455 static JSClassRef ObjectiveC_Images_;
456 static JSClassRef ObjectiveC_Protocols_;
457
458 static JSObjectRef Array_;
459 static JSObjectRef Function_;
460 static JSObjectRef String_;
461
462 static JSStringRef Result_;
463
464 static JSStringRef length_;
465 static JSStringRef message_;
466 static JSStringRef name_;
467 static JSStringRef prototype_;
468 static JSStringRef toCYON_;
469 static JSStringRef toJSON_;
470
471 static JSObjectRef Instance_prototype_;
472 static JSObjectRef Object_prototype_;
473
474 static JSObjectRef Array_prototype_;
475 static JSObjectRef Array_pop_;
476 static JSObjectRef Array_push_;
477 static JSObjectRef Array_splice_;
478
479 #ifdef __OBJC__
480 #ifdef __APPLE__
481 static Class NSCFBoolean_;
482 static Class NSCFType_;
483 #endif
484
485 static Class NSArray_;
486 static Class NSDictionary_;
487 static Class NSMessageBuilder_;
488 static Class NSZombie_;
489 static Class Object_;
490 #endif
491
492 static NSArray *Bridge_;
493
494 static void Finalize(JSObjectRef object) {
495 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
496 }
497
498 class Type_privateData;
499
500 struct CYValue :
501 CYData
502 {
503 void *value_;
504
505 CYValue() {
506 }
507
508 CYValue(const void *value) :
509 value_(const_cast<void *>(value))
510 {
511 }
512
513 CYValue(const CYValue &rhs) :
514 value_(rhs.value_)
515 {
516 }
517
518 virtual Type_privateData *GetType() const {
519 return NULL;
520 }
521 };
522
523 struct CYOwned :
524 CYValue
525 {
526 private:
527 JSContextRef context_;
528 JSObjectRef owner_;
529
530 public:
531 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
532 CYValue(value),
533 context_(context),
534 owner_(owner)
535 {
536 if (owner_ != NULL)
537 JSValueProtect(context_, owner_);
538 }
539
540 virtual ~CYOwned() {
541 if (owner_ != NULL)
542 JSValueUnprotect(context_, owner_);
543 }
544
545 JSObjectRef GetOwner() const {
546 return owner_;
547 }
548 };
549
550 #ifdef __OBJC__
551 struct Selector_privateData :
552 CYValue
553 {
554 Selector_privateData(SEL value) :
555 CYValue(value)
556 {
557 }
558
559 SEL GetValue() const {
560 return reinterpret_cast<SEL>(value_);
561 }
562
563 virtual Type_privateData *GetType() const;
564 };
565
566 // XXX: trick this out with associated objects!
567 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
568 if (self == nil)
569 return Instance_prototype_;
570
571 // XXX: I need to think through multi-context
572 typedef std::map<id, JSValueRef> CacheMap;
573 static CacheMap cache_;
574
575 JSValueRef &value(cache_[self]);
576 if (value != NULL)
577 return value;
578
579 JSClassRef _class(NULL);
580 JSValueRef prototype;
581
582 if (self == NSArray_)
583 prototype = Array_prototype_;
584 else if (self == NSDictionary_)
585 prototype = Object_prototype_;
586 else
587 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
588
589 JSObjectRef object(JSObjectMake(context, _class, NULL));
590 JSObjectSetPrototype(context, object, prototype);
591
592 JSValueProtect(context, object);
593 value = object;
594 return object;
595 }
596
597 struct Instance :
598 CYValue
599 {
600 enum Flags {
601 None = 0,
602 Transient = (1 << 0),
603 Uninitialized = (1 << 1),
604 };
605
606 Flags flags_;
607
608 Instance(id value, Flags flags) :
609 CYValue(value),
610 flags_(flags)
611 {
612 }
613
614 virtual ~Instance() {
615 if ((flags_ & Transient) == 0)
616 // XXX: does this handle background threads correctly?
617 // XXX: this simply does not work on the console because I'm stupid
618 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
619 }
620
621 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
622 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
623 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
624 return value;
625 }
626
627 id GetValue() const {
628 return reinterpret_cast<id>(value_);
629 }
630
631 bool IsUninitialized() const {
632 return (flags_ & Uninitialized) != 0;
633 }
634
635 virtual Type_privateData *GetType() const;
636 };
637
638 struct Messages :
639 CYValue
640 {
641 Messages(Class value) :
642 CYValue(value)
643 {
644 }
645
646 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
647 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
648 if (_class == NSArray_)
649 array = true;
650 if (Class super = class_getSuperclass(_class))
651 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
652 /*else if (array)
653 JSObjectSetPrototype(context, value, Array_prototype_);*/
654 return value;
655 }
656
657 Class GetValue() const {
658 return reinterpret_cast<Class>(value_);
659 }
660 };
661
662 struct Internal :
663 CYOwned
664 {
665 Internal(id value, JSContextRef context, JSObjectRef owner) :
666 CYOwned(value, context, owner)
667 {
668 }
669
670 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
671 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
672 }
673
674 id GetValue() const {
675 return reinterpret_cast<id>(value_);
676 }
677 };
678 #endif
679
680 namespace sig {
681
682 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
683
684 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
685 lhs.name = apr_pstrdup(pool, rhs.name);
686 if (rhs.type == NULL)
687 lhs.type = NULL;
688 else {
689 lhs.type = new(pool) Type;
690 Copy(pool, *lhs.type, *rhs.type);
691 }
692 lhs.offset = rhs.offset;
693 }
694
695 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
696 size_t count(rhs.count);
697 lhs.count = count;
698 lhs.elements = new(pool) Element[count];
699 for (size_t index(0); index != count; ++index)
700 Copy(pool, lhs.elements[index], rhs.elements[index]);
701 }
702
703 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
704 lhs.primitive = rhs.primitive;
705 lhs.name = apr_pstrdup(pool, rhs.name);
706 lhs.flags = rhs.flags;
707
708 if (sig::IsAggregate(rhs.primitive))
709 Copy(pool, lhs.data.signature, rhs.data.signature);
710 else {
711 sig::Type *&lht(lhs.data.data.type);
712 sig::Type *&rht(rhs.data.data.type);
713
714 if (rht == NULL)
715 lht = NULL;
716 else {
717 lht = new(pool) Type;
718 Copy(pool, *lht, *rht);
719 }
720
721 lhs.data.data.size = rhs.data.data.size;
722 }
723 }
724
725 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
726 lhs.size = rhs.size;
727 lhs.alignment = rhs.alignment;
728 lhs.type = rhs.type;
729 if (rhs.elements == NULL)
730 lhs.elements = NULL;
731 else {
732 size_t count(0);
733 while (rhs.elements[count] != NULL)
734 ++count;
735
736 lhs.elements = new(pool) ffi_type *[count + 1];
737 lhs.elements[count] = NULL;
738
739 for (size_t index(0); index != count; ++index) {
740 // XXX: if these are libffi native then you can just take them
741 ffi_type *ffi(new(pool) ffi_type);
742 lhs.elements[index] = ffi;
743 sig::Copy(pool, *ffi, *rhs.elements[index]);
744 }
745 }
746 }
747
748 }
749
750 struct CStringMapLess :
751 std::binary_function<const char *, const char *, bool>
752 {
753 _finline bool operator ()(const char *lhs, const char *rhs) const {
754 return strcmp(lhs, rhs) < 0;
755 }
756 };
757
758 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
759 if (name == NULL)
760 return;
761
762 CYPoolTry {
763 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
764 switch ([[entry objectAtIndex:0] intValue]) {
765 case 0: {
766 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
767 } break;
768
769 case 1: {
770 sig::Signature signature;
771 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
772 type = signature.elements[0].type;
773 } break;
774 }
775 } CYPoolCatch()
776 }
777
778 struct Type_privateData :
779 CYData
780 {
781 #ifdef __OBJC__
782 static Type_privateData *Object;
783 static Type_privateData *Selector;
784 #endif
785
786 static JSClassRef Class_;
787
788 ffi_type *ffi_;
789 sig::Type *type_;
790
791 void Set(sig::Type *type) {
792 type_ = new(pool_) sig::Type;
793 sig::Copy(pool_, *type_, *type);
794 }
795
796 Type_privateData(apr_pool_t *pool, const char *type) :
797 ffi_(NULL)
798 {
799 if (pool != NULL)
800 pool_ = pool;
801
802 sig::Signature signature;
803 sig::Parse(pool_, &signature, type, &Structor_);
804 type_ = signature.elements[0].type;
805 }
806
807 Type_privateData(sig::Type *type) :
808 ffi_(NULL)
809 {
810 if (type != NULL)
811 Set(type);
812 }
813
814 Type_privateData(sig::Type *type, ffi_type *ffi) {
815 ffi_ = new(pool_) ffi_type;
816 sig::Copy(pool_, *ffi_, *ffi);
817 Set(type);
818 }
819
820 ffi_type *GetFFI() {
821 if (ffi_ == NULL) {
822 ffi_ = new(pool_) ffi_type;
823
824 sig::Element element;
825 element.name = NULL;
826 element.type = type_;
827 element.offset = 0;
828
829 sig::Signature signature;
830 signature.elements = &element;
831 signature.count = 1;
832
833 ffi_cif cif;
834 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
835 *ffi_ = *cif.rtype;
836 }
837
838 return ffi_;
839 }
840 };
841
842 JSClassRef Type_privateData::Class_;
843
844 #ifdef __OBJC__
845 Type_privateData *Type_privateData::Object;
846 Type_privateData *Type_privateData::Selector;
847
848 Type_privateData *Instance::GetType() const {
849 return Type_privateData::Object;
850 }
851
852 Type_privateData *Selector_privateData::GetType() const {
853 return Type_privateData::Selector;
854 }
855 #endif
856
857 struct Pointer :
858 CYOwned
859 {
860 Type_privateData *type_;
861
862 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
863 CYOwned(value, context, owner),
864 type_(new(pool_) Type_privateData(type))
865 {
866 }
867 };
868
869 struct Struct_privateData :
870 CYOwned
871 {
872 Type_privateData *type_;
873
874 Struct_privateData(JSContextRef context, JSObjectRef owner) :
875 CYOwned(NULL, context, owner)
876 {
877 }
878 };
879
880 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
881 static TypeMap Types_;
882
883 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
884 Struct_privateData *internal(new Struct_privateData(context, owner));
885 apr_pool_t *pool(internal->pool_);
886 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
887 internal->type_ = typical;
888
889 if (owner != NULL)
890 internal->value_ = data;
891 else {
892 size_t size(typical->GetFFI()->size);
893 void *copy(apr_palloc(internal->pool_, size));
894 memcpy(copy, data, size);
895 internal->value_ = copy;
896 }
897
898 return JSObjectMake(context, Struct_, internal);
899 }
900
901 struct Functor_privateData :
902 CYValue
903 {
904 sig::Signature signature_;
905 ffi_cif cif_;
906
907
908 Functor_privateData(const char *type, void (*value)()) :
909 CYValue(reinterpret_cast<void *>(value))
910 {
911 sig::Parse(pool_, &signature_, type, &Structor_);
912 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
913 }
914
915 void (*GetValue())() const {
916 return reinterpret_cast<void (*)()>(value_);
917 }
918 };
919
920 struct Closure_privateData :
921 Functor_privateData
922 {
923 JSContextRef context_;
924 JSObjectRef function_;
925
926 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
927 Functor_privateData(type, NULL),
928 context_(context),
929 function_(function)
930 {
931 JSValueProtect(context_, function_);
932 }
933
934 virtual ~Closure_privateData() {
935 JSValueUnprotect(context_, function_);
936 }
937 };
938
939 #ifdef __OBJC__
940 struct Message_privateData :
941 Functor_privateData
942 {
943 SEL sel_;
944
945 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
946 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
947 sel_(sel)
948 {
949 }
950 };
951
952 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
953 Instance::Flags flags;
954
955 if (transient)
956 flags = Instance::Transient;
957 else {
958 flags = Instance::None;
959 object = [object retain];
960 }
961
962 return Instance::Make(context, object, flags);
963 }
964 #endif
965
966 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
967 return JSValueMakeBoolean(context, value);
968 }
969
970 JSValueRef CYCastJSValue(JSContextRef context, double value) {
971 return JSValueMakeNumber(context, value);
972 }
973
974 #define CYCastJSValue_(Type_) \
975 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
976 return JSValueMakeNumber(context, static_cast<double>(value)); \
977 }
978
979 CYCastJSValue_(int)
980 CYCastJSValue_(unsigned int)
981 CYCastJSValue_(long int)
982 CYCastJSValue_(long unsigned int)
983 CYCastJSValue_(long long int)
984 CYCastJSValue_(long long unsigned int)
985
986 JSValueRef CYJSUndefined(JSContextRef context) {
987 return JSValueMakeUndefined(context);
988 }
989
990 size_t CYGetIndex(const CYUTF8String &value) {
991 if (value.data[0] != '0') {
992 char *end;
993 size_t index(strtoul(value.data, &end, 10));
994 if (value.data + value.size == end)
995 return index;
996 } else if (value.data[1] == '\0')
997 return 0;
998 return _not(size_t);
999 }
1000
1001 // XXX: fix this
1002 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value);
1003
1004 size_t CYGetIndex(apr_pool_t *pool, JSStringRef value) {
1005 return CYGetIndex(CYPoolUTF8String(pool, value));
1006 }
1007
1008 bool CYGetOffset(const char *value, ssize_t &index) {
1009 if (value[0] != '0') {
1010 char *end;
1011 index = strtol(value, &end, 10);
1012 if (value + strlen(value) == end)
1013 return true;
1014 } else if (value[1] == '\0') {
1015 index = 0;
1016 return true;
1017 }
1018
1019 return false;
1020 }
1021
1022 #ifdef __OBJC__
1023 size_t CYGetIndex(NSString *value) {
1024 return CYGetIndex(CYCastUTF8String(value));
1025 }
1026
1027 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
1028 return CYGetOffset(CYPoolCString(pool, value), index);
1029 }
1030 #endif
1031
1032 #ifdef __OBJC__
1033 @interface NSMethodSignature (Cycript)
1034 - (NSString *) _typeString;
1035 @end
1036
1037 @interface NSObject (Cycript)
1038
1039 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1040 - (JSType) cy$JSType;
1041
1042 - (NSObject *) cy$toJSON:(NSString *)key;
1043 - (NSString *) cy$toCYON;
1044 - (NSString *) cy$toKey;
1045
1046 - (bool) cy$hasProperty:(NSString *)name;
1047 - (NSObject *) cy$getProperty:(NSString *)name;
1048 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
1049 - (bool) cy$deleteProperty:(NSString *)name;
1050
1051 @end
1052
1053 @protocol Cycript
1054 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
1055 @end
1056
1057 @interface NSString (Cycript)
1058 - (void *) cy$symbol;
1059 @end
1060 #endif
1061
1062 #ifdef __OBJC__
1063 NSString *CYCastNSCYON(id value) {
1064 NSString *string;
1065
1066 if (value == nil)
1067 string = @"nil";
1068 else {
1069 Class _class(object_getClass(value));
1070 SEL sel(@selector(cy$toCYON));
1071
1072 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
1073 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1074 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1075 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1076 string = [value cy$toCYON];
1077 else goto fail;
1078 } else fail: {
1079 if (value == NSZombie_)
1080 string = @"_NSZombie_";
1081 else if (_class == NSZombie_)
1082 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1083 // XXX: frowny /in/ the pants
1084 else if (value == NSMessageBuilder_ || value == Object_)
1085 string = nil;
1086 else
1087 string = [NSString stringWithFormat:@"%@", value];
1088 }
1089
1090 // XXX: frowny pants
1091 if (string == nil)
1092 string = @"undefined";
1093 }
1094
1095 return string;
1096 }
1097 #endif
1098
1099 #ifdef __OBJC__
1100 #ifdef __APPLE__
1101 struct PropertyAttributes {
1102 CYPool pool_;
1103
1104 const char *name;
1105
1106 const char *variable;
1107
1108 const char *getter_;
1109 const char *setter_;
1110
1111 bool readonly;
1112 bool copy;
1113 bool retain;
1114 bool nonatomic;
1115 bool dynamic;
1116 bool weak;
1117 bool garbage;
1118
1119 PropertyAttributes(objc_property_t property) :
1120 variable(NULL),
1121 getter_(NULL),
1122 setter_(NULL),
1123 readonly(false),
1124 copy(false),
1125 retain(false),
1126 nonatomic(false),
1127 dynamic(false),
1128 weak(false),
1129 garbage(false)
1130 {
1131 name = property_getName(property);
1132 const char *attributes(property_getAttributes(property));
1133
1134 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
1135 switch (*token) {
1136 case 'R': readonly = true; break;
1137 case 'C': copy = true; break;
1138 case '&': retain = true; break;
1139 case 'N': nonatomic = true; break;
1140 case 'G': getter_ = token + 1; break;
1141 case 'S': setter_ = token + 1; break;
1142 case 'V': variable = token + 1; break;
1143 }
1144 }
1145
1146 /*if (variable == NULL) {
1147 variable = property_getName(property);
1148 size_t size(strlen(variable));
1149 char *name(new(pool_) char[size + 2]);
1150 name[0] = '_';
1151 memcpy(name + 1, variable, size);
1152 name[size + 1] = '\0';
1153 variable = name;
1154 }*/
1155 }
1156
1157 const char *Getter() {
1158 if (getter_ == NULL)
1159 getter_ = apr_pstrdup(pool_, name);
1160 return getter_;
1161 }
1162
1163 const char *Setter() {
1164 if (setter_ == NULL && !readonly) {
1165 size_t length(strlen(name));
1166
1167 char *temp(new(pool_) char[length + 5]);
1168 temp[0] = 's';
1169 temp[1] = 'e';
1170 temp[2] = 't';
1171
1172 if (length != 0) {
1173 temp[3] = toupper(name[0]);
1174 memcpy(temp + 4, name + 1, length - 1);
1175 }
1176
1177 temp[length + 3] = ':';
1178 temp[length + 4] = '\0';
1179 setter_ = temp;
1180 }
1181
1182 return setter_;
1183 }
1184
1185 };
1186 #endif
1187 #endif
1188
1189 #ifdef __OBJC__
1190 #ifdef __APPLE__
1191 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
1192 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
1193 }
1194 #endif
1195 #endif
1196
1197 #ifdef __OBJC__
1198 #ifndef __APPLE__
1199 @interface CYWebUndefined : NSObject {
1200 }
1201
1202 + (CYWebUndefined *) undefined;
1203
1204 @end
1205
1206 @implementation CYWebUndefined
1207
1208 + (CYWebUndefined *) undefined {
1209 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
1210 return instance_;
1211 }
1212
1213 @end
1214
1215 #define WebUndefined CYWebUndefined
1216 #endif
1217 #endif
1218
1219 #ifdef __OBJC__
1220 /* Bridge: NSArray {{{ */
1221 @implementation NSArray (Cycript)
1222
1223 - (NSString *) cy$toCYON {
1224 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1225 [json appendString:@"["];
1226
1227 bool comma(false);
1228 #ifdef __APPLE__
1229 for (id object in self) {
1230 #else
1231 id object;
1232 for (size_t index(0), count([self count]); index != count; ++index) {
1233 object = [self objectAtIndex:index];
1234 #endif
1235 if (comma)
1236 [json appendString:@","];
1237 else
1238 comma = true;
1239 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
1240 [json appendString:CYCastNSCYON(object)];
1241 else {
1242 [json appendString:@","];
1243 comma = false;
1244 }
1245 }
1246
1247 [json appendString:@"]"];
1248 return json;
1249 }
1250
1251 - (bool) cy$hasProperty:(NSString *)name {
1252 if ([name isEqualToString:@"length"])
1253 return true;
1254
1255 size_t index(CYGetIndex(name));
1256 if (index == _not(size_t) || index >= [self count])
1257 return [super cy$hasProperty:name];
1258 else
1259 return true;
1260 }
1261
1262 - (NSObject *) cy$getProperty:(NSString *)name {
1263 if ([name isEqualToString:@"length"]) {
1264 NSUInteger count([self count]);
1265 #ifdef __APPLE__
1266 return [NSNumber numberWithUnsignedInteger:count];
1267 #else
1268 return [NSNumber numberWithUnsignedInt:count];
1269 #endif
1270 }
1271
1272 size_t index(CYGetIndex(name));
1273 if (index == _not(size_t) || index >= [self count])
1274 return [super cy$getProperty:name];
1275 else
1276 return [self objectAtIndex:index];
1277 }
1278
1279 @end
1280 /* }}} */
1281 /* Bridge: NSDictionary {{{ */
1282 @implementation NSDictionary (Cycript)
1283
1284 - (NSString *) cy$toCYON {
1285 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1286 [json appendString:@"{"];
1287
1288 bool comma(false);
1289 #ifdef __APPLE__
1290 for (id key in self) {
1291 #else
1292 NSEnumerator *keys([self keyEnumerator]);
1293 while (id key = [keys nextObject]) {
1294 #endif
1295 if (comma)
1296 [json appendString:@","];
1297 else
1298 comma = true;
1299 [json appendString:[key cy$toKey]];
1300 [json appendString:@":"];
1301 NSObject *object([self objectForKey:key]);
1302 [json appendString:CYCastNSCYON(object)];
1303 }
1304
1305 [json appendString:@"}"];
1306 return json;
1307 }
1308
1309 - (bool) cy$hasProperty:(NSString *)name {
1310 return [self objectForKey:name] != nil;
1311 }
1312
1313 - (NSObject *) cy$getProperty:(NSString *)name {
1314 return [self objectForKey:name];
1315 }
1316
1317 @end
1318 /* }}} */
1319 /* Bridge: NSMutableArray {{{ */
1320 @implementation NSMutableArray (Cycript)
1321
1322 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1323 if ([name isEqualToString:@"length"]) {
1324 // XXX: is this not intelligent?
1325 NSNumber *number(reinterpret_cast<NSNumber *>(value));
1326 #ifdef __APPLE__
1327 NSUInteger size([number unsignedIntegerValue]);
1328 #else
1329 NSUInteger size([number unsignedIntValue]);
1330 #endif
1331 NSUInteger count([self count]);
1332 if (size < count)
1333 [self removeObjectsInRange:NSMakeRange(size, count - size)];
1334 else if (size != count) {
1335 WebUndefined *undefined([WebUndefined undefined]);
1336 for (size_t i(count); i != size; ++i)
1337 [self addObject:undefined];
1338 }
1339 return true;
1340 }
1341
1342 size_t index(CYGetIndex(name));
1343 if (index == _not(size_t))
1344 return [super cy$setProperty:name to:value];
1345
1346 id object(value ?: [NSNull null]);
1347
1348 size_t count([self count]);
1349 if (index < count)
1350 [self replaceObjectAtIndex:index withObject:object];
1351 else {
1352 if (index != count) {
1353 WebUndefined *undefined([WebUndefined undefined]);
1354 for (size_t i(count); i != index; ++i)
1355 [self addObject:undefined];
1356 }
1357
1358 [self addObject:object];
1359 }
1360
1361 return true;
1362 }
1363
1364 - (bool) cy$deleteProperty:(NSString *)name {
1365 size_t index(CYGetIndex(name));
1366 if (index == _not(size_t) || index >= [self count])
1367 return [super cy$deleteProperty:name];
1368 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1369 return true;
1370 }
1371
1372 @end
1373 /* }}} */
1374 /* Bridge: NSMutableDictionary {{{ */
1375 @implementation NSMutableDictionary (Cycript)
1376
1377 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1378 [self setObject:(value ?: [NSNull null]) forKey:name];
1379 return true;
1380 }
1381
1382 - (bool) cy$deleteProperty:(NSString *)name {
1383 if ([self objectForKey:name] == nil)
1384 return false;
1385 else {
1386 [self removeObjectForKey:name];
1387 return true;
1388 }
1389 }
1390
1391 @end
1392 /* }}} */
1393 /* Bridge: NSNumber {{{ */
1394 @implementation NSNumber (Cycript)
1395
1396 - (JSType) cy$JSType {
1397 #ifdef __APPLE__
1398 // XXX: this just seems stupid
1399 if ([self class] == NSCFBoolean_)
1400 return kJSTypeBoolean;
1401 #endif
1402 return kJSTypeNumber;
1403 }
1404
1405 - (NSObject *) cy$toJSON:(NSString *)key {
1406 return self;
1407 }
1408
1409 - (NSString *) cy$toCYON {
1410 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1411 }
1412
1413 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1414 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1415 }
1416
1417 @end
1418 /* }}} */
1419 /* Bridge: NSNull {{{ */
1420 @implementation NSNull (Cycript)
1421
1422 - (JSType) cy$JSType {
1423 return kJSTypeNull;
1424 }
1425
1426 - (NSObject *) cy$toJSON:(NSString *)key {
1427 return self;
1428 }
1429
1430 - (NSString *) cy$toCYON {
1431 return @"null";
1432 }
1433
1434 @end
1435 /* }}} */
1436 /* Bridge: NSObject {{{ */
1437 @implementation NSObject (Cycript)
1438
1439 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1440 return CYMakeInstance(context, self, false);
1441 }
1442
1443 - (JSType) cy$JSType {
1444 return kJSTypeObject;
1445 }
1446
1447 - (NSObject *) cy$toJSON:(NSString *)key {
1448 return [self description];
1449 }
1450
1451 - (NSString *) cy$toCYON {
1452 return [[self cy$toJSON:@""] cy$toCYON];
1453 }
1454
1455 - (NSString *) cy$toKey {
1456 return [self cy$toCYON];
1457 }
1458
1459 - (bool) cy$hasProperty:(NSString *)name {
1460 return false;
1461 }
1462
1463 - (NSObject *) cy$getProperty:(NSString *)name {
1464 return nil;
1465 }
1466
1467 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1468 return false;
1469 }
1470
1471 - (bool) cy$deleteProperty:(NSString *)name {
1472 return false;
1473 }
1474
1475 @end
1476 /* }}} */
1477 /* Bridge: NSProxy {{{ */
1478 @implementation NSProxy (Cycript)
1479
1480 - (NSObject *) cy$toJSON:(NSString *)key {
1481 return [self description];
1482 }
1483
1484 - (NSString *) cy$toCYON {
1485 return [[self cy$toJSON:@""] cy$toCYON];
1486 }
1487
1488 @end
1489 /* }}} */
1490 /* Bridge: NSString {{{ */
1491 @implementation NSString (Cycript)
1492
1493 - (JSType) cy$JSType {
1494 return kJSTypeString;
1495 }
1496
1497 - (NSObject *) cy$toJSON:(NSString *)key {
1498 return self;
1499 }
1500
1501 - (NSString *) cy$toCYON {
1502 std::ostringstream str;
1503 CYUTF8String string(CYCastUTF8String(self));
1504 CYStringify(str, string.data, string.size);
1505 std::string value(str.str());
1506 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1507 }
1508
1509 - (NSString *) cy$toKey {
1510 const char *value([self UTF8String]);
1511 size_t size(strlen(value));
1512
1513 if (size == 0)
1514 goto cyon;
1515
1516 if (DigitRange_[value[0]]) {
1517 size_t index(CYGetIndex(self));
1518 if (index == _not(size_t))
1519 goto cyon;
1520 } else {
1521 if (!WordStartRange_[value[0]])
1522 goto cyon;
1523 for (size_t i(1); i != size; ++i)
1524 if (!WordEndRange_[value[i]])
1525 goto cyon;
1526 }
1527
1528 return self;
1529
1530 cyon:
1531 return [self cy$toCYON];
1532 }
1533
1534 - (void *) cy$symbol {
1535 CYPool pool;
1536 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1537 }
1538
1539 @end
1540 /* }}} */
1541 /* Bridge: WebUndefined {{{ */
1542 @implementation WebUndefined (Cycript)
1543
1544 - (JSType) cy$JSType {
1545 return kJSTypeUndefined;
1546 }
1547
1548 - (NSObject *) cy$toJSON:(NSString *)key {
1549 return self;
1550 }
1551
1552 - (NSString *) cy$toCYON {
1553 return @"undefined";
1554 }
1555
1556 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1557 return CYJSUndefined(context);
1558 }
1559
1560 @end
1561 /* }}} */
1562
1563 /* Bridge: CYJSObject {{{ */
1564 @interface CYJSObject : NSMutableDictionary {
1565 JSObjectRef object_;
1566 JSContextRef context_;
1567 }
1568
1569 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1570
1571 - (NSObject *) cy$toJSON:(NSString *)key;
1572
1573 - (NSUInteger) count;
1574 - (id) objectForKey:(id)key;
1575 - (NSEnumerator *) keyEnumerator;
1576 - (void) setObject:(id)object forKey:(id)key;
1577 - (void) removeObjectForKey:(id)key;
1578
1579 @end
1580 /* }}} */
1581 /* Bridge: CYJSArray {{{ */
1582 @interface CYJSArray : NSMutableArray {
1583 JSObjectRef object_;
1584 JSContextRef context_;
1585 }
1586
1587 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1588
1589 - (NSUInteger) count;
1590 - (id) objectAtIndex:(NSUInteger)index;
1591
1592 - (void) addObject:(id)anObject;
1593 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1594 - (void) removeLastObject;
1595 - (void) removeObjectAtIndex:(NSUInteger)index;
1596 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1597
1598 @end
1599 /* }}} */
1600 #endif
1601
1602 #ifdef __OBJC__
1603 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1604 JSValueRef exception(NULL);
1605 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1606 CYThrow(context, exception);
1607 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1608 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1609 }
1610
1611 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1612 if (!JSValueIsObjectOfClass(context, object, Instance_))
1613 return CYCastNSObject_(pool, context, object);
1614 else {
1615 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1616 return internal->GetValue();
1617 }
1618 }
1619 #endif
1620
1621 double CYCastDouble(const char *value, size_t size) {
1622 char *end;
1623 double number(strtod(value, &end));
1624 if (end != value + size)
1625 return NAN;
1626 return number;
1627 }
1628
1629 double CYCastDouble(const char *value) {
1630 return CYCastDouble(value, strlen(value));
1631 }
1632
1633 double CYCastDouble(JSContextRef context, JSValueRef value) {
1634 JSValueRef exception(NULL);
1635 double number(JSValueToNumber(context, value, &exception));
1636 CYThrow(context, exception);
1637 return number;
1638 }
1639
1640 #ifdef __OBJC__
1641 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
1642 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
1643 }
1644 #endif
1645
1646 bool CYCastBool(JSContextRef context, JSValueRef value) {
1647 return JSValueToBoolean(context, value);
1648 }
1649
1650 #ifdef __OBJC__
1651 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1652 id object;
1653 bool copy;
1654
1655 switch (JSType type = JSValueGetType(context, value)) {
1656 case kJSTypeUndefined:
1657 object = [WebUndefined undefined];
1658 copy = false;
1659 break;
1660
1661 case kJSTypeNull:
1662 return NULL;
1663 break;
1664
1665 case kJSTypeBoolean:
1666 #ifdef __APPLE__
1667 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
1668 copy = false;
1669 #else
1670 object = [[NSNumber alloc] initWithBool:CYCastBool(context, value)];
1671 copy = true;
1672 #endif
1673 break;
1674
1675 case kJSTypeNumber:
1676 object = CYCopyNSNumber(context, value);
1677 copy = true;
1678 break;
1679
1680 case kJSTypeString:
1681 object = CYCopyNSString(context, value);
1682 copy = true;
1683 break;
1684
1685 case kJSTypeObject:
1686 // XXX: this might could be more efficient
1687 object = CYCastNSObject(pool, context, (JSObjectRef) value);
1688 copy = false;
1689 break;
1690
1691 default:
1692 _throw(NSInternalInconsistencyException, "JSValueGetType() == 0x%x", type);
1693 break;
1694 }
1695
1696 if (cast != copy)
1697 return object;
1698 else if (copy)
1699 return CYPoolRelease(pool, object);
1700 else
1701 return [object retain];
1702 }
1703
1704 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1705 return CYNSObject(pool, context, value, true);
1706 }
1707
1708 id CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1709 return CYNSObject(pool, context, value, false);
1710 }
1711
1712 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1713 CYPool pool;
1714 size_t size(JSPropertyNameArrayGetCount(names));
1715 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1716 for (size_t index(0); index != size; ++index)
1717 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1718 return array;
1719 }
1720 #endif
1721
1722 void CYThrow(JSContextRef context, JSValueRef value) {
1723 if (value == NULL)
1724 return;
1725 #ifdef __OBJC__
1726 @throw CYCastNSObject(NULL, context, value);
1727 #else
1728 // XXX: why not?
1729 throw value;
1730 #endif
1731 }
1732
1733 JSValueRef CYJSNull(JSContextRef context) {
1734 return JSValueMakeNull(context);
1735 }
1736
1737 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1738 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1739 }
1740
1741 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1742 return CYCastJSValue(context, CYJSString(value));
1743 }
1744
1745 #ifdef __OBJC__
1746 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1747 if (value == nil)
1748 return CYJSNull(context);
1749 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1750 return [value cy$JSValueInContext:context];
1751 else
1752 return CYMakeInstance(context, value, false);
1753 }
1754 #endif
1755
1756 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1757 JSValueRef exception(NULL);
1758 JSObjectRef object(JSValueToObject(context, value, &exception));
1759 CYThrow(context, exception);
1760 return object;
1761 }
1762
1763 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1764 if (exception == NULL)
1765 throw error;
1766 *exception = CYCastJSValue(context, error);
1767 }
1768
1769 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1770 JSValueRef exception(NULL);
1771 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1772 CYThrow(context, exception);
1773 return value;
1774 }
1775
1776 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1777 // XXX: this isn't actually correct
1778 return value != NULL && JSValueIsObject(context, value);
1779 }
1780
1781 #ifdef __OBJC__
1782 @implementation CYJSObject
1783
1784 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1785 if ((self = [super init]) != nil) {
1786 object_ = object;
1787 context_ = context;
1788 JSValueProtect(context_, object_);
1789 } return self;
1790 }
1791
1792 - (void) dealloc {
1793 JSValueUnprotect(context_, object_);
1794 [super dealloc];
1795 }
1796
1797 - (NSObject *) cy$toJSON:(NSString *)key {
1798 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1799 if (!CYIsCallable(context_, toJSON))
1800 return [super cy$toJSON:key];
1801 else {
1802 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1803 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1804 // XXX: do I really want an NSNull here?!
1805 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1806 }
1807 }
1808
1809 - (NSString *) cy$toCYON {
1810 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1811 if (!CYIsCallable(context_, toCYON)) super:
1812 return [super cy$toCYON];
1813 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1814 return CYCastNSString(NULL, CYJSString(context_, value));
1815 else goto super;
1816 }
1817
1818 - (NSUInteger) count {
1819 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1820 size_t size(JSPropertyNameArrayGetCount(names));
1821 JSPropertyNameArrayRelease(names);
1822 return size;
1823 }
1824
1825 - (id) objectForKey:(id)key {
1826 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1827 if (JSValueIsUndefined(context_, value))
1828 return nil;
1829 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1830 }
1831
1832 - (NSEnumerator *) keyEnumerator {
1833 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1834 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1835 JSPropertyNameArrayRelease(names);
1836 return enumerator;
1837 }
1838
1839 - (void) setObject:(id)object forKey:(id)key {
1840 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1841 }
1842
1843 - (void) removeObjectForKey:(id)key {
1844 JSValueRef exception(NULL);
1845 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1846 CYThrow(context_, exception);
1847 }
1848
1849 @end
1850
1851 @implementation CYJSArray
1852
1853 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1854 if ((self = [super init]) != nil) {
1855 object_ = object;
1856 context_ = context;
1857 JSValueProtect(context_, object_);
1858 } return self;
1859 }
1860
1861 - (void) dealloc {
1862 JSValueUnprotect(context_, object_);
1863 [super dealloc];
1864 }
1865
1866 - (NSUInteger) count {
1867 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1868 }
1869
1870 - (id) objectAtIndex:(NSUInteger)index {
1871 size_t bounds([self count]);
1872 if (index >= bounds)
1873 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1874 JSValueRef exception(NULL);
1875 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1876 CYThrow(context_, exception);
1877 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1878 }
1879
1880 - (void) addObject:(id)object {
1881 JSValueRef exception(NULL);
1882 JSValueRef arguments[1];
1883 arguments[0] = CYCastJSValue(context_, object);
1884 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1885 CYThrow(context_, exception);
1886 }
1887
1888 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1889 size_t bounds([self count] + 1);
1890 if (index >= bounds)
1891 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1892 JSValueRef exception(NULL);
1893 JSValueRef arguments[3];
1894 arguments[0] = CYCastJSValue(context_, index);
1895 arguments[1] = CYCastJSValue(context_, 0);
1896 arguments[2] = CYCastJSValue(context_, object);
1897 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1898 CYThrow(context_, exception);
1899 }
1900
1901 - (void) removeLastObject {
1902 JSValueRef exception(NULL);
1903 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1904 CYThrow(context_, exception);
1905 }
1906
1907 - (void) removeObjectAtIndex:(NSUInteger)index {
1908 size_t bounds([self count]);
1909 if (index >= bounds)
1910 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1911 JSValueRef exception(NULL);
1912 JSValueRef arguments[2];
1913 arguments[0] = CYCastJSValue(context_, index);
1914 arguments[1] = CYCastJSValue(context_, 1);
1915 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1916 CYThrow(context_, exception);
1917 }
1918
1919 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1920 size_t bounds([self count]);
1921 if (index >= bounds)
1922 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1923 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1924 }
1925
1926 @end
1927 #endif
1928
1929 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1930 if (JSValueIsNull(context, value))
1931 return [@"null" retain];
1932
1933 CYTry {
1934 CYPoolTry {
1935 return [CYCastNSCYON(CYCastNSObject(NULL, context, value)) retain];
1936 } CYPoolCatch(NULL)
1937 } CYCatch
1938 }
1939
1940 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1941 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1942 const char *string(CYPoolCString(pool, json));
1943 [json release];
1944 return string;
1945 } else return NULL;
1946 }
1947
1948 #ifdef __OBJC__
1949 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1950 struct CYInternal :
1951 CYData
1952 {
1953 JSObjectRef object_;
1954
1955 CYInternal() :
1956 object_(NULL)
1957 {
1958 }
1959
1960 ~CYInternal() {
1961 // XXX: delete object_? ;(
1962 }
1963
1964 static CYInternal *Get(id self) {
1965 CYInternal *internal(NULL);
1966 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1967 // XXX: do something epic? ;P
1968 }
1969
1970 return internal;
1971 }
1972
1973 static CYInternal *Set(id self) {
1974 CYInternal *internal(NULL);
1975 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1976 if (internal == NULL) {
1977 internal = new CYInternal();
1978 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1979 }
1980 } else {
1981 // XXX: do something epic? ;P
1982 }
1983
1984 return internal;
1985 }
1986
1987 bool HasProperty(JSContextRef context, JSStringRef name) {
1988 if (object_ == NULL)
1989 return false;
1990 return JSObjectHasProperty(context, object_, name);
1991 }
1992
1993 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1994 if (object_ == NULL)
1995 return NULL;
1996 return CYGetProperty(context, object_, name);
1997 }
1998
1999 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
2000 if (object_ == NULL)
2001 object_ = JSObjectMake(context, NULL, NULL);
2002 CYSetProperty(context, object_, name, value);
2003 }
2004 };
2005 #endif
2006
2007 #ifdef __OBJC__
2008 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
2009 Selector_privateData *internal(new Selector_privateData(sel));
2010 return JSObjectMake(context, Selector_, internal);
2011 }
2012 #endif
2013
2014 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
2015 Pointer *internal(new Pointer(pointer, context, owner, type));
2016 return JSObjectMake(context, Pointer_, internal);
2017 }
2018
2019 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
2020 Functor_privateData *internal(new Functor_privateData(type, function));
2021 return JSObjectMake(context, Functor_, internal);
2022 }
2023
2024 static CYUTF16String CYCastUTF16String(JSStringRef value) {
2025 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
2026 }
2027
2028 // XXX: sometimes pool is null
2029 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSStringRef value) {
2030 CYUTF16String utf16(CYCastUTF16String(value));
2031 const char *in(reinterpret_cast<const char *>(utf16.data));
2032
2033 iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL")));
2034
2035 size_t size(JSStringGetMaximumUTF8CStringSize(value));
2036 char *out(new(pool) char[size]);
2037 CYUTF8String utf8(out, size);
2038
2039 size = utf16.size * 2;
2040 _syscall(iconv(conversion, const_cast<char **>(&in), &size, &out, &utf8.size));
2041
2042 *out = '\0';
2043 utf8.size = out - utf8.data;
2044
2045 _syscall(iconv_close(conversion));
2046
2047 return utf8;
2048 }
2049
2050 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
2051 CYUTF8String utf8(CYPoolUTF8String(pool, value));
2052 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
2053 return utf8.data;
2054 }
2055
2056 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
2057 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
2058 }
2059
2060 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
2061 return CYGetOffset(CYPoolCString(pool, value), index);
2062 }
2063
2064 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
2065 switch (JSValueGetType(context, value)) {
2066 case kJSTypeNull:
2067 return NULL;
2068 /*case kJSTypeString:
2069 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
2070 case kJSTypeObject:
2071 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
2072 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
2073 return internal->value_;
2074 }*/
2075 default:
2076 double number(CYCastDouble(context, value));
2077 if (std::isnan(number))
2078 _throw(NSInvalidArgumentException, "cannot convert value to pointer");
2079 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
2080 }
2081 }
2082
2083 template <typename Type_>
2084 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
2085 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
2086 }
2087
2088 #ifdef __OBJC__
2089 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
2090 if (JSValueIsObjectOfClass(context, value, Selector_)) {
2091 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2092 return reinterpret_cast<SEL>(internal->value_);
2093 } else
2094 return CYCastPointer<SEL>(context, value);
2095 }
2096 #endif
2097
2098 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
2099 switch (type->primitive) {
2100 case sig::boolean_P:
2101 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
2102 break;
2103
2104 #define CYPoolFFI_(primitive, native) \
2105 case sig::primitive ## _P: \
2106 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
2107 break;
2108
2109 CYPoolFFI_(uchar, unsigned char)
2110 CYPoolFFI_(char, char)
2111 CYPoolFFI_(ushort, unsigned short)
2112 CYPoolFFI_(short, short)
2113 CYPoolFFI_(ulong, unsigned long)
2114 CYPoolFFI_(long, long)
2115 CYPoolFFI_(uint, unsigned int)
2116 CYPoolFFI_(int, int)
2117 CYPoolFFI_(ulonglong, unsigned long long)
2118 CYPoolFFI_(longlong, long long)
2119 CYPoolFFI_(float, float)
2120 CYPoolFFI_(double, double)
2121
2122 #ifdef __OBJC__
2123 case sig::object_P:
2124 case sig::typename_P:
2125 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
2126 break;
2127
2128 case sig::selector_P:
2129 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
2130 break;
2131 #endif
2132
2133 case sig::pointer_P:
2134 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
2135 break;
2136
2137 case sig::string_P:
2138 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
2139 break;
2140
2141 case sig::struct_P: {
2142 uint8_t *base(reinterpret_cast<uint8_t *>(data));
2143 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
2144 for (size_t index(0); index != type->data.signature.count; ++index) {
2145 sig::Element *element(&type->data.signature.elements[index]);
2146 ffi_type *field(ffi->elements[index]);
2147
2148 JSValueRef rhs;
2149 if (aggregate == NULL)
2150 rhs = value;
2151 else {
2152 rhs = CYGetProperty(context, aggregate, index);
2153 if (JSValueIsUndefined(context, rhs)) {
2154 if (element->name != NULL)
2155 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
2156 else
2157 goto undefined;
2158 if (JSValueIsUndefined(context, rhs)) undefined:
2159 _throw(NSInvalidArgumentException, "unable to extract structure value");
2160 }
2161 }
2162
2163 CYPoolFFI(pool, context, element->type, field, base, rhs);
2164 // XXX: alignment?
2165 base += field->size;
2166 }
2167 } break;
2168
2169 case sig::void_P:
2170 break;
2171
2172 default:
2173 fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
2174 _assert(false);
2175 }
2176 }
2177
2178 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
2179 JSValueRef value;
2180
2181 switch (type->primitive) {
2182 case sig::boolean_P:
2183 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
2184 break;
2185
2186 #define CYFromFFI_(primitive, native) \
2187 case sig::primitive ## _P: \
2188 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
2189 break;
2190
2191 CYFromFFI_(uchar, unsigned char)
2192 CYFromFFI_(char, char)
2193 CYFromFFI_(ushort, unsigned short)
2194 CYFromFFI_(short, short)
2195 CYFromFFI_(ulong, unsigned long)
2196 CYFromFFI_(long, long)
2197 CYFromFFI_(uint, unsigned int)
2198 CYFromFFI_(int, int)
2199 CYFromFFI_(ulonglong, unsigned long long)
2200 CYFromFFI_(longlong, long long)
2201 CYFromFFI_(float, float)
2202 CYFromFFI_(double, double)
2203
2204 #ifdef __OBJC__
2205 case sig::object_P: {
2206 if (id object = *reinterpret_cast<id *>(data)) {
2207 value = CYCastJSValue(context, object);
2208 if (initialize)
2209 [object release];
2210 } else goto null;
2211 } break;
2212
2213 case sig::typename_P:
2214 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
2215 break;
2216
2217 case sig::selector_P:
2218 if (SEL sel = *reinterpret_cast<SEL *>(data))
2219 value = CYMakeSelector(context, sel);
2220 else goto null;
2221 break;
2222 #endif
2223
2224 case sig::pointer_P:
2225 if (void *pointer = *reinterpret_cast<void **>(data))
2226 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
2227 else goto null;
2228 break;
2229
2230 case sig::string_P:
2231 if (char *utf8 = *reinterpret_cast<char **>(data))
2232 value = CYCastJSValue(context, utf8);
2233 else goto null;
2234 break;
2235
2236 case sig::struct_P:
2237 value = CYMakeStruct(context, data, type, ffi, owner);
2238 break;
2239
2240 case sig::void_P:
2241 value = CYJSUndefined(context);
2242 break;
2243
2244 null:
2245 value = CYJSNull(context);
2246 break;
2247
2248 default:
2249 fprintf(stderr, "CYFromFFI(%c)\n", type->primitive);
2250 _assert(false);
2251 }
2252
2253 return value;
2254 }
2255
2256 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
2257 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
2258 if (!devoid)
2259 return true;
2260 char type[16];
2261 method_getReturnType(method, type, sizeof(type));
2262 if (type[0] != 'v')
2263 return true;
2264 }
2265
2266 // XXX: possibly use a more "awesome" check?
2267 return false;
2268 }
2269
2270 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, objc_method *method) {
2271 if (method != NULL)
2272 return method_getTypeEncoding(method);
2273 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel)])
2274 return CYPoolCString(pool, type);
2275 else
2276 return NULL;
2277 }
2278
2279 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2280 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2281
2282 JSContextRef context(internal->context_);
2283
2284 size_t count(internal->cif_.nargs);
2285 JSValueRef values[count];
2286
2287 for (size_t index(0); index != count; ++index)
2288 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2289
2290 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2291 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2292 }
2293
2294 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2295 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2296
2297 JSContextRef context(internal->context_);
2298
2299 size_t count(internal->cif_.nargs);
2300 JSValueRef values[count];
2301
2302 for (size_t index(0); index != count; ++index)
2303 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2304
2305 JSObjectRef _this(CYCastJSObject(context, values[0]));
2306
2307 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2308 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2309 }
2310
2311 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2312 // XXX: in case of exceptions this will leak
2313 // XXX: in point of fact, this may /need/ to leak :(
2314 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2315
2316 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2317 NULL, sizeof(ffi_closure),
2318 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2319 -1, 0
2320 )));
2321
2322 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2323 _assert(status == FFI_OK);
2324
2325 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2326
2327 internal->value_ = closure;
2328
2329 return internal;
2330 }
2331
2332 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2333 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2334 return JSObjectMake(context, Functor_, internal);
2335 }
2336
2337 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2338 JSValueRef exception(NULL);
2339 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2340 CYThrow(context, exception);
2341
2342 if (function) {
2343 JSObjectRef function(CYCastJSObject(context, value));
2344 return CYMakeFunctor(context, function, type);
2345 } else {
2346 void (*function)()(CYCastPointer<void (*)()>(context, value));
2347 return CYMakeFunctor(context, function, type);
2348 }
2349 }
2350
2351 #ifdef __OBJC__
2352 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2353 Message_privateData *internal(new Message_privateData(sel, type, imp));
2354 return JSObjectMake(context, Message_, internal);
2355 }
2356
2357 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2358 JSObjectRef function(CYCastJSObject(context, value));
2359 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2360 return reinterpret_cast<IMP>(internal->GetValue());
2361 }
2362
2363 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2364 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2365 Class _class(internal->GetValue());
2366
2367 CYPool pool;
2368 const char *name(CYPoolCString(pool, property));
2369
2370 if (SEL sel = sel_getUid(name))
2371 if (class_getInstanceMethod(_class, sel) != NULL)
2372 return true;
2373
2374 return false;
2375 }
2376
2377 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2378 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2379 Class _class(internal->GetValue());
2380
2381 CYPool pool;
2382 const char *name(CYPoolCString(pool, property));
2383
2384 if (SEL sel = sel_getUid(name))
2385 if (objc_method *method = class_getInstanceMethod(_class, sel))
2386 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2387
2388 return NULL;
2389 }
2390
2391 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2392 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2393 Class _class(internal->GetValue());
2394
2395 CYPool pool;
2396 const char *name(CYPoolCString(pool, property));
2397
2398 SEL sel(sel_registerName(name));
2399
2400 objc_method *method(class_getInstanceMethod(_class, sel));
2401
2402 const char *type;
2403 IMP imp;
2404
2405 if (JSValueIsObjectOfClass(context, value, Message_)) {
2406 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2407 type = sig::Unparse(pool, &message->signature_);
2408 imp = reinterpret_cast<IMP>(message->GetValue());
2409 } else {
2410 type = CYPoolTypeEncoding(pool, _class, sel, method);
2411 imp = CYMakeMessage(context, value, type);
2412 }
2413
2414 if (method != NULL)
2415 method_setImplementation(method, imp);
2416 else
2417 class_replaceMethod(_class, sel, imp, type);
2418
2419 return true;
2420 }
2421
2422 #if !__OBJC2__
2423 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2424 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2425 Class _class(internal->GetValue());
2426
2427 CYPool pool;
2428 const char *name(CYPoolCString(pool, property));
2429
2430 if (SEL sel = sel_getUid(name))
2431 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
2432 objc_method_list list = {NULL, 1, {method}};
2433 class_removeMethods(_class, &list);
2434 return true;
2435 }
2436
2437 return false;
2438 }
2439 #endif
2440
2441 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2442 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2443 Class _class(internal->GetValue());
2444
2445 unsigned int size;
2446 objc_method **data(class_copyMethodList(_class, &size));
2447 for (size_t i(0); i != size; ++i)
2448 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2449 free(data);
2450 }
2451
2452 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2453 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2454 id self(internal->GetValue());
2455
2456 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2457 return true;
2458
2459 CYPool pool;
2460 NSString *name(CYCastNSString(pool, property));
2461
2462 if (CYInternal *internal = CYInternal::Get(self))
2463 if (internal->HasProperty(context, property))
2464 return true;
2465
2466 Class _class(object_getClass(self));
2467
2468 CYPoolTry {
2469 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2470 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2471 if ([self cy$hasProperty:name])
2472 return true;
2473 } CYPoolCatch(false)
2474
2475 const char *string(CYPoolCString(pool, name));
2476
2477 if (class_getProperty(_class, string) != NULL)
2478 return true;
2479
2480 if (SEL sel = sel_getUid(string))
2481 if (CYImplements(self, _class, sel, true))
2482 return true;
2483
2484 return false;
2485 }
2486
2487 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2488 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2489 id self(internal->GetValue());
2490
2491 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2492 return Internal::Make(context, self, object);
2493
2494 CYTry {
2495 CYPool pool;
2496 NSString *name(CYCastNSString(pool, property));
2497
2498 if (CYInternal *internal = CYInternal::Get(self))
2499 if (JSValueRef value = internal->GetProperty(context, property))
2500 return value;
2501
2502 CYPoolTry {
2503 if (NSObject *data = [self cy$getProperty:name])
2504 return CYCastJSValue(context, data);
2505 } CYPoolCatch(NULL)
2506
2507 const char *string(CYPoolCString(pool, name));
2508 Class _class(object_getClass(self));
2509
2510 #ifdef __APPLE__
2511 if (objc_property_t property = class_getProperty(_class, string)) {
2512 PropertyAttributes attributes(property);
2513 SEL sel(sel_registerName(attributes.Getter()));
2514 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2515 }
2516 #endif
2517
2518 if (SEL sel = sel_getUid(string))
2519 if (CYImplements(self, _class, sel, true))
2520 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2521
2522 return NULL;
2523 } CYCatch
2524 }
2525
2526 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2527 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2528 id self(internal->GetValue());
2529
2530 CYPool pool;
2531
2532 CYTry {
2533 NSString *name(CYCastNSString(pool, property));
2534 NSObject *data(CYCastNSObject(pool, context, value));
2535
2536 CYPoolTry {
2537 if ([self cy$setProperty:name to:data])
2538 return true;
2539 } CYPoolCatch(NULL)
2540
2541 const char *string(CYPoolCString(pool, name));
2542 Class _class(object_getClass(self));
2543
2544 #ifdef __APPLE__
2545 if (objc_property_t property = class_getProperty(_class, string)) {
2546 PropertyAttributes attributes(property);
2547 if (const char *setter = attributes.Setter()) {
2548 SEL sel(sel_registerName(setter));
2549 JSValueRef arguments[1] = {value};
2550 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2551 return true;
2552 }
2553 }
2554 #endif
2555
2556 size_t length(strlen(string));
2557
2558 char set[length + 5];
2559
2560 set[0] = 's';
2561 set[1] = 'e';
2562 set[2] = 't';
2563
2564 if (string[0] != '\0') {
2565 set[3] = toupper(string[0]);
2566 memcpy(set + 4, string + 1, length - 1);
2567 }
2568
2569 set[length + 3] = ':';
2570 set[length + 4] = '\0';
2571
2572 if (SEL sel = sel_getUid(set))
2573 if (CYImplements(self, _class, sel, false)) {
2574 JSValueRef arguments[1] = {value};
2575 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2576 }
2577
2578 if (CYInternal *internal = CYInternal::Set(self)) {
2579 internal->SetProperty(context, property, value);
2580 return true;
2581 }
2582
2583 return false;
2584 } CYCatch
2585 }
2586
2587 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2588 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2589 id self(internal->GetValue());
2590
2591 CYTry {
2592 CYPoolTry {
2593 NSString *name(CYCastNSString(NULL, property));
2594 return [self cy$deleteProperty:name];
2595 } CYPoolCatch(NULL)
2596 } CYCatch
2597 }
2598
2599 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2600 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2601 id self(internal->GetValue());
2602
2603 CYPool pool;
2604 Class _class(object_getClass(self));
2605
2606 {
2607 unsigned int size;
2608 objc_property_t *data(class_copyPropertyList(_class, &size));
2609 for (size_t i(0); i != size; ++i)
2610 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2611 free(data);
2612 }
2613 }
2614
2615 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2616 CYTry {
2617 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2618 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2619 return value;
2620 } CYCatch
2621 }
2622
2623 static bool CYIsClass(id self) {
2624 // XXX: this is a lame object_isClass
2625 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2626 }
2627
2628 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2629 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2630 Class _class(internal->GetValue());
2631 if (!CYIsClass(_class))
2632 return false;
2633
2634 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2635 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2636 // XXX: this isn't always safe
2637 CYTry {
2638 return [linternal->GetValue() isKindOfClass:_class];
2639 } CYCatch
2640 }
2641
2642 return false;
2643 }
2644
2645 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2646 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2647 CYPool pool;
2648
2649 id self(internal->GetValue());
2650 const char *name(CYPoolCString(pool, property));
2651
2652 if (object_getInstanceVariable(self, name, NULL) != NULL)
2653 return true;
2654
2655 return false;
2656 }
2657
2658 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2659 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2660 CYPool pool;
2661
2662 CYTry {
2663 id self(internal->GetValue());
2664 const char *name(CYPoolCString(pool, property));
2665
2666 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2667 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2668 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2669 }
2670
2671 return NULL;
2672 } CYCatch
2673 }
2674
2675 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2676 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2677 CYPool pool;
2678
2679 CYTry {
2680 id self(internal->GetValue());
2681 const char *name(CYPoolCString(pool, property));
2682
2683 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2684 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2685 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2686 return true;
2687 }
2688
2689 return false;
2690 } CYCatch
2691 }
2692
2693 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2694 if (Class super = class_getSuperclass(_class))
2695 Internal_getPropertyNames_(super, names);
2696
2697 unsigned int size;
2698 Ivar *data(class_copyIvarList(_class, &size));
2699 for (size_t i(0); i != size; ++i)
2700 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2701 free(data);
2702 }
2703
2704 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2705 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2706 CYPool pool;
2707
2708 id self(internal->GetValue());
2709 Class _class(object_getClass(self));
2710
2711 Internal_getPropertyNames_(_class, names);
2712 }
2713
2714 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2715 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2716 return internal->GetOwner();
2717 }
2718 #endif
2719
2720 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2721 Type_privateData *typical(internal->type_);
2722 sig::Type *type(typical->type_);
2723 if (type == NULL)
2724 return false;
2725
2726 const char *name(CYPoolCString(pool, property));
2727 size_t length(strlen(name));
2728 double number(CYCastDouble(name, length));
2729
2730 size_t count(type->data.signature.count);
2731
2732 if (std::isnan(number)) {
2733 if (property == NULL)
2734 return false;
2735
2736 sig::Element *elements(type->data.signature.elements);
2737
2738 for (size_t local(0); local != count; ++local) {
2739 sig::Element *element(&elements[local]);
2740 if (element->name != NULL && strcmp(name, element->name) == 0) {
2741 index = local;
2742 goto base;
2743 }
2744 }
2745
2746 return false;
2747 } else {
2748 index = static_cast<ssize_t>(number);
2749 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2750 return false;
2751 }
2752
2753 base:
2754 ffi_type **elements(typical->GetFFI()->elements);
2755
2756 base = reinterpret_cast<uint8_t *>(internal->value_);
2757 for (ssize_t local(0); local != index; ++local)
2758 base += elements[local]->size;
2759
2760 return true;
2761 }
2762
2763 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2764 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2765 Type_privateData *typical(internal->type_);
2766
2767 ffi_type *ffi(typical->GetFFI());
2768
2769 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2770 base += ffi->size * index;
2771
2772 JSObjectRef owner(internal->GetOwner() ?: object);
2773
2774 CYTry {
2775 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2776 } CYCatch
2777 }
2778
2779 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2780 CYPool pool;
2781 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2782 Type_privateData *typical(internal->type_);
2783
2784 if (typical->type_ == NULL)
2785 return NULL;
2786
2787 ssize_t offset;
2788 if (!CYGetOffset(pool, property, offset))
2789 return NULL;
2790
2791 return Pointer_getIndex(context, object, offset, exception);
2792 }
2793
2794 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2795 return Pointer_getIndex(context, object, 0, exception);
2796 }
2797
2798 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2799 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2800 Type_privateData *typical(internal->type_);
2801
2802 ffi_type *ffi(typical->GetFFI());
2803
2804 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2805 base += ffi->size * index;
2806
2807 CYTry {
2808 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2809 return true;
2810 } CYCatch
2811 }
2812
2813 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2814 CYPool pool;
2815 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2816 Type_privateData *typical(internal->type_);
2817
2818 if (typical->type_ == NULL)
2819 return NULL;
2820
2821 ssize_t offset;
2822 if (!CYGetOffset(pool, property, offset))
2823 return NULL;
2824
2825 return Pointer_setIndex(context, object, offset, value, exception);
2826 }
2827
2828 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2829 return Pointer_setIndex(context, object, 0, value, exception);
2830 }
2831
2832 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2833 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2834 Type_privateData *typical(internal->type_);
2835 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2836 }
2837
2838 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2839 CYPool pool;
2840 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2841 Type_privateData *typical(internal->type_);
2842
2843 ssize_t index;
2844 uint8_t *base;
2845
2846 CYTry {
2847 if (!Index_(pool, internal, property, index, base))
2848 return NULL;
2849
2850 JSObjectRef owner(internal->GetOwner() ?: object);
2851
2852 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2853 } CYCatch
2854 }
2855
2856 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2857 CYPool pool;
2858 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2859 Type_privateData *typical(internal->type_);
2860
2861 ssize_t index;
2862 uint8_t *base;
2863
2864 CYTry {
2865 if (!Index_(pool, internal, property, index, base))
2866 return false;
2867
2868 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2869 return true;
2870 } CYCatch
2871 }
2872
2873 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2874 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2875 Type_privateData *typical(internal->type_);
2876 sig::Type *type(typical->type_);
2877
2878 if (type == NULL)
2879 return;
2880
2881 size_t count(type->data.signature.count);
2882 sig::Element *elements(type->data.signature.elements);
2883
2884 char number[32];
2885
2886 for (size_t index(0); index != count; ++index) {
2887 const char *name;
2888 name = elements[index].name;
2889
2890 if (name == NULL) {
2891 sprintf(number, "%lu", index);
2892 name = number;
2893 }
2894
2895 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2896 }
2897 }
2898
2899 JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
2900 CYTry {
2901 if (setups + count != signature->count - 1)
2902 _throw(NSInvalidArgumentException, "incorrect number of arguments to ffi function");
2903
2904 size_t size(setups + count);
2905 void *values[size];
2906 memcpy(values, setup, sizeof(void *) * setups);
2907
2908 for (size_t index(setups); index != size; ++index) {
2909 sig::Element *element(&signature->elements[index + 1]);
2910 ffi_type *ffi(cif->arg_types[index]);
2911 // XXX: alignment?
2912 values[index] = new(pool) uint8_t[ffi->size];
2913 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2914 }
2915
2916 uint8_t value[cif->rtype->size];
2917 ffi_call(cif, function, value, values);
2918
2919 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2920 } CYCatch
2921 }
2922
2923 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2924 CYTry {
2925 CYPool pool;
2926 NSString *name(CYCastNSString(pool, property));
2927 if (Class _class = NSClassFromString(name))
2928 return CYMakeInstance(context, _class, true);
2929 return NULL;
2930 } CYCatch
2931 }
2932
2933 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2934 size_t size(objc_getClassList(NULL, 0));
2935 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2936
2937 get:
2938 size_t writ(objc_getClassList(data, size));
2939 if (size < writ) {
2940 size = writ;
2941 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2942 data = copy;
2943 goto get;
2944 } else goto done;
2945 }
2946
2947 for (size_t i(0); i != writ; ++i)
2948 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2949
2950 done:
2951 free(data);
2952 }
2953
2954 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2955 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2956
2957 CYTry {
2958 CYPool pool;
2959 const char *name(CYPoolCString(pool, property));
2960 unsigned int size;
2961 const char **data(objc_copyClassNamesForImage(internal, &size));
2962 JSValueRef value;
2963 for (size_t i(0); i != size; ++i)
2964 if (strcmp(name, data[i]) == 0) {
2965 if (Class _class = objc_getClass(name)) {
2966 value = CYMakeInstance(context, _class, true);
2967 goto free;
2968 } else
2969 break;
2970 }
2971 value = NULL;
2972 free:
2973 free(data);
2974 return value;
2975 } CYCatch
2976 }
2977
2978 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2979 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2980 unsigned int size;
2981 const char **data(objc_copyClassNamesForImage(internal, &size));
2982 for (size_t i(0); i != size; ++i)
2983 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2984 free(data);
2985 }
2986
2987 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2988 CYTry {
2989 CYPool pool;
2990 const char *name(CYPoolCString(pool, property));
2991 unsigned int size;
2992 const char **data(objc_copyImageNames(&size));
2993 for (size_t i(0); i != size; ++i)
2994 if (strcmp(name, data[i]) == 0) {
2995 name = data[i];
2996 goto free;
2997 }
2998 name = NULL;
2999 free:
3000 free(data);
3001 if (name == NULL)
3002 return NULL;
3003 JSObjectRef value(JSObjectMake(context, NULL, NULL));
3004 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
3005 return value;
3006 } CYCatch
3007 }
3008
3009 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3010 unsigned int size;
3011 const char **data(objc_copyImageNames(&size));
3012 for (size_t i(0); i != size; ++i)
3013 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3014 free(data);
3015 }
3016
3017 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3018 CYTry {
3019 CYPool pool;
3020 NSString *name(CYCastNSString(pool, property));
3021 if (Protocol *protocol = NSProtocolFromString(name))
3022 return CYMakeInstance(context, protocol, true);
3023 return NULL;
3024 } CYCatch
3025 }
3026
3027 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3028 unsigned int size;
3029 Protocol **data(objc_copyProtocolList(&size));
3030 for (size_t i(0); i != size; ++i)
3031 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
3032 free(data);
3033 }
3034
3035 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
3036 Type_privateData *internal(new Type_privateData(NULL, type));
3037 return JSObjectMake(context, Type_privateData::Class_, internal);
3038 }
3039
3040 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
3041 Type_privateData *internal(new Type_privateData(type));
3042 return JSObjectMake(context, Type_privateData::Class_, internal);
3043 }
3044
3045 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3046 if (JSStringIsEqualToUTF8CString(property, "nil"))
3047 return Instance::Make(context, nil);
3048
3049 CYTry {
3050 CYPool pool;
3051 NSString *name(CYCastNSString(pool, property));
3052 if (Class _class = NSClassFromString(name))
3053 return CYMakeInstance(context, _class, true);
3054 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
3055 switch ([[entry objectAtIndex:0] intValue]) {
3056 case 0:
3057 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
3058 case 1:
3059 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
3060 case 2:
3061 // XXX: this is horrendously inefficient
3062 sig::Signature signature;
3063 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
3064 ffi_cif cif;
3065 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3066 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
3067 }
3068 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
3069 switch ([[entry objectAtIndex:0] intValue]) {
3070 // XXX: implement case 0
3071 case 1:
3072 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
3073 }
3074 return NULL;
3075 } CYCatch
3076 }
3077
3078 static bool stret(ffi_type *ffi_type) {
3079 return ffi_type->type == FFI_TYPE_STRUCT && (
3080 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
3081 struct_forward_array[ffi_type->size] != 0
3082 );
3083 }
3084
3085 extern "C" {
3086 int *_NSGetArgc(void);
3087 char ***_NSGetArgv(void);
3088 }
3089
3090 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3091 CYTry {
3092 if (count == 0)
3093 printf("\n");
3094 else
3095 printf("%s\n", CYCastCString(context, arguments[0]));
3096 return CYJSUndefined(context);
3097 } CYCatch
3098 }
3099
3100 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
3101 const char *type;
3102
3103 Class _class(object_getClass(self));
3104 if (objc_method *method = class_getInstanceMethod(_class, _cmd))
3105 type = method_getTypeEncoding(method);
3106 else {
3107 CYTry {
3108 CYPoolTry {
3109 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
3110 if (method == nil)
3111 _throw(NSInvalidArgumentException, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3112 type = CYPoolCString(pool, [method _typeString]);
3113 } CYPoolCatch(NULL)
3114 } CYCatch
3115 }
3116
3117 void *setup[2];
3118 setup[0] = &self;
3119 setup[1] = &_cmd;
3120
3121 sig::Signature signature;
3122 sig::Parse(pool, &signature, type, &Structor_);
3123
3124 ffi_cif cif;
3125 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3126
3127 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
3128 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3129 }
3130
3131 static size_t Nonce_(0);
3132
3133 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3134 char name[16];
3135 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
3136 return CYCastJSValue(context, name);
3137 }
3138
3139 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3140 CYPool pool;
3141
3142 bool uninitialized;
3143
3144 id self;
3145 SEL _cmd;
3146
3147 CYTry {
3148 if (count < 2)
3149 _throw(NSInvalidArgumentException, "too few arguments to objc_msgSend");
3150
3151 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
3152 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3153 self = internal->GetValue();
3154 uninitialized = internal->IsUninitialized();
3155 if (uninitialized)
3156 internal->value_ = nil;
3157 } else {
3158 self = CYCastNSObject(pool, context, arguments[0]);
3159 uninitialized = false;
3160 }
3161
3162 if (self == nil)
3163 return CYJSNull(context);
3164
3165 _cmd = CYCastSEL(context, arguments[1]);
3166 } CYCatch
3167
3168 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
3169 }
3170
3171 #ifdef __OBJC__
3172 /* Hook: objc_registerClassPair {{{ */
3173 // XXX: replace this with associated objects
3174
3175 MSHook(void, CYDealloc, id self, SEL sel) {
3176 CYInternal *internal;
3177 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
3178 if (internal != NULL)
3179 delete internal;
3180 _CYDealloc(self, sel);
3181 }
3182
3183 MSHook(void, objc_registerClassPair, Class _class) {
3184 Class super(class_getSuperclass(_class));
3185 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
3186 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
3187 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
3188 }
3189
3190 _objc_registerClassPair(_class);
3191 }
3192
3193 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3194 CYTry {
3195 if (count != 1)
3196 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3197 CYPool pool;
3198 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3199 if (value == NULL || !CYIsClass(value))
3200 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3201 Class _class((Class) value);
3202 $objc_registerClassPair(_class);
3203 return CYJSUndefined(context);
3204 } CYCatch
3205 }
3206 /* }}} */
3207 #endif
3208
3209 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3210 JSGarbageCollect(context);
3211 return CYJSUndefined(context);
3212 }
3213
3214 #ifdef __OBJC__
3215 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3216 JSValueRef setup[count + 2];
3217 setup[0] = _this;
3218 setup[1] = object;
3219 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
3220 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
3221 }
3222
3223 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3224 CYPool pool;
3225 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
3226
3227 // XXX: handle Instance::Uninitialized?
3228 id self(CYCastNSObject(pool, context, _this));
3229
3230 void *setup[2];
3231 setup[0] = &self;
3232 setup[1] = &internal->sel_;
3233
3234 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3235 }
3236 #endif
3237
3238 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3239 CYPool pool;
3240 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
3241 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3242 }
3243
3244 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3245 CYTry {
3246 if (count != 1)
3247 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector constructor");
3248 const char *name(CYCastCString(context, arguments[0]));
3249 return CYMakeSelector(context, sel_registerName(name));
3250 } CYCatch
3251 }
3252
3253 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3254 CYTry {
3255 if (count != 2)
3256 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3257
3258 void *value(CYCastPointer<void *>(context, arguments[0]));
3259 const char *type(CYCastCString(context, arguments[1]));
3260
3261 CYPool pool;
3262
3263 sig::Signature signature;
3264 sig::Parse(pool, &signature, type, &Structor_);
3265
3266 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
3267 } CYCatch
3268 }
3269
3270 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3271 CYTry {
3272 if (count != 1)
3273 _throw(NSInvalidArgumentException, "incorrect number of arguments to Type constructor");
3274 const char *type(CYCastCString(context, arguments[0]));
3275 return CYMakeType(context, type);
3276 } CYCatch
3277 }
3278
3279 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3280 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3281
3282 CYTry {
3283 sig::Type type;
3284
3285 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3286 type.primitive = sig::pointer_P;
3287 type.data.data.size = 0;
3288 } else {
3289 size_t index(CYGetIndex(NULL, property));
3290 if (index == _not(size_t))
3291 return NULL;
3292 type.primitive = sig::array_P;
3293 type.data.data.size = index;
3294 }
3295
3296 type.name = NULL;
3297 type.flags = 0;
3298
3299 type.data.data.type = internal->type_;
3300
3301 return CYMakeType(context, &type);
3302 } CYCatch
3303 }
3304
3305 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3306 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3307
3308 CYTry {
3309 if (count != 1)
3310 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3311 sig::Type *type(internal->type_);
3312 ffi_type *ffi(internal->GetFFI());
3313 // XXX: alignment?
3314 uint8_t value[ffi->size];
3315 CYPool pool;
3316 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3317 return CYFromFFI(context, type, ffi, value);
3318 } CYCatch
3319 }
3320
3321 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3322 CYTry {
3323 if (count != 0)
3324 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3325 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3326
3327 sig::Type *type(internal->type_);
3328 size_t size;
3329
3330 if (type->primitive != sig::array_P)
3331 size = 0;
3332 else {
3333 size = type->data.data.size;
3334 type = type->data.data.type;
3335 }
3336
3337 void *value(malloc(internal->GetFFI()->size));
3338 return CYMakePointer(context, value, type, NULL, NULL);
3339 } CYCatch
3340 }
3341
3342 #ifdef __OBJC__
3343 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3344 CYTry {
3345 if (count > 1)
3346 _throw(NSInvalidArgumentException, "incorrect number of arguments to Instance constructor");
3347 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3348 return Instance::Make(context, self);
3349 } CYCatch
3350 }
3351 #endif
3352
3353 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3354 CYTry {
3355 if (count != 2)
3356 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3357 const char *type(CYCastCString(context, arguments[1]));
3358 return CYMakeFunctor(context, arguments[0], type);
3359 } CYCatch
3360 }
3361
3362 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3363 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3364 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3365 }
3366
3367 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3368 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3369 Type_privateData *typical(internal->GetType());
3370
3371 sig::Type *type;
3372 ffi_type *ffi;
3373
3374 if (typical == NULL) {
3375 type = NULL;
3376 ffi = NULL;
3377 } else {
3378 type = typical->type_;
3379 ffi = typical->ffi_;
3380 }
3381
3382 return CYMakePointer(context, &internal->value_, type, ffi, object);
3383 }
3384
3385 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3386 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3387
3388 CYTry {
3389 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3390 } CYCatch
3391 }
3392
3393 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3394 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3395 }
3396
3397 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3398 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3399 char string[32];
3400 sprintf(string, "%p", internal->value_);
3401
3402 CYTry {
3403 return CYCastJSValue(context, string);
3404 } CYCatch
3405 }
3406
3407 #ifdef __OBJC__
3408 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3409 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3410 return Instance::Make(context, object_getClass(internal->GetValue()));
3411 }
3412
3413 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3414 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3415 id self(internal->GetValue());
3416 if (!CYIsClass(self))
3417 return CYJSUndefined(context);
3418 CYTry {
3419 return CYGetClassPrototype(context, self);
3420 } CYCatch
3421 }
3422
3423 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3424 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3425 id self(internal->GetValue());
3426 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3427 return CYJSUndefined(context);
3428 return Messages::Make(context, self);
3429 }
3430
3431 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3432 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3433 return NULL;
3434
3435 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3436
3437 CYTry {
3438 CYPoolTry {
3439 return CYCastJSValue(context, CYJSString(CYCastNSCYON(internal->GetValue())));
3440 } CYPoolCatch(NULL)
3441 } CYCatch
3442 }
3443
3444 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3445 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3446 return NULL;
3447
3448 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3449
3450 CYTry {
3451 CYPoolTry {
3452 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3453 // XXX: check for support of cy$toJSON?
3454 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3455 } CYPoolCatch(NULL)
3456 } CYCatch
3457 }
3458
3459 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3460 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3461 return NULL;
3462
3463 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3464
3465 CYTry {
3466 CYPoolTry {
3467 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3468 } CYPoolCatch(NULL)
3469 } CYCatch
3470 }
3471
3472 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3473 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3474
3475 CYTry {
3476 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3477 } CYCatch
3478 }
3479
3480 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3481 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3482 }
3483
3484 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3485 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3486 const char *name(sel_getName(internal->GetValue()));
3487
3488 CYTry {
3489 CYPoolTry {
3490 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3491 } CYPoolCatch(NULL)
3492 } CYCatch
3493 }
3494
3495 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3496 CYTry {
3497 if (count != 1)
3498 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector.type");
3499 CYPool pool;
3500 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3501 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3502 if (value == NULL) lookup:
3503 // XXX: do a lookup of some kind
3504 return CYJSNull(context);
3505 else if (!CYIsClass(value))
3506 _throw(NSInvalidArgumentException, "Selector.type takes a Class");
3507 else {
3508 Class _class((Class) value);
3509 SEL sel(internal->GetValue());
3510 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
3511 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3512 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3513 } else goto lookup;
3514 }
3515 } CYCatch
3516 }
3517 #endif
3518
3519 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3520 CYTry {
3521 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3522 CYPool pool;
3523 const char *type(sig::Unparse(pool, internal->type_));
3524 return CYCastJSValue(context, CYJSString(type));
3525 } CYCatch
3526 }
3527
3528 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3529 CYTry {
3530 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3531 CYPool pool;
3532 const char *type(sig::Unparse(pool, internal->type_));
3533 size_t size(strlen(type));
3534 char *cyon(new(pool) char[12 + size + 1]);
3535 memcpy(cyon, "new Type(\"", 10);
3536 cyon[12 + size] = '\0';
3537 cyon[12 + size - 2] = '"';
3538 cyon[12 + size - 1] = ')';
3539 memcpy(cyon + 10, type, size);
3540 return CYCastJSValue(context, CYJSString(cyon));
3541 } CYCatch
3542 }
3543
3544 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3545 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3546 }
3547
3548 static JSStaticValue CYValue_staticValues[2] = {
3549 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3550 {NULL, NULL, NULL, 0}
3551 };
3552
3553 static JSStaticValue Pointer_staticValues[2] = {
3554 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3555 {NULL, NULL, NULL, 0}
3556 };
3557
3558 static JSStaticFunction Pointer_staticFunctions[4] = {
3559 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3560 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3561 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3562 {NULL, NULL, 0}
3563 };
3564
3565 static JSStaticFunction Struct_staticFunctions[2] = {
3566 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3567 {NULL, NULL, 0}
3568 };
3569
3570 static JSStaticFunction Functor_staticFunctions[4] = {
3571 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3572 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3573 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3574 {NULL, NULL, 0}
3575 };
3576
3577 #ifdef __OBJC__
3578 static JSStaticValue Instance_staticValues[5] = {
3579 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3580 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3581 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3582 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3583 {NULL, NULL, NULL, 0}
3584 };
3585
3586 static JSStaticFunction Instance_staticFunctions[5] = {
3587 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3588 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3589 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3590 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3591 {NULL, NULL, 0}
3592 };
3593
3594 static JSStaticFunction Internal_staticFunctions[2] = {
3595 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3596 {NULL, NULL, 0}
3597 };
3598
3599 static JSStaticFunction Selector_staticFunctions[5] = {
3600 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3601 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3602 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3603 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3604 {NULL, NULL, 0}
3605 };
3606 #endif
3607
3608 static JSStaticFunction Type_staticFunctions[4] = {
3609 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3610 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3611 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3612 {NULL, NULL, 0}
3613 };
3614
3615 void CYSetArgs(int argc, const char *argv[]) {
3616 JSContextRef context(CYGetJSContext());
3617 JSValueRef args[argc];
3618 for (int i(0); i != argc; ++i)
3619 args[i] = CYCastJSValue(context, argv[i]);
3620 JSValueRef exception(NULL);
3621 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3622 CYThrow(context, exception);
3623 CYSetProperty(context, System_, CYJSString("args"), array);
3624 }
3625
3626 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3627 return JSContextGetGlobalObject(context);
3628 }
3629
3630 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3631 JSContextRef context(CYGetJSContext());
3632 JSValueRef exception(NULL), result;
3633
3634 try {
3635 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3636 } catch (const char *error) {
3637 return error;
3638 }
3639
3640 if (exception != NULL) { error:
3641 result = exception;
3642 exception = NULL;
3643 }
3644
3645 if (JSValueIsUndefined(context, result))
3646 return NULL;
3647
3648 const char *json;
3649
3650 try {
3651 json = CYPoolCCYON(pool, context, result, &exception);
3652 } catch (const char *error) {
3653 return error;
3654 }
3655
3656 if (exception != NULL)
3657 goto error;
3658
3659 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3660 return json;
3661 }
3662
3663 static apr_pool_t *Pool_;
3664
3665 apr_pool_t *CYGetGlobalPool() {
3666 return Pool_;
3667 }
3668
3669 MSInitialize { _pooled
3670 _aprcall(apr_initialize());
3671 _aprcall(apr_pool_create(&Pool_, NULL));
3672
3673 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3674
3675 #ifdef __OBJC__
3676 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3677 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3678
3679 #ifdef __APPLE__
3680 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3681 NSCFType_ = objc_getClass("NSCFType");
3682 #endif
3683
3684 NSArray_ = objc_getClass("NSArray");
3685 NSDictionary_ = objc_getClass("NSDictonary");
3686 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3687 NSZombie_ = objc_getClass("_NSZombie_");
3688 Object_ = objc_getClass("Object");
3689 #endif
3690 }
3691
3692 JSGlobalContextRef CYGetJSContext() {
3693 if (Context_ == NULL) {
3694 JSClassDefinition definition;
3695
3696 definition = kJSClassDefinitionEmpty;
3697 definition.className = "Functor";
3698 definition.staticFunctions = Functor_staticFunctions;
3699 definition.callAsFunction = &Functor_callAsFunction;
3700 definition.finalize = &Finalize;
3701 Functor_ = JSClassCreate(&definition);
3702
3703 definition = kJSClassDefinitionEmpty;
3704 definition.className = "Pointer";
3705 definition.staticValues = Pointer_staticValues;
3706 definition.staticFunctions = Pointer_staticFunctions;
3707 definition.getProperty = &Pointer_getProperty;
3708 definition.setProperty = &Pointer_setProperty;
3709 definition.finalize = &Finalize;
3710 Pointer_ = JSClassCreate(&definition);
3711
3712 definition = kJSClassDefinitionEmpty;
3713 definition.className = "Selector";
3714 definition.staticValues = CYValue_staticValues;
3715 definition.staticFunctions = Selector_staticFunctions;
3716 definition.callAsFunction = &Selector_callAsFunction;
3717 definition.finalize = &Finalize;
3718 Selector_ = JSClassCreate(&definition);
3719
3720 definition = kJSClassDefinitionEmpty;
3721 definition.className = "Struct";
3722 definition.staticFunctions = Struct_staticFunctions;
3723 definition.getProperty = &Struct_getProperty;
3724 definition.setProperty = &Struct_setProperty;
3725 definition.getPropertyNames = &Struct_getPropertyNames;
3726 definition.finalize = &Finalize;
3727 Struct_ = JSClassCreate(&definition);
3728
3729 definition = kJSClassDefinitionEmpty;
3730 definition.className = "Type";
3731 definition.staticFunctions = Type_staticFunctions;
3732 definition.getProperty = &Type_getProperty;
3733 definition.callAsFunction = &Type_callAsFunction;
3734 definition.callAsConstructor = &Type_callAsConstructor;
3735 definition.finalize = &Finalize;
3736 Type_privateData::Class_ = JSClassCreate(&definition);
3737
3738 definition = kJSClassDefinitionEmpty;
3739 definition.className = "Runtime";
3740 definition.getProperty = &Runtime_getProperty;
3741 Runtime_ = JSClassCreate(&definition);
3742
3743 definition = kJSClassDefinitionEmpty;
3744 //definition.getProperty = &Global_getProperty;
3745 JSClassRef Global(JSClassCreate(&definition));
3746
3747 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3748 Context_ = context;
3749 JSObjectRef global(CYGetGlobalObject(context));
3750
3751 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3752
3753 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3754 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3755 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3756
3757 length_ = JSStringCreateWithUTF8CString("length");
3758 message_ = JSStringCreateWithUTF8CString("message");
3759 name_ = JSStringCreateWithUTF8CString("name");
3760 prototype_ = JSStringCreateWithUTF8CString("prototype");
3761 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3762 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3763
3764 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3765 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3766
3767 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3768 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3769 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3770 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3771
3772 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3773
3774 /* Objective-C Classes {{{ */
3775 #ifdef __OBJC__
3776 definition = kJSClassDefinitionEmpty;
3777 definition.className = "Instance";
3778 definition.staticValues = Instance_staticValues;
3779 definition.staticFunctions = Instance_staticFunctions;
3780 definition.hasProperty = &Instance_hasProperty;
3781 definition.getProperty = &Instance_getProperty;
3782 definition.setProperty = &Instance_setProperty;
3783 definition.deleteProperty = &Instance_deleteProperty;
3784 definition.getPropertyNames = &Instance_getPropertyNames;
3785 definition.callAsConstructor = &Instance_callAsConstructor;
3786 definition.hasInstance = &Instance_hasInstance;
3787 definition.finalize = &Finalize;
3788 Instance_ = JSClassCreate(&definition);
3789
3790 definition = kJSClassDefinitionEmpty;
3791 definition.className = "Internal";
3792 definition.staticFunctions = Internal_staticFunctions;
3793 definition.hasProperty = &Internal_hasProperty;
3794 definition.getProperty = &Internal_getProperty;
3795 definition.setProperty = &Internal_setProperty;
3796 definition.getPropertyNames = &Internal_getPropertyNames;
3797 definition.finalize = &Finalize;
3798 Internal_ = JSClassCreate(&definition);
3799
3800 definition = kJSClassDefinitionEmpty;
3801 definition.className = "Message";
3802 definition.staticFunctions = Functor_staticFunctions;
3803 definition.callAsFunction = &Message_callAsFunction;
3804 definition.finalize = &Finalize;
3805 Message_ = JSClassCreate(&definition);
3806
3807 definition = kJSClassDefinitionEmpty;
3808 definition.className = "Messages";
3809 definition.hasProperty = &Messages_hasProperty;
3810 definition.getProperty = &Messages_getProperty;
3811 definition.setProperty = &Messages_setProperty;
3812 #if !__OBJC2__
3813 definition.deleteProperty = &Messages_deleteProperty;
3814 #endif
3815 definition.getPropertyNames = &Messages_getPropertyNames;
3816 definition.finalize = &Finalize;
3817 Messages_ = JSClassCreate(&definition);
3818 definition = kJSClassDefinitionEmpty;
3819
3820 definition.className = "ObjectiveC::Classes";
3821 definition.getProperty = &ObjectiveC_Classes_getProperty;
3822 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3823 ObjectiveC_Classes_ = JSClassCreate(&definition);
3824
3825 definition = kJSClassDefinitionEmpty;
3826 definition.className = "ObjectiveC::Images";
3827 definition.getProperty = &ObjectiveC_Images_getProperty;
3828 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3829 ObjectiveC_Images_ = JSClassCreate(&definition);
3830
3831 definition = kJSClassDefinitionEmpty;
3832 definition.className = "ObjectiveC::Image::Classes";
3833 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3834 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3835 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3836
3837 definition = kJSClassDefinitionEmpty;
3838 definition.className = "ObjectiveC::Protocols";
3839 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3840 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3841 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3842
3843 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3844 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3845
3846 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3847 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3848 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3849
3850 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3851 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3852 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3853
3854 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3855 JSValueProtect(context, Instance_prototype_);
3856
3857 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3858 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3859
3860 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3861 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3862 #endif
3863 /* }}} */
3864
3865 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3866 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3867 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3868 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3869
3870 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3871 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3872 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
3873
3874 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3875
3876 #ifdef __OBJC__
3877 #ifdef __APPLE__
3878 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3879 #endif
3880 #endif
3881
3882 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
3883 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
3884 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
3885
3886 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3887
3888 System_ = JSObjectMake(context, NULL, NULL);
3889 CYSetProperty(context, global, CYJSString("system"), System_);
3890 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3891 //CYSetProperty(context, System_, CYJSString("global"), global);
3892
3893 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3894
3895 Result_ = JSStringCreateWithUTF8CString("_");
3896
3897 JSValueProtect(context, Array_);
3898 JSValueProtect(context, Function_);
3899 JSValueProtect(context, String_);
3900
3901 JSValueProtect(context, Object_prototype_);
3902
3903 JSValueProtect(context, Array_prototype_);
3904 JSValueProtect(context, Array_pop_);
3905 JSValueProtect(context, Array_push_);
3906 JSValueProtect(context, Array_splice_);
3907 }
3908
3909 return Context_;
3910 }