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