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