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