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