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