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