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