]> git.saurik.com Git - cycript.git/blob - Library.mm
3f88ae6c38cdbc26b23be0820069710572f96bae
[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 // XXX: this is, sadly, going to leak
2140 // XXX: shouldn't this be done with .length?!
2141 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, _this));
2142
2143 bool comma(false);
2144
2145 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
2146 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
2147 JSValueRef value(CYGetProperty(context, _this, name));
2148
2149 if (comma)
2150 str << ',';
2151 else
2152 comma = true;
2153
2154 if (!JSValueIsUndefined(context, value))
2155 str << CYPoolCCYON(pool, context, value);
2156 else {
2157 str << ',';
2158 comma = false;
2159 }
2160 }
2161
2162 str << ']';
2163
2164 JSPropertyNameArrayRelease(names);
2165
2166 std::string value(str.str());
2167 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
2168 } CYCatch }
2169
2170 #ifdef __OBJC__
2171 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
2172 struct CYInternal :
2173 CYData
2174 {
2175 JSObjectRef object_;
2176
2177 CYInternal() :
2178 object_(NULL)
2179 {
2180 }
2181
2182 ~CYInternal() {
2183 // XXX: delete object_? ;(
2184 }
2185
2186 static CYInternal *Get(id self) {
2187 CYInternal *internal(NULL);
2188 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
2189 // XXX: do something epic? ;P
2190 }
2191
2192 return internal;
2193 }
2194
2195 static CYInternal *Set(id self) {
2196 CYInternal *internal(NULL);
2197 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
2198 if (internal == NULL) {
2199 internal = new CYInternal();
2200 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
2201 }
2202 } else {
2203 // XXX: do something epic? ;P
2204 }
2205
2206 return internal;
2207 }
2208
2209 bool HasProperty(JSContextRef context, JSStringRef name) {
2210 if (object_ == NULL)
2211 return false;
2212 return JSObjectHasProperty(context, object_, name);
2213 }
2214
2215 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
2216 if (object_ == NULL)
2217 return NULL;
2218 return CYGetProperty(context, object_, name);
2219 }
2220
2221 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
2222 if (object_ == NULL)
2223 object_ = JSObjectMake(context, NULL, NULL);
2224 CYSetProperty(context, object_, name, value);
2225 }
2226 };
2227 #endif
2228
2229 #ifdef __OBJC__
2230 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
2231 Selector_privateData *internal(new Selector_privateData(sel));
2232 return JSObjectMake(context, Selector_, internal);
2233 }
2234 #endif
2235
2236 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
2237 Pointer *internal(new Pointer(pointer, context, owner, type));
2238 return JSObjectMake(context, Pointer_, internal);
2239 }
2240
2241 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
2242 Functor_privateData *internal(new Functor_privateData(type, function));
2243 return JSObjectMake(context, Functor_, internal);
2244 }
2245
2246 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
2247 return CYGetOffset(CYPoolCString(pool, value), index);
2248 }
2249
2250 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
2251 switch (JSValueGetType(context, value)) {
2252 case kJSTypeNull:
2253 return NULL;
2254 /*case kJSTypeString:
2255 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
2256 case kJSTypeObject:
2257 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
2258 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
2259 return internal->value_;
2260 }*/
2261 default:
2262 double number(CYCastDouble(context, value));
2263 if (std::isnan(number))
2264 _throw(NSInvalidArgumentException, "cannot convert value to pointer");
2265 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
2266 }
2267 }
2268
2269 template <typename Type_>
2270 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
2271 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
2272 }
2273
2274 #ifdef __OBJC__
2275 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
2276 if (JSValueIsObjectOfClass(context, value, Selector_)) {
2277 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2278 return reinterpret_cast<SEL>(internal->value_);
2279 } else
2280 return CYCastPointer<SEL>(context, value);
2281 }
2282 #endif
2283
2284 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
2285 switch (type->primitive) {
2286 case sig::boolean_P:
2287 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
2288 break;
2289
2290 #define CYPoolFFI_(primitive, native) \
2291 case sig::primitive ## _P: \
2292 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
2293 break;
2294
2295 CYPoolFFI_(uchar, unsigned char)
2296 CYPoolFFI_(char, char)
2297 CYPoolFFI_(ushort, unsigned short)
2298 CYPoolFFI_(short, short)
2299 CYPoolFFI_(ulong, unsigned long)
2300 CYPoolFFI_(long, long)
2301 CYPoolFFI_(uint, unsigned int)
2302 CYPoolFFI_(int, int)
2303 CYPoolFFI_(ulonglong, unsigned long long)
2304 CYPoolFFI_(longlong, long long)
2305 CYPoolFFI_(float, float)
2306 CYPoolFFI_(double, double)
2307
2308 #ifdef __OBJC__
2309 case sig::object_P:
2310 case sig::typename_P:
2311 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
2312 break;
2313
2314 case sig::selector_P:
2315 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
2316 break;
2317 #endif
2318
2319 case sig::pointer_P:
2320 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
2321 break;
2322
2323 case sig::string_P:
2324 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
2325 break;
2326
2327 case sig::struct_P: {
2328 uint8_t *base(reinterpret_cast<uint8_t *>(data));
2329 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
2330 for (size_t index(0); index != type->data.signature.count; ++index) {
2331 sig::Element *element(&type->data.signature.elements[index]);
2332 ffi_type *field(ffi->elements[index]);
2333
2334 JSValueRef rhs;
2335 if (aggregate == NULL)
2336 rhs = value;
2337 else {
2338 rhs = CYGetProperty(context, aggregate, index);
2339 if (JSValueIsUndefined(context, rhs)) {
2340 if (element->name != NULL)
2341 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
2342 else
2343 goto undefined;
2344 if (JSValueIsUndefined(context, rhs)) undefined:
2345 _throw(NSInvalidArgumentException, "unable to extract structure value");
2346 }
2347 }
2348
2349 CYPoolFFI(pool, context, element->type, field, base, rhs);
2350 // XXX: alignment?
2351 base += field->size;
2352 }
2353 } break;
2354
2355 case sig::void_P:
2356 break;
2357
2358 default:
2359 fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
2360 _assert(false);
2361 }
2362 }
2363
2364 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
2365 JSValueRef value;
2366
2367 switch (type->primitive) {
2368 case sig::boolean_P:
2369 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
2370 break;
2371
2372 #define CYFromFFI_(primitive, native) \
2373 case sig::primitive ## _P: \
2374 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
2375 break;
2376
2377 CYFromFFI_(uchar, unsigned char)
2378 CYFromFFI_(char, char)
2379 CYFromFFI_(ushort, unsigned short)
2380 CYFromFFI_(short, short)
2381 CYFromFFI_(ulong, unsigned long)
2382 CYFromFFI_(long, long)
2383 CYFromFFI_(uint, unsigned int)
2384 CYFromFFI_(int, int)
2385 CYFromFFI_(ulonglong, unsigned long long)
2386 CYFromFFI_(longlong, long long)
2387 CYFromFFI_(float, float)
2388 CYFromFFI_(double, double)
2389
2390 #ifdef __OBJC__
2391 case sig::object_P: {
2392 if (id object = *reinterpret_cast<id *>(data)) {
2393 value = CYCastJSValue(context, object);
2394 if (initialize)
2395 [object release];
2396 } else goto null;
2397 } break;
2398
2399 case sig::typename_P:
2400 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
2401 break;
2402
2403 case sig::selector_P:
2404 if (SEL sel = *reinterpret_cast<SEL *>(data))
2405 value = CYMakeSelector(context, sel);
2406 else goto null;
2407 break;
2408 #endif
2409
2410 case sig::pointer_P:
2411 if (void *pointer = *reinterpret_cast<void **>(data))
2412 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
2413 else goto null;
2414 break;
2415
2416 case sig::string_P:
2417 if (char *utf8 = *reinterpret_cast<char **>(data))
2418 value = CYCastJSValue(context, utf8);
2419 else goto null;
2420 break;
2421
2422 case sig::struct_P:
2423 value = CYMakeStruct(context, data, type, ffi, owner);
2424 break;
2425
2426 case sig::void_P:
2427 value = CYJSUndefined(context);
2428 break;
2429
2430 null:
2431 value = CYJSNull(context);
2432 break;
2433
2434 default:
2435 fprintf(stderr, "CYFromFFI(%c)\n", type->primitive);
2436 _assert(false);
2437 }
2438
2439 return value;
2440 }
2441
2442 #ifdef __OBJC__
2443 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
2444 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
2445 if (!devoid)
2446 return true;
2447 char type[16];
2448 method_getReturnType(method, type, sizeof(type));
2449 if (type[0] != 'v')
2450 return true;
2451 }
2452
2453 // XXX: possibly use a more "awesome" check?
2454 return false;
2455 }
2456 #endif
2457
2458 #ifdef __OBJC__
2459 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, objc_method *method) {
2460 if (method != NULL)
2461 return method_getTypeEncoding(method);
2462
2463 const char *name(sel_getName(sel));
2464
2465 sqlite3_stmt *statement;
2466
2467 _sqlcall(sqlite3_prepare(Bridge_,
2468 "select "
2469 "\"bridge\".\"mode\", "
2470 "\"bridge\".\"value\" "
2471 "from \"bridge\" "
2472 "where"
2473 " \"bridge\".\"mode\" in (3, 4) and"
2474 " \"bridge\".\"name\" = ?"
2475 " limit 1"
2476 , -1, &statement, NULL));
2477
2478 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
2479
2480 int mode;
2481 const char *value;
2482
2483 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
2484 mode = -1;
2485 value = NULL;
2486 } else {
2487 mode = sqlite3_column_int(statement, 0);
2488 value = sqlite3_column_pooled(pool, statement, 1);
2489 }
2490
2491 _sqlcall(sqlite3_finalize(statement));
2492
2493 if (value != NULL)
2494 return value;
2495
2496 return NULL;
2497 }
2498 #endif
2499
2500 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2501 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2502
2503 JSContextRef context(internal->context_);
2504
2505 size_t count(internal->cif_.nargs);
2506 JSValueRef values[count];
2507
2508 for (size_t index(0); index != count; ++index)
2509 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2510
2511 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2512 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2513 }
2514
2515 #ifdef __OBJC__
2516 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2517 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2518
2519 JSContextRef context(internal->context_);
2520
2521 size_t count(internal->cif_.nargs);
2522 JSValueRef values[count];
2523
2524 for (size_t index(0); index != count; ++index)
2525 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2526
2527 JSObjectRef _this(CYCastJSObject(context, values[0]));
2528
2529 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2530 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2531 }
2532 #endif
2533
2534 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2535 // XXX: in case of exceptions this will leak
2536 // XXX: in point of fact, this may /need/ to leak :(
2537 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2538
2539 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2540 NULL, sizeof(ffi_closure),
2541 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2542 -1, 0
2543 )));
2544
2545 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2546 _assert(status == FFI_OK);
2547
2548 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2549
2550 internal->value_ = closure;
2551
2552 return internal;
2553 }
2554
2555 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2556 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2557 return JSObjectMake(context, Functor_, internal);
2558 }
2559
2560 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2561 JSValueRef exception(NULL);
2562 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2563 CYThrow(context, exception);
2564
2565 if (function) {
2566 JSObjectRef function(CYCastJSObject(context, value));
2567 return CYMakeFunctor(context, function, type);
2568 } else {
2569 void (*function)()(CYCastPointer<void (*)()>(context, value));
2570 return CYMakeFunctor(context, function, type);
2571 }
2572 }
2573
2574 #ifdef __OBJC__
2575 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2576 Message_privateData *internal(new Message_privateData(sel, type, imp));
2577 return JSObjectMake(context, Message_, internal);
2578 }
2579
2580 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2581 JSObjectRef function(CYCastJSObject(context, value));
2582 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2583 return reinterpret_cast<IMP>(internal->GetValue());
2584 }
2585
2586 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2587 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2588 Class _class(internal->GetValue());
2589
2590 CYPool pool;
2591 const char *name(CYPoolCString(pool, property));
2592
2593 if (SEL sel = sel_getUid(name))
2594 if (class_getInstanceMethod(_class, sel) != NULL)
2595 return true;
2596
2597 return false;
2598 }
2599
2600 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2601 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2602 Class _class(internal->GetValue());
2603
2604 CYPool pool;
2605 const char *name(CYPoolCString(pool, property));
2606
2607 if (SEL sel = sel_getUid(name))
2608 if (objc_method *method = class_getInstanceMethod(_class, sel))
2609 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2610
2611 return NULL;
2612 }
2613
2614 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2615 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2616 Class _class(internal->GetValue());
2617
2618 CYPool pool;
2619 const char *name(CYPoolCString(pool, property));
2620
2621 SEL sel(sel_registerName(name));
2622
2623 objc_method *method(class_getInstanceMethod(_class, sel));
2624
2625 const char *type;
2626 IMP imp;
2627
2628 if (JSValueIsObjectOfClass(context, value, Message_)) {
2629 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2630 type = sig::Unparse(pool, &message->signature_);
2631 imp = reinterpret_cast<IMP>(message->GetValue());
2632 } else {
2633 type = CYPoolTypeEncoding(pool, _class, sel, method);
2634 imp = CYMakeMessage(context, value, type);
2635 }
2636
2637 if (method != NULL)
2638 method_setImplementation(method, imp);
2639 else
2640 class_replaceMethod(_class, sel, imp, type);
2641
2642 return true;
2643 }
2644
2645 #if !__OBJC2__
2646 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2647 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2648 Class _class(internal->GetValue());
2649
2650 CYPool pool;
2651 const char *name(CYPoolCString(pool, property));
2652
2653 if (SEL sel = sel_getUid(name))
2654 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
2655 objc_method_list list = {NULL, 1, {method}};
2656 class_removeMethods(_class, &list);
2657 return true;
2658 }
2659
2660 return false;
2661 }
2662 #endif
2663
2664 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2665 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2666 Class _class(internal->GetValue());
2667
2668 unsigned int size;
2669 objc_method **data(class_copyMethodList(_class, &size));
2670 for (size_t i(0); i != size; ++i)
2671 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2672 free(data);
2673 }
2674
2675 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2676 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2677 id self(internal->GetValue());
2678
2679 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2680 return true;
2681
2682 CYPool pool;
2683 NSString *name(CYCastNSString(pool, property));
2684
2685 if (CYInternal *internal = CYInternal::Get(self))
2686 if (internal->HasProperty(context, property))
2687 return true;
2688
2689 Class _class(object_getClass(self));
2690
2691 CYPoolTry {
2692 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2693 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2694 if ([self cy$hasProperty:name])
2695 return true;
2696 } CYPoolCatch(false)
2697
2698 const char *string(CYPoolCString(pool, name));
2699
2700 if (class_getProperty(_class, string) != NULL)
2701 return true;
2702
2703 if (SEL sel = sel_getUid(string))
2704 if (CYImplements(self, _class, sel, true))
2705 return true;
2706
2707 return false;
2708 }
2709
2710 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2711 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2712 id self(internal->GetValue());
2713
2714 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2715 return Internal::Make(context, self, object);
2716
2717 CYTry {
2718 CYPool pool;
2719 NSString *name(CYCastNSString(pool, property));
2720
2721 if (CYInternal *internal = CYInternal::Get(self))
2722 if (JSValueRef value = internal->GetProperty(context, property))
2723 return value;
2724
2725 CYPoolTry {
2726 if (NSObject *data = [self cy$getProperty:name])
2727 return CYCastJSValue(context, data);
2728 } CYPoolCatch(NULL)
2729
2730 const char *string(CYPoolCString(pool, name));
2731 Class _class(object_getClass(self));
2732
2733 #ifdef __APPLE__
2734 if (objc_property_t property = class_getProperty(_class, string)) {
2735 PropertyAttributes attributes(property);
2736 SEL sel(sel_registerName(attributes.Getter()));
2737 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
2738 }
2739 #endif
2740
2741 if (SEL sel = sel_getUid(string))
2742 if (CYImplements(self, _class, sel, true))
2743 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
2744
2745 return NULL;
2746 } CYCatch
2747 }
2748
2749 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2750 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2751 id self(internal->GetValue());
2752
2753 CYPool pool;
2754
2755 CYTry {
2756 NSString *name(CYCastNSString(pool, property));
2757 NSObject *data(CYCastNSObject(pool, context, value));
2758
2759 CYPoolTry {
2760 if ([self cy$setProperty:name to:data])
2761 return true;
2762 } CYPoolCatch(NULL)
2763
2764 const char *string(CYPoolCString(pool, name));
2765 Class _class(object_getClass(self));
2766
2767 #ifdef __APPLE__
2768 if (objc_property_t property = class_getProperty(_class, string)) {
2769 PropertyAttributes attributes(property);
2770 if (const char *setter = attributes.Setter()) {
2771 SEL sel(sel_registerName(setter));
2772 JSValueRef arguments[1] = {value};
2773 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
2774 return true;
2775 }
2776 }
2777 #endif
2778
2779 size_t length(strlen(string));
2780
2781 char set[length + 5];
2782
2783 set[0] = 's';
2784 set[1] = 'e';
2785 set[2] = 't';
2786
2787 if (string[0] != '\0') {
2788 set[3] = toupper(string[0]);
2789 memcpy(set + 4, string + 1, length - 1);
2790 }
2791
2792 set[length + 3] = ':';
2793 set[length + 4] = '\0';
2794
2795 if (SEL sel = sel_getUid(set))
2796 if (CYImplements(self, _class, sel, false)) {
2797 JSValueRef arguments[1] = {value};
2798 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
2799 }
2800
2801 if (CYInternal *internal = CYInternal::Set(self)) {
2802 internal->SetProperty(context, property, value);
2803 return true;
2804 }
2805
2806 return false;
2807 } CYCatch
2808 }
2809
2810 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2811 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2812 id self(internal->GetValue());
2813
2814 CYTry {
2815 CYPoolTry {
2816 NSString *name(CYCastNSString(NULL, property));
2817 return [self cy$deleteProperty:name];
2818 } CYPoolCatch(NULL)
2819 } CYCatch
2820 }
2821
2822 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2823 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2824 id self(internal->GetValue());
2825
2826 CYPool pool;
2827 Class _class(object_getClass(self));
2828
2829 #ifdef __APPLE__
2830 {
2831 unsigned int size;
2832 objc_property_t *data(class_copyPropertyList(_class, &size));
2833 for (size_t i(0); i != size; ++i)
2834 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2835 free(data);
2836 }
2837 #endif
2838 }
2839
2840 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2841 CYTry {
2842 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2843 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2844 return value;
2845 } CYCatch
2846 }
2847
2848 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2849 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2850 Class _class(internal->GetValue());
2851 if (!CYIsClass(_class))
2852 return false;
2853
2854 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2855 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2856 // XXX: this isn't always safe
2857 CYTry {
2858 return [linternal->GetValue() isKindOfClass:_class];
2859 } CYCatch
2860 }
2861
2862 return false;
2863 }
2864
2865 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2866 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2867 CYPool pool;
2868
2869 id self(internal->GetValue());
2870 const char *name(CYPoolCString(pool, property));
2871
2872 if (object_getInstanceVariable(self, name, NULL) != NULL)
2873 return true;
2874
2875 return false;
2876 }
2877
2878 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2879 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2880 CYPool pool;
2881
2882 CYTry {
2883 id self(internal->GetValue());
2884 const char *name(CYPoolCString(pool, property));
2885
2886 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2887 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2888 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2889 }
2890
2891 return NULL;
2892 } CYCatch
2893 }
2894
2895 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2896 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2897 CYPool pool;
2898
2899 CYTry {
2900 id self(internal->GetValue());
2901 const char *name(CYPoolCString(pool, property));
2902
2903 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2904 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2905 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2906 return true;
2907 }
2908
2909 return false;
2910 } CYCatch
2911 }
2912
2913 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2914 if (Class super = class_getSuperclass(_class))
2915 Internal_getPropertyNames_(super, names);
2916
2917 unsigned int size;
2918 Ivar *data(class_copyIvarList(_class, &size));
2919 for (size_t i(0); i != size; ++i)
2920 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2921 free(data);
2922 }
2923
2924 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2925 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2926 CYPool pool;
2927
2928 id self(internal->GetValue());
2929 Class _class(object_getClass(self));
2930
2931 Internal_getPropertyNames_(_class, names);
2932 }
2933
2934 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2935 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2936 return internal->GetOwner();
2937 }
2938 #endif
2939
2940 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2941 Type_privateData *typical(internal->type_);
2942 sig::Type *type(typical->type_);
2943 if (type == NULL)
2944 return false;
2945
2946 const char *name(CYPoolCString(pool, property));
2947 size_t length(strlen(name));
2948 double number(CYCastDouble(name, length));
2949
2950 size_t count(type->data.signature.count);
2951
2952 if (std::isnan(number)) {
2953 if (property == NULL)
2954 return false;
2955
2956 sig::Element *elements(type->data.signature.elements);
2957
2958 for (size_t local(0); local != count; ++local) {
2959 sig::Element *element(&elements[local]);
2960 if (element->name != NULL && strcmp(name, element->name) == 0) {
2961 index = local;
2962 goto base;
2963 }
2964 }
2965
2966 return false;
2967 } else {
2968 index = static_cast<ssize_t>(number);
2969 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2970 return false;
2971 }
2972
2973 base:
2974 ffi_type **elements(typical->GetFFI()->elements);
2975
2976 base = reinterpret_cast<uint8_t *>(internal->value_);
2977 for (ssize_t local(0); local != index; ++local)
2978 base += elements[local]->size;
2979
2980 return true;
2981 }
2982
2983 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2984 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2985 Type_privateData *typical(internal->type_);
2986
2987 ffi_type *ffi(typical->GetFFI());
2988
2989 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2990 base += ffi->size * index;
2991
2992 JSObjectRef owner(internal->GetOwner() ?: object);
2993
2994 CYTry {
2995 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2996 } CYCatch
2997 }
2998
2999 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3000 CYPool pool;
3001 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
3002 Type_privateData *typical(internal->type_);
3003
3004 if (typical->type_ == NULL)
3005 return NULL;
3006
3007 ssize_t offset;
3008 if (!CYGetOffset(pool, property, offset))
3009 return NULL;
3010
3011 return Pointer_getIndex(context, object, offset, exception);
3012 }
3013
3014 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3015 return Pointer_getIndex(context, object, 0, exception);
3016 }
3017
3018 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
3019 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
3020 Type_privateData *typical(internal->type_);
3021
3022 ffi_type *ffi(typical->GetFFI());
3023
3024 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
3025 base += ffi->size * index;
3026
3027 CYTry {
3028 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
3029 return true;
3030 } CYCatch
3031 }
3032
3033 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
3034 CYPool pool;
3035 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
3036 Type_privateData *typical(internal->type_);
3037
3038 if (typical->type_ == NULL)
3039 return NULL;
3040
3041 ssize_t offset;
3042 if (!CYGetOffset(pool, property, offset))
3043 return NULL;
3044
3045 return Pointer_setIndex(context, object, offset, value, exception);
3046 }
3047
3048 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
3049 return Pointer_setIndex(context, object, 0, value, exception);
3050 }
3051
3052 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3053 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
3054 Type_privateData *typical(internal->type_);
3055 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
3056 }
3057
3058 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3059 CYPool pool;
3060 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
3061 Type_privateData *typical(internal->type_);
3062
3063 ssize_t index;
3064 uint8_t *base;
3065
3066 CYTry {
3067 if (!Index_(pool, internal, property, index, base))
3068 return NULL;
3069
3070 JSObjectRef owner(internal->GetOwner() ?: object);
3071
3072 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
3073 } CYCatch
3074 }
3075
3076 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
3077 CYPool pool;
3078 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
3079 Type_privateData *typical(internal->type_);
3080
3081 ssize_t index;
3082 uint8_t *base;
3083
3084 CYTry {
3085 if (!Index_(pool, internal, property, index, base))
3086 return false;
3087
3088 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
3089 return true;
3090 } CYCatch
3091 }
3092
3093 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3094 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
3095 Type_privateData *typical(internal->type_);
3096 sig::Type *type(typical->type_);
3097
3098 if (type == NULL)
3099 return;
3100
3101 size_t count(type->data.signature.count);
3102 sig::Element *elements(type->data.signature.elements);
3103
3104 char number[32];
3105
3106 for (size_t index(0); index != count; ++index) {
3107 const char *name;
3108 name = elements[index].name;
3109
3110 if (name == NULL) {
3111 sprintf(number, "%lu", index);
3112 name = number;
3113 }
3114
3115 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
3116 }
3117 }
3118
3119 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)()) {
3120 CYTry {
3121 if (setups + count != signature->count - 1)
3122 _throw(NSInvalidArgumentException, "incorrect number of arguments to ffi function");
3123
3124 size_t size(setups + count);
3125 void *values[size];
3126 memcpy(values, setup, sizeof(void *) * setups);
3127
3128 for (size_t index(setups); index != size; ++index) {
3129 sig::Element *element(&signature->elements[index + 1]);
3130 ffi_type *ffi(cif->arg_types[index]);
3131 // XXX: alignment?
3132 values[index] = new(pool) uint8_t[ffi->size];
3133 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
3134 }
3135
3136 uint8_t value[cif->rtype->size];
3137 ffi_call(cif, function, value, values);
3138
3139 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
3140 } CYCatch
3141 }
3142
3143 #ifdef __OBJC__
3144 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3145 CYTry {
3146 CYPool pool;
3147 NSString *name(CYCastNSString(pool, property));
3148 if (Class _class = NSClassFromString(name))
3149 return CYMakeInstance(context, _class, true);
3150 return NULL;
3151 } CYCatch
3152 }
3153
3154 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3155 size_t size(objc_getClassList(NULL, 0));
3156 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
3157
3158 get:
3159 size_t writ(objc_getClassList(data, size));
3160 if (size < writ) {
3161 size = writ;
3162 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
3163 data = copy;
3164 goto get;
3165 } else goto done;
3166 }
3167
3168 for (size_t i(0); i != writ; ++i)
3169 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
3170
3171 done:
3172 free(data);
3173 }
3174
3175 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3176 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
3177
3178 CYTry {
3179 CYPool pool;
3180 const char *name(CYPoolCString(pool, property));
3181 unsigned int size;
3182 const char **data(objc_copyClassNamesForImage(internal, &size));
3183 JSValueRef value;
3184 for (size_t i(0); i != size; ++i)
3185 if (strcmp(name, data[i]) == 0) {
3186 if (Class _class = objc_getClass(name)) {
3187 value = CYMakeInstance(context, _class, true);
3188 goto free;
3189 } else
3190 break;
3191 }
3192 value = NULL;
3193 free:
3194 free(data);
3195 return value;
3196 } CYCatch
3197 }
3198
3199 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3200 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
3201 unsigned int size;
3202 const char **data(objc_copyClassNamesForImage(internal, &size));
3203 for (size_t i(0); i != size; ++i)
3204 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3205 free(data);
3206 }
3207
3208 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3209 CYTry {
3210 CYPool pool;
3211 const char *name(CYPoolCString(pool, property));
3212 unsigned int size;
3213 const char **data(objc_copyImageNames(&size));
3214 for (size_t i(0); i != size; ++i)
3215 if (strcmp(name, data[i]) == 0) {
3216 name = data[i];
3217 goto free;
3218 }
3219 name = NULL;
3220 free:
3221 free(data);
3222 if (name == NULL)
3223 return NULL;
3224 JSObjectRef value(JSObjectMake(context, NULL, NULL));
3225 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
3226 return value;
3227 } CYCatch
3228 }
3229
3230 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3231 unsigned int size;
3232 const char **data(objc_copyImageNames(&size));
3233 for (size_t i(0); i != size; ++i)
3234 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
3235 free(data);
3236 }
3237
3238 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3239 CYTry {
3240 CYPool pool;
3241 NSString *name(CYCastNSString(pool, property));
3242 if (Protocol *protocol = NSProtocolFromString(name))
3243 return CYMakeInstance(context, protocol, true);
3244 return NULL;
3245 } CYCatch
3246 }
3247
3248 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
3249 unsigned int size;
3250 Protocol **data(objc_copyProtocolList(&size));
3251 for (size_t i(0); i != size; ++i)
3252 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
3253 free(data);
3254 }
3255 #endif
3256
3257 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
3258 Type_privateData *internal(new Type_privateData(NULL, type));
3259 return JSObjectMake(context, Type_privateData::Class_, internal);
3260 }
3261
3262 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
3263 Type_privateData *internal(new Type_privateData(type));
3264 return JSObjectMake(context, Type_privateData::Class_, internal);
3265 }
3266
3267 static void *CYCastSymbol(const char *name) {
3268 return dlsym(RTLD_DEFAULT, name);
3269 }
3270
3271 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3272 #ifdef __OBJC__
3273 if (JSStringIsEqualToUTF8CString(property, "nil"))
3274 return Instance::Make(context, nil);
3275 #endif
3276
3277 CYTry {
3278 CYPool pool;
3279 const char *name(CYPoolCString(pool, property));
3280
3281 #ifdef __OBJC__
3282 if (Class _class = objc_getClass(name))
3283 return CYMakeInstance(context, _class, true);
3284 #endif
3285
3286 sqlite3_stmt *statement;
3287
3288 _sqlcall(sqlite3_prepare(Bridge_,
3289 "select "
3290 "\"bridge\".\"mode\", "
3291 "\"bridge\".\"value\" "
3292 "from \"bridge\" "
3293 "where"
3294 " \"bridge\".\"name\" = ?"
3295 " limit 1"
3296 , -1, &statement, NULL));
3297
3298 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
3299
3300 int mode;
3301 const char *value;
3302
3303 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
3304 mode = -1;
3305 value = NULL;
3306 } else {
3307 mode = sqlite3_column_int(statement, 0);
3308 value = sqlite3_column_pooled(pool, statement, 1);
3309 }
3310
3311 _sqlcall(sqlite3_finalize(statement));
3312
3313 switch (mode) {
3314 default:
3315 _assert(false);
3316 case -1:
3317 return NULL;
3318
3319 case 0:
3320 return JSEvaluateScript(CYGetJSContext(), CYJSString(value), NULL, NULL, 0, NULL);
3321 case 1:
3322 return CYMakeFunctor(context, reinterpret_cast<void (*)()>(CYCastSymbol(name)), value);
3323
3324 case 2: {
3325 // XXX: this is horrendously inefficient
3326 sig::Signature signature;
3327 sig::Parse(pool, &signature, value, &Structor_);
3328 ffi_cif cif;
3329 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3330 return CYFromFFI(context, signature.elements[0].type, cif.rtype, CYCastSymbol(name));
3331 }
3332
3333 // XXX: implement case 3
3334 case 4:
3335 return CYMakeType(context, value);
3336 }
3337 } CYCatch
3338 }
3339
3340 #ifdef __OBJC__
3341 static bool stret(ffi_type *ffi_type) {
3342 return ffi_type->type == FFI_TYPE_STRUCT && (
3343 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
3344 struct_forward_array[ffi_type->size] != 0
3345 );
3346 }
3347 #endif
3348
3349 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3350 CYTry {
3351 if (count == 0)
3352 printf("\n");
3353 else
3354 printf("%s\n", CYCastCString(context, arguments[0]));
3355 return CYJSUndefined(context);
3356 } CYCatch
3357 }
3358
3359 #ifdef __OBJC__
3360 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
3361 const char *type;
3362
3363 if (_class == NULL)
3364 _class = object_getClass(self);
3365
3366 if (objc_method *method = class_getInstanceMethod(_class, _cmd))
3367 type = method_getTypeEncoding(method);
3368 else {
3369 CYTry {
3370 CYPoolTry {
3371 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
3372 if (method == nil)
3373 _throw(NSInvalidArgumentException, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
3374 type = CYPoolCString(pool, [method _typeString]);
3375 } CYPoolCatch(NULL)
3376 } CYCatch
3377 }
3378
3379 objc_super super = {self, _class};
3380 void *arg0 = &super;
3381
3382 void *setup[2];
3383 setup[0] = &arg0;
3384 setup[1] = &_cmd;
3385
3386 sig::Signature signature;
3387 sig::Parse(pool, &signature, type, &Structor_);
3388
3389 ffi_cif cif;
3390 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
3391
3392 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSendSuper_stret) : reinterpret_cast<void (*)()>(&objc_msgSendSuper);
3393 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
3394 }
3395 #endif
3396
3397 static size_t Nonce_(0);
3398
3399 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3400 char name[16];
3401 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
3402 return CYCastJSValue(context, name);
3403 }
3404
3405 #ifdef __OBJC__
3406 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3407 CYPool pool;
3408
3409 bool uninitialized;
3410
3411 id self;
3412 SEL _cmd;
3413 Class _class;
3414
3415 CYTry {
3416 if (count < 2)
3417 _throw(NSInvalidArgumentException, "too few arguments to objc_msgSend");
3418
3419 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
3420 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3421 self = internal->GetValue();
3422 _class = internal->class_;;
3423 uninitialized = false;
3424 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
3425 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
3426 self = internal->GetValue();
3427 _class = nil;
3428 uninitialized = internal->IsUninitialized();
3429 if (uninitialized)
3430 internal->value_ = nil;
3431 } else {
3432 self = CYCastNSObject(pool, context, arguments[0]);
3433 _class = nil;
3434 uninitialized = false;
3435 }
3436
3437 if (self == nil)
3438 return CYJSNull(context);
3439
3440 _cmd = CYCastSEL(context, arguments[1]);
3441 } CYCatch
3442
3443 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
3444 }
3445 #endif
3446
3447 #ifdef __OBJC__
3448 /* Hook: objc_registerClassPair {{{ */
3449 // XXX: replace this with associated objects
3450
3451 MSHook(void, CYDealloc, id self, SEL sel) {
3452 CYInternal *internal;
3453 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
3454 if (internal != NULL)
3455 delete internal;
3456 _CYDealloc(self, sel);
3457 }
3458
3459 MSHook(void, objc_registerClassPair, Class _class) {
3460 Class super(class_getSuperclass(_class));
3461 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
3462 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
3463 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
3464 }
3465
3466 _objc_registerClassPair(_class);
3467 }
3468
3469 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3470 CYTry {
3471 if (count != 1)
3472 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3473 CYPool pool;
3474 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
3475 if (value == NULL || !CYIsClass(value))
3476 _throw(NSInvalidArgumentException, "incorrect number of arguments to objc_registerClassPair");
3477 Class _class((Class) value);
3478 $objc_registerClassPair(_class);
3479 return CYJSUndefined(context);
3480 } CYCatch
3481 }
3482 /* }}} */
3483 #endif
3484
3485 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3486 JSGarbageCollect(context);
3487 return CYJSUndefined(context);
3488 }
3489
3490 #ifdef __OBJC__
3491 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3492 JSValueRef setup[count + 2];
3493 setup[0] = _this;
3494 setup[1] = object;
3495 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
3496 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
3497 }
3498
3499 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3500 CYPool pool;
3501 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
3502
3503 // XXX: handle Instance::Uninitialized?
3504 id self(CYCastNSObject(pool, context, _this));
3505
3506 void *setup[2];
3507 setup[0] = &self;
3508 setup[1] = &internal->sel_;
3509
3510 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3511 }
3512 #endif
3513
3514 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3515 CYPool pool;
3516 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
3517 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
3518 }
3519
3520 #ifdef __OBJC__
3521 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3522 CYTry {
3523 if (count != 2)
3524 _throw(NSInvalidArgumentException, "incorrect number of arguments to Super constructor");
3525 CYPool pool;
3526 id self(CYCastNSObject(pool, context, arguments[0]));
3527 Class _class(CYCastClass(pool, context, arguments[1]));
3528 return cy::Super::Make(context, self, _class);
3529 } CYCatch
3530 }
3531
3532 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3533 CYTry {
3534 if (count != 1)
3535 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector constructor");
3536 const char *name(CYCastCString(context, arguments[0]));
3537 return CYMakeSelector(context, sel_registerName(name));
3538 } CYCatch
3539 }
3540 #endif
3541
3542 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3543 CYTry {
3544 if (count != 2)
3545 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3546
3547 void *value(CYCastPointer<void *>(context, arguments[0]));
3548 const char *type(CYCastCString(context, arguments[1]));
3549
3550 CYPool pool;
3551
3552 sig::Signature signature;
3553 sig::Parse(pool, &signature, type, &Structor_);
3554
3555 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
3556 } CYCatch
3557 }
3558
3559 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3560 CYTry {
3561 if (count != 1)
3562 _throw(NSInvalidArgumentException, "incorrect number of arguments to Type constructor");
3563 const char *type(CYCastCString(context, arguments[0]));
3564 return CYMakeType(context, type);
3565 } CYCatch
3566 }
3567
3568 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3569 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3570
3571 CYTry {
3572 sig::Type type;
3573
3574 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3575 type.primitive = sig::pointer_P;
3576 type.data.data.size = 0;
3577 } else {
3578 CYPool pool;
3579 size_t index(CYGetIndex(pool, property));
3580 if (index == _not(size_t))
3581 return NULL;
3582 type.primitive = sig::array_P;
3583 type.data.data.size = index;
3584 }
3585
3586 type.name = NULL;
3587 type.flags = 0;
3588
3589 type.data.data.type = internal->type_;
3590
3591 return CYMakeType(context, &type);
3592 } CYCatch
3593 }
3594
3595 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3596 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3597
3598 CYTry {
3599 if (count != 1)
3600 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3601 sig::Type *type(internal->type_);
3602 ffi_type *ffi(internal->GetFFI());
3603 // XXX: alignment?
3604 uint8_t value[ffi->size];
3605 CYPool pool;
3606 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3607 return CYFromFFI(context, type, ffi, value);
3608 } CYCatch
3609 }
3610
3611 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3612 CYTry {
3613 if (count != 0)
3614 _throw(NSInvalidArgumentException, "incorrect number of arguments to type cast function");
3615 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3616
3617 sig::Type *type(internal->type_);
3618 size_t size;
3619
3620 if (type->primitive != sig::array_P)
3621 size = 0;
3622 else {
3623 size = type->data.data.size;
3624 type = type->data.data.type;
3625 }
3626
3627 void *value(malloc(internal->GetFFI()->size));
3628 return CYMakePointer(context, value, type, NULL, NULL);
3629 } CYCatch
3630 }
3631
3632 #ifdef __OBJC__
3633 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3634 CYTry {
3635 if (count > 1)
3636 _throw(NSInvalidArgumentException, "incorrect number of arguments to Instance constructor");
3637 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3638 return Instance::Make(context, self);
3639 } CYCatch
3640 }
3641 #endif
3642
3643 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3644 CYTry {
3645 if (count != 2)
3646 _throw(NSInvalidArgumentException, "incorrect number of arguments to Functor constructor");
3647 const char *type(CYCastCString(context, arguments[1]));
3648 return CYMakeFunctor(context, arguments[0], type);
3649 } CYCatch
3650 }
3651
3652 #ifdef __OBJC__
3653 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3654 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3655 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3656 }
3657
3658 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3659 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3660 Type_privateData *typical(internal->GetType());
3661
3662 sig::Type *type;
3663 ffi_type *ffi;
3664
3665 if (typical == NULL) {
3666 type = NULL;
3667 ffi = NULL;
3668 } else {
3669 type = typical->type_;
3670 ffi = typical->ffi_;
3671 }
3672
3673 return CYMakePointer(context, &internal->value_, type, ffi, object);
3674 }
3675 #endif
3676
3677 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3678 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3679
3680 CYTry {
3681 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3682 } CYCatch
3683 }
3684
3685 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3686 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3687 }
3688
3689 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3690 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3691 char string[32];
3692 sprintf(string, "%p", internal->value_);
3693
3694 CYTry {
3695 return CYCastJSValue(context, string);
3696 } CYCatch
3697 }
3698
3699 #ifdef __OBJC__
3700 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3701 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3702 return Instance::Make(context, object_getClass(internal->GetValue()));
3703 }
3704
3705 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3706 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3707 id self(internal->GetValue());
3708 if (!CYIsClass(self))
3709 return CYJSUndefined(context);
3710 CYTry {
3711 return CYGetClassPrototype(context, self);
3712 } CYCatch
3713 }
3714
3715 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3716 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3717 id self(internal->GetValue());
3718 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3719 return CYJSUndefined(context);
3720 return Messages::Make(context, self);
3721 }
3722
3723 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3724 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3725 return NULL;
3726
3727 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3728
3729 CYTry {
3730 CYPoolTry {
3731 return CYCastJSValue(context, CYJSString(CYCastNSCYON(internal->GetValue())));
3732 } CYPoolCatch(NULL)
3733 } CYCatch
3734 }
3735
3736 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3737 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3738 return NULL;
3739
3740 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3741
3742 CYTry {
3743 CYPoolTry {
3744 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3745 // XXX: check for support of cy$toJSON?
3746 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3747 } CYPoolCatch(NULL)
3748 } CYCatch
3749 }
3750
3751 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3752 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3753 return NULL;
3754
3755 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3756
3757 CYTry {
3758 CYPoolTry {
3759 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3760 } CYPoolCatch(NULL)
3761 } CYCatch
3762 }
3763
3764 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3765 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3766
3767 CYTry {
3768 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3769 } CYCatch
3770 }
3771
3772 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3773 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3774 }
3775
3776 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3777 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3778 const char *name(sel_getName(internal->GetValue()));
3779
3780 CYTry {
3781 CYPoolTry {
3782 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3783 } CYPoolCatch(NULL)
3784 } CYCatch
3785 }
3786
3787 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3788 CYTry {
3789 if (count != 1)
3790 _throw(NSInvalidArgumentException, "incorrect number of arguments to Selector.type");
3791 CYPool pool;
3792 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3793 if (Class _class = CYCastClass(pool, context, arguments[0])) {
3794 SEL sel(internal->GetValue());
3795 if (objc_method *method = class_getInstanceMethod(_class, sel))
3796 if (const char *type = CYPoolTypeEncoding(pool, _class, sel, method))
3797 return CYCastJSValue(context, CYJSString(type));
3798 }
3799
3800 // XXX: do a lookup of some kind
3801 return CYJSNull(context);
3802 } CYCatch
3803 }
3804 #endif
3805
3806 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3807 CYTry {
3808 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3809 CYPool pool;
3810 const char *type(sig::Unparse(pool, internal->type_));
3811 return CYCastJSValue(context, CYJSString(type));
3812 } CYCatch
3813 }
3814
3815 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3816 CYTry {
3817 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3818 CYPool pool;
3819 const char *type(sig::Unparse(pool, internal->type_));
3820 size_t size(strlen(type));
3821 char *cyon(new(pool) char[12 + size + 1]);
3822 memcpy(cyon, "new Type(\"", 10);
3823 cyon[12 + size] = '\0';
3824 cyon[12 + size - 2] = '"';
3825 cyon[12 + size - 1] = ')';
3826 memcpy(cyon + 10, type, size);
3827 return CYCastJSValue(context, CYJSString(cyon));
3828 } CYCatch
3829 }
3830
3831 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3832 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3833 }
3834
3835 #ifdef __OBJC__
3836 static JSStaticValue Selector_staticValues[2] = {
3837 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3838 {NULL, NULL, NULL, 0}
3839 };
3840 #endif
3841
3842 static JSStaticValue Pointer_staticValues[2] = {
3843 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3844 {NULL, NULL, NULL, 0}
3845 };
3846
3847 static JSStaticFunction Pointer_staticFunctions[4] = {
3848 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3849 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3850 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3851 {NULL, NULL, 0}
3852 };
3853
3854 static JSStaticFunction Struct_staticFunctions[2] = {
3855 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3856 {NULL, NULL, 0}
3857 };
3858
3859 static JSStaticFunction Functor_staticFunctions[4] = {
3860 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3861 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3862 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3863 {NULL, NULL, 0}
3864 };
3865
3866 #ifdef __OBJC__
3867 static JSStaticValue Instance_staticValues[5] = {
3868 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3869 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3870 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3871 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3872 {NULL, NULL, NULL, 0}
3873 };
3874
3875 static JSStaticFunction Instance_staticFunctions[5] = {
3876 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3877 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3878 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3879 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3880 {NULL, NULL, 0}
3881 };
3882
3883 static JSStaticFunction Internal_staticFunctions[2] = {
3884 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3885 {NULL, NULL, 0}
3886 };
3887
3888 static JSStaticFunction Selector_staticFunctions[5] = {
3889 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3890 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3891 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3892 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3893 {NULL, NULL, 0}
3894 };
3895 #endif
3896
3897 static JSStaticFunction Type_staticFunctions[4] = {
3898 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3899 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3900 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3901 {NULL, NULL, 0}
3902 };
3903
3904 void CYSetArgs(int argc, const char *argv[]) {
3905 JSContextRef context(CYGetJSContext());
3906 JSValueRef args[argc];
3907 for (int i(0); i != argc; ++i)
3908 args[i] = CYCastJSValue(context, argv[i]);
3909 JSValueRef exception(NULL);
3910 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3911 CYThrow(context, exception);
3912 CYSetProperty(context, System_, CYJSString("args"), array);
3913 }
3914
3915 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3916 return JSContextGetGlobalObject(context);
3917 }
3918
3919 const char *CYExecute(apr_pool_t *pool, const char *code) {
3920 JSContextRef context(CYGetJSContext());
3921 JSValueRef exception(NULL), result;
3922
3923 const char *json;
3924
3925 CYPoolTry {
3926 try {
3927 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3928 } catch (const char *error) {
3929 return error;
3930 }
3931
3932 if (exception != NULL) { error:
3933 result = exception;
3934 exception = NULL;
3935 }
3936
3937 if (JSValueIsUndefined(context, result))
3938 return NULL;
3939
3940 try {
3941 json = CYPoolCCYON(pool, context, result, &exception);
3942 } catch (const char *error) {
3943 return error;
3944 }
3945
3946 if (exception != NULL)
3947 goto error;
3948 } CYPoolCatch(NULL)
3949
3950 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3951 return json;
3952 }
3953
3954 static apr_pool_t *Pool_;
3955
3956 apr_pool_t *CYGetGlobalPool() {
3957 return Pool_;
3958 }
3959
3960 MSInitialize {
3961 _aprcall(apr_initialize());
3962 _aprcall(apr_pool_create(&Pool_, NULL));
3963
3964 _sqlcall(sqlite3_open("/usr/lib/libcycript.db", &Bridge_));
3965
3966 #ifdef __OBJC__
3967 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3968 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3969
3970 #ifdef __APPLE__
3971 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3972 NSCFType_ = objc_getClass("NSCFType");
3973 #endif
3974
3975 NSArray_ = objc_getClass("NSArray");
3976 NSDictionary_ = objc_getClass("NSDictonary");
3977 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3978 NSZombie_ = objc_getClass("_NSZombie_");
3979 Object_ = objc_getClass("Object");
3980 #endif
3981 }
3982
3983 JSGlobalContextRef CYGetJSContext() {
3984 if (Context_ == NULL) {
3985 JSClassDefinition definition;
3986
3987 definition = kJSClassDefinitionEmpty;
3988 definition.className = "Functor";
3989 definition.staticFunctions = Functor_staticFunctions;
3990 definition.callAsFunction = &Functor_callAsFunction;
3991 definition.finalize = &Finalize;
3992 Functor_ = JSClassCreate(&definition);
3993
3994 definition = kJSClassDefinitionEmpty;
3995 definition.className = "Pointer";
3996 definition.staticValues = Pointer_staticValues;
3997 definition.staticFunctions = Pointer_staticFunctions;
3998 definition.getProperty = &Pointer_getProperty;
3999 definition.setProperty = &Pointer_setProperty;
4000 definition.finalize = &Finalize;
4001 Pointer_ = JSClassCreate(&definition);
4002
4003 definition = kJSClassDefinitionEmpty;
4004 definition.className = "Struct";
4005 definition.staticFunctions = Struct_staticFunctions;
4006 definition.getProperty = &Struct_getProperty;
4007 definition.setProperty = &Struct_setProperty;
4008 definition.getPropertyNames = &Struct_getPropertyNames;
4009 definition.finalize = &Finalize;
4010 Struct_ = JSClassCreate(&definition);
4011
4012 definition = kJSClassDefinitionEmpty;
4013 definition.className = "Type";
4014 definition.staticFunctions = Type_staticFunctions;
4015 definition.getProperty = &Type_getProperty;
4016 definition.callAsFunction = &Type_callAsFunction;
4017 definition.callAsConstructor = &Type_callAsConstructor;
4018 definition.finalize = &Finalize;
4019 Type_privateData::Class_ = JSClassCreate(&definition);
4020
4021 definition = kJSClassDefinitionEmpty;
4022 definition.className = "Runtime";
4023 definition.getProperty = &Runtime_getProperty;
4024 Runtime_ = JSClassCreate(&definition);
4025
4026 definition = kJSClassDefinitionEmpty;
4027 //definition.getProperty = &Global_getProperty;
4028 JSClassRef Global(JSClassCreate(&definition));
4029
4030 JSGlobalContextRef context(JSGlobalContextCreate(Global));
4031 Context_ = context;
4032 JSObjectRef global(CYGetGlobalObject(context));
4033
4034 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
4035
4036 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
4037 JSValueProtect(context, Array_);
4038
4039 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
4040 JSValueProtect(context, Function_);
4041
4042 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
4043 JSValueProtect(context, String_);
4044
4045 length_ = JSStringCreateWithUTF8CString("length");
4046 message_ = JSStringCreateWithUTF8CString("message");
4047 name_ = JSStringCreateWithUTF8CString("name");
4048 prototype_ = JSStringCreateWithUTF8CString("prototype");
4049 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
4050 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
4051
4052 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
4053 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
4054 JSValueProtect(context, Object_prototype_);
4055
4056 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
4057 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
4058 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
4059 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
4060
4061 CYSetProperty(context, Array_prototype_, toCYON_, JSObjectMakeFunctionWithCallback(context, toCYON_, &Array_callAsFunction_toCYON), kJSPropertyAttributeDontEnum);
4062
4063 JSValueProtect(context, Array_prototype_);
4064 JSValueProtect(context, Array_pop_);
4065 JSValueProtect(context, Array_push_);
4066 JSValueProtect(context, Array_splice_);
4067
4068 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
4069
4070 JSValueRef function(CYGetProperty(context, Function_, prototype_));
4071
4072 /* Objective-C Classes {{{ */
4073 #ifdef __OBJC__
4074 definition = kJSClassDefinitionEmpty;
4075 definition.className = "Instance";
4076 definition.staticValues = Instance_staticValues;
4077 definition.staticFunctions = Instance_staticFunctions;
4078 definition.hasProperty = &Instance_hasProperty;
4079 definition.getProperty = &Instance_getProperty;
4080 definition.setProperty = &Instance_setProperty;
4081 definition.deleteProperty = &Instance_deleteProperty;
4082 definition.getPropertyNames = &Instance_getPropertyNames;
4083 definition.callAsConstructor = &Instance_callAsConstructor;
4084 definition.hasInstance = &Instance_hasInstance;
4085 definition.finalize = &Finalize;
4086 Instance_ = JSClassCreate(&definition);
4087
4088 definition = kJSClassDefinitionEmpty;
4089 definition.className = "Internal";
4090 definition.staticFunctions = Internal_staticFunctions;
4091 definition.hasProperty = &Internal_hasProperty;
4092 definition.getProperty = &Internal_getProperty;
4093 definition.setProperty = &Internal_setProperty;
4094 definition.getPropertyNames = &Internal_getPropertyNames;
4095 definition.finalize = &Finalize;
4096 Internal_ = JSClassCreate(&definition);
4097
4098 definition = kJSClassDefinitionEmpty;
4099 definition.className = "Message";
4100 definition.staticFunctions = Functor_staticFunctions;
4101 definition.callAsFunction = &Message_callAsFunction;
4102 definition.finalize = &Finalize;
4103 Message_ = JSClassCreate(&definition);
4104
4105 definition = kJSClassDefinitionEmpty;
4106 definition.className = "Messages";
4107 definition.hasProperty = &Messages_hasProperty;
4108 definition.getProperty = &Messages_getProperty;
4109 definition.setProperty = &Messages_setProperty;
4110 #if !__OBJC2__
4111 definition.deleteProperty = &Messages_deleteProperty;
4112 #endif
4113 definition.getPropertyNames = &Messages_getPropertyNames;
4114 definition.finalize = &Finalize;
4115 Messages_ = JSClassCreate(&definition);
4116
4117 definition = kJSClassDefinitionEmpty;
4118 definition.className = "Selector";
4119 definition.staticValues = Selector_staticValues;
4120 definition.staticFunctions = Selector_staticFunctions;
4121 definition.callAsFunction = &Selector_callAsFunction;
4122 definition.finalize = &Finalize;
4123 Selector_ = JSClassCreate(&definition);
4124
4125 definition = kJSClassDefinitionEmpty;
4126 definition.className = "Super";
4127 definition.staticFunctions = Internal_staticFunctions;
4128 definition.finalize = &Finalize;
4129 Super_ = JSClassCreate(&definition);
4130
4131 definition = kJSClassDefinitionEmpty;
4132 definition.className = "ObjectiveC::Classes";
4133 definition.getProperty = &ObjectiveC_Classes_getProperty;
4134 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
4135 ObjectiveC_Classes_ = JSClassCreate(&definition);
4136
4137 definition = kJSClassDefinitionEmpty;
4138 definition.className = "ObjectiveC::Images";
4139 definition.getProperty = &ObjectiveC_Images_getProperty;
4140 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
4141 ObjectiveC_Images_ = JSClassCreate(&definition);
4142
4143 definition = kJSClassDefinitionEmpty;
4144 definition.className = "ObjectiveC::Image::Classes";
4145 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
4146 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
4147 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
4148
4149 definition = kJSClassDefinitionEmpty;
4150 definition.className = "ObjectiveC::Protocols";
4151 definition.getProperty = &ObjectiveC_Protocols_getProperty;
4152 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
4153 ObjectiveC_Protocols_ = JSClassCreate(&definition);
4154
4155 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
4156 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC);
4157
4158 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
4159 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
4160 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
4161
4162 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
4163 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
4164 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
4165 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
4166
4167 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
4168 JSValueProtect(context, Instance_prototype_);
4169
4170 CYSetProperty(context, global, CYJSString("Instance"), Instance);
4171 CYSetProperty(context, global, CYJSString("Selector"), Selector);
4172 CYSetProperty(context, global, CYJSString("Super"), Super);
4173
4174 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
4175 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
4176
4177 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
4178 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
4179 #endif
4180 /* }}} */
4181
4182 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
4183
4184 CYSetProperty(context, global, CYJSString("Functor"), Functor);
4185 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
4186 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
4187
4188 #ifdef __OBJC__
4189 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
4190 #endif
4191
4192 #ifdef __OBJC__
4193 #ifdef __APPLE__
4194 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
4195 #endif
4196 #endif
4197
4198 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
4199 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
4200 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
4201
4202 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
4203
4204 System_ = JSObjectMake(context, NULL, NULL);
4205 JSValueProtect(context, System_);
4206
4207 CYSetProperty(context, global, CYJSString("system"), System_);
4208 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
4209 //CYSetProperty(context, System_, CYJSString("global"), global);
4210
4211 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
4212
4213 Result_ = JSStringCreateWithUTF8CString("_");
4214 }
4215
4216 return Context_;
4217 }