]> git.saurik.com Git - cycript.git/blob - Library.mm
c5027c052ab77afcd70c9cbf7c652560de4cd12e
[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-1/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 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1284 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1285 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1286
1287 #define CYTry \
1288 @try
1289 #define CYCatch \
1290 @catch (id error) { \
1291 CYThrow(context, error, exception); \
1292 return NULL; \
1293 }
1294
1295 apr_status_t CYPoolRelease_(void *data) {
1296 id object(reinterpret_cast<id>(data));
1297 [object release];
1298 return APR_SUCCESS;
1299 }
1300
1301 id CYPoolRelease(apr_pool_t *pool, id object) {
1302 if (object == nil)
1303 return nil;
1304 else if (pool == NULL)
1305 return [object autorelease];
1306 else {
1307 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1308 return object;
1309 }
1310 }
1311
1312 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1313 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1314 }
1315
1316 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1317 JSValueRef exception(NULL);
1318 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1319 CYThrow(context, exception);
1320 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1321 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1322 }
1323
1324 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1325 if (!JSValueIsObjectOfClass(context, object, Instance_))
1326 return CYCastNSObject_(pool, context, object);
1327 else {
1328 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1329 return internal->GetValue();
1330 }
1331 }
1332
1333 double CYCastDouble(const char *value, size_t size) {
1334 char *end;
1335 double number(strtod(value, &end));
1336 if (end != value + size)
1337 return NAN;
1338 return number;
1339 }
1340
1341 double CYCastDouble(const char *value) {
1342 return CYCastDouble(value, strlen(value));
1343 }
1344
1345 double CYCastDouble(JSContextRef context, JSValueRef value) {
1346 JSValueRef exception(NULL);
1347 double number(JSValueToNumber(context, value, &exception));
1348 CYThrow(context, exception);
1349 return number;
1350 }
1351
1352 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1353 double number(CYCastDouble(context, value));
1354 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1355 }
1356
1357 CFStringRef CYCopyCFString(const char *value) {
1358 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1359 }
1360
1361 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1362 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1363 }
1364
1365 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1366 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1367 }
1368
1369 bool CYCastBool(JSContextRef context, JSValueRef value) {
1370 return JSValueToBoolean(context, value);
1371 }
1372
1373 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1374 CFTypeRef object;
1375 bool copy;
1376
1377 switch (JSType type = JSValueGetType(context, value)) {
1378 case kJSTypeUndefined:
1379 object = [WebUndefined undefined];
1380 copy = false;
1381 break;
1382
1383 case kJSTypeNull:
1384 return NULL;
1385 break;
1386
1387 case kJSTypeBoolean:
1388 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1389 copy = false;
1390 break;
1391
1392 case kJSTypeNumber:
1393 object = CYCopyCFNumber(context, value);
1394 copy = true;
1395 break;
1396
1397 case kJSTypeString:
1398 object = CYCopyCFString(context, value);
1399 copy = true;
1400 break;
1401
1402 case kJSTypeObject:
1403 // XXX: this might could be more efficient
1404 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1405 copy = false;
1406 break;
1407
1408 default:
1409 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1410 break;
1411 }
1412
1413 if (cast != copy)
1414 return object;
1415 else if (copy)
1416 return CYPoolRelease(pool, object);
1417 else
1418 return CFRetain(object);
1419 }
1420
1421 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1422 return CYCFType(pool, context, value, true);
1423 }
1424
1425 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1426 return CYCFType(pool, context, value, false);
1427 }
1428
1429 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1430 CYPool pool;
1431 size_t size(JSPropertyNameArrayGetCount(names));
1432 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1433 for (size_t index(0); index != size; ++index)
1434 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1435 return array;
1436 }
1437
1438 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1439 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1440 }
1441
1442 void CYThrow(JSContextRef context, JSValueRef value) {
1443 if (value == NULL)
1444 return;
1445 @throw CYCastNSObject(NULL, context, value);
1446 }
1447
1448 JSValueRef CYJSNull(JSContextRef context) {
1449 return JSValueMakeNull(context);
1450 }
1451
1452 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1453 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1454 }
1455
1456 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1457 return CYCastJSValue(context, CYJSString(value));
1458 }
1459
1460 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1461 if (value == nil)
1462 return CYJSNull(context);
1463 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1464 return [value cy$JSValueInContext:context];
1465 else
1466 return CYMakeInstance(context, value, false);
1467 }
1468
1469 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1470 JSValueRef exception(NULL);
1471 JSObjectRef object(JSValueToObject(context, value, &exception));
1472 CYThrow(context, exception);
1473 return object;
1474 }
1475
1476 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1477 if (exception == NULL)
1478 throw error;
1479 *exception = CYCastJSValue(context, error);
1480 }
1481
1482 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1483 JSValueRef exception(NULL);
1484 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1485 CYThrow(context, exception);
1486 return value;
1487 }
1488
1489 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1490 // XXX: this isn't actually correct
1491 return value != NULL && JSValueIsObject(context, value);
1492 }
1493
1494 @implementation CYJSObject
1495
1496 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1497 if ((self = [super init]) != nil) {
1498 object_ = object;
1499 context_ = context;
1500 JSValueProtect(context_, object_);
1501 } return self;
1502 }
1503
1504 - (void) dealloc {
1505 JSValueUnprotect(context_, object_);
1506 [super dealloc];
1507 }
1508
1509 - (NSObject *) cy$toJSON:(NSString *)key {
1510 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1511 if (!CYIsCallable(context_, toJSON))
1512 return [super cy$toJSON:key];
1513 else {
1514 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1515 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1516 // XXX: do I really want an NSNull here?!
1517 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1518 }
1519 }
1520
1521 - (NSString *) cy$toCYON {
1522 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1523 if (!CYIsCallable(context_, toCYON)) super:
1524 return [super cy$toCYON];
1525 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1526 return CYCastNSString(NULL, CYJSString(context_, value));
1527 else goto super;
1528 }
1529
1530 - (NSUInteger) count {
1531 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1532 size_t size(JSPropertyNameArrayGetCount(names));
1533 JSPropertyNameArrayRelease(names);
1534 return size;
1535 }
1536
1537 - (id) objectForKey:(id)key {
1538 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1539 if (JSValueIsUndefined(context_, value))
1540 return nil;
1541 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1542 }
1543
1544 - (NSEnumerator *) keyEnumerator {
1545 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1546 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1547 JSPropertyNameArrayRelease(names);
1548 return enumerator;
1549 }
1550
1551 - (void) setObject:(id)object forKey:(id)key {
1552 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1553 }
1554
1555 - (void) removeObjectForKey:(id)key {
1556 JSValueRef exception(NULL);
1557 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1558 CYThrow(context_, exception);
1559 }
1560
1561 @end
1562
1563 @implementation CYJSArray
1564
1565 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1566 if ((self = [super init]) != nil) {
1567 object_ = object;
1568 context_ = context;
1569 JSValueProtect(context_, object_);
1570 } return self;
1571 }
1572
1573 - (void) dealloc {
1574 JSValueUnprotect(context_, object_);
1575 [super dealloc];
1576 }
1577
1578 - (NSUInteger) count {
1579 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1580 }
1581
1582 - (id) objectAtIndex:(NSUInteger)index {
1583 size_t bounds([self count]);
1584 if (index >= bounds)
1585 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1586 JSValueRef exception(NULL);
1587 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1588 CYThrow(context_, exception);
1589 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1590 }
1591
1592 - (void) addObject:(id)object {
1593 JSValueRef exception(NULL);
1594 JSValueRef arguments[1];
1595 arguments[0] = CYCastJSValue(context_, object);
1596 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1597 CYThrow(context_, exception);
1598 }
1599
1600 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1601 size_t bounds([self count] + 1);
1602 if (index >= bounds)
1603 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1604 JSValueRef exception(NULL);
1605 JSValueRef arguments[3];
1606 arguments[0] = CYCastJSValue(context_, index);
1607 arguments[1] = CYCastJSValue(context_, 0);
1608 arguments[2] = CYCastJSValue(context_, object);
1609 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1610 CYThrow(context_, exception);
1611 }
1612
1613 - (void) removeLastObject {
1614 JSValueRef exception(NULL);
1615 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1616 CYThrow(context_, exception);
1617 }
1618
1619 - (void) removeObjectAtIndex:(NSUInteger)index {
1620 size_t bounds([self count]);
1621 if (index >= bounds)
1622 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1623 JSValueRef exception(NULL);
1624 JSValueRef arguments[2];
1625 arguments[0] = CYCastJSValue(context_, index);
1626 arguments[1] = CYCastJSValue(context_, 1);
1627 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1628 CYThrow(context_, exception);
1629 }
1630
1631 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1632 size_t bounds([self count]);
1633 if (index >= bounds)
1634 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1635 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1636 }
1637
1638 @end
1639
1640 NSString *CYCopyNSCYON(id value) {
1641 NSString *string;
1642
1643 if (value == nil)
1644 string = @"nil";
1645 else {
1646 Class _class(object_getClass(value));
1647 SEL sel(@selector(cy$toCYON));
1648
1649 if (Method toCYON = class_getInstanceMethod(_class, sel))
1650 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1651 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1652 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1653 string = [value cy$toCYON];
1654 else goto fail;
1655 } else fail: {
1656 if (value == NSZombie_)
1657 string = @"_NSZombie_";
1658 else if (_class == NSZombie_)
1659 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1660 // XXX: frowny /in/ the pants
1661 else if (value == NSMessageBuilder_ || value == Object_)
1662 string = nil;
1663 else
1664 string = [NSString stringWithFormat:@"%@", value];
1665 }
1666
1667 // XXX: frowny pants
1668 if (string == nil)
1669 string = @"undefined";
1670 }
1671
1672 return [string retain];
1673 }
1674
1675 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1676 if (JSValueIsNull(context, value))
1677 return [@"null" retain];
1678
1679 CYTry {
1680 CYPoolTry {
1681 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1682 } CYPoolCatch(NULL)
1683 } CYCatch
1684 }
1685
1686 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1687 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1688 }
1689
1690 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1691 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1692 const char *string(CYPoolCString(pool, json));
1693 [json release];
1694 return string;
1695 } else return NULL;
1696 }
1697
1698 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1699 struct CYInternal :
1700 CYData
1701 {
1702 JSObjectRef object_;
1703
1704 CYInternal() :
1705 object_(NULL)
1706 {
1707 }
1708
1709 ~CYInternal() {
1710 // XXX: delete object_? ;(
1711 }
1712
1713 static CYInternal *Get(id self) {
1714 CYInternal *internal(NULL);
1715 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1716 // XXX: do something epic? ;P
1717 }
1718
1719 return internal;
1720 }
1721
1722 static CYInternal *Set(id self) {
1723 CYInternal *internal(NULL);
1724 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1725 if (internal == NULL) {
1726 internal = new CYInternal();
1727 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1728 }
1729 } else {
1730 // XXX: do something epic? ;P
1731 }
1732
1733 return internal;
1734 }
1735
1736 bool HasProperty(JSContextRef context, JSStringRef name) {
1737 if (object_ == NULL)
1738 return false;
1739 return JSObjectHasProperty(context, object_, name);
1740 }
1741
1742 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1743 if (object_ == NULL)
1744 return NULL;
1745 return CYGetProperty(context, object_, name);
1746 }
1747
1748 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1749 if (object_ == NULL)
1750 object_ = JSObjectMake(context, NULL, NULL);
1751 CYSetProperty(context, object_, name, value);
1752 }
1753 };
1754
1755 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1756 Selector_privateData *internal(new Selector_privateData(sel));
1757 return JSObjectMake(context, Selector_, internal);
1758 }
1759
1760 static JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1761 Pointer *internal(new Pointer(pointer, context, owner, type));
1762 return JSObjectMake(context, Pointer_, internal);
1763 }
1764
1765 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1766 Functor_privateData *internal(new Functor_privateData(type, function));
1767 return JSObjectMake(context, Functor_, internal);
1768 }
1769
1770 static const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1771 if (pool == NULL) {
1772 // XXX: this could be much more efficient
1773 const char *string([CYCastNSString(NULL, value) UTF8String]);
1774 return string;
1775 } else {
1776 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1777 char *string(new(pool) char[size]);
1778 JSStringGetUTF8CString(value, string, size);
1779 return string;
1780 }
1781 }
1782
1783 static const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1784 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1785 }
1786
1787 static bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1788 return CYGetOffset(CYPoolCString(pool, value), index);
1789 }
1790
1791 // XXX: this macro is unhygenic
1792 #define CYCastCString(context, value) ({ \
1793 char *utf8; \
1794 if (value == NULL) \
1795 utf8 = NULL; \
1796 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1797 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1798 utf8 = reinterpret_cast<char *>(alloca(size)); \
1799 JSStringGetUTF8CString(string, utf8, size); \
1800 JSStringRelease(string); \
1801 } else \
1802 utf8 = NULL; \
1803 utf8; \
1804 })
1805
1806 static void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1807 switch (JSValueGetType(context, value)) {
1808 case kJSTypeNull:
1809 return NULL;
1810 /*case kJSTypeString:
1811 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1812 case kJSTypeObject:
1813 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1814 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1815 return internal->value_;
1816 }*/
1817 default:
1818 double number(CYCastDouble(context, value));
1819 if (std::isnan(number))
1820 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1821 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1822 }
1823 }
1824
1825 template <typename Type_>
1826 static _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1827 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1828 }
1829
1830 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1831 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1832 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1833 return reinterpret_cast<SEL>(internal->value_);
1834 } else
1835 return CYCastPointer<SEL>(context, value);
1836 }
1837
1838 static void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1839 switch (type->primitive) {
1840 case sig::boolean_P:
1841 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1842 break;
1843
1844 #define CYPoolFFI_(primitive, native) \
1845 case sig::primitive ## _P: \
1846 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1847 break;
1848
1849 CYPoolFFI_(uchar, unsigned char)
1850 CYPoolFFI_(char, char)
1851 CYPoolFFI_(ushort, unsigned short)
1852 CYPoolFFI_(short, short)
1853 CYPoolFFI_(ulong, unsigned long)
1854 CYPoolFFI_(long, long)
1855 CYPoolFFI_(uint, unsigned int)
1856 CYPoolFFI_(int, int)
1857 CYPoolFFI_(ulonglong, unsigned long long)
1858 CYPoolFFI_(longlong, long long)
1859 CYPoolFFI_(float, float)
1860 CYPoolFFI_(double, double)
1861
1862 case sig::object_P:
1863 case sig::typename_P:
1864 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1865 break;
1866
1867 case sig::selector_P:
1868 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1869 break;
1870
1871 case sig::pointer_P:
1872 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1873 break;
1874
1875 case sig::string_P:
1876 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1877 break;
1878
1879 case sig::struct_P: {
1880 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1881 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1882 for (size_t index(0); index != type->data.signature.count; ++index) {
1883 sig::Element *element(&type->data.signature.elements[index]);
1884 ffi_type *field(ffi->elements[index]);
1885
1886 JSValueRef rhs;
1887 if (aggregate == NULL)
1888 rhs = value;
1889 else {
1890 rhs = CYGetProperty(context, aggregate, index);
1891 if (JSValueIsUndefined(context, rhs)) {
1892 if (element->name != NULL)
1893 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1894 else
1895 goto undefined;
1896 if (JSValueIsUndefined(context, rhs)) undefined:
1897 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1898 }
1899 }
1900
1901 CYPoolFFI(pool, context, element->type, field, base, rhs);
1902 // XXX: alignment?
1903 base += field->size;
1904 }
1905 } break;
1906
1907 case sig::void_P:
1908 break;
1909
1910 default:
1911 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1912 _assert(false);
1913 }
1914 }
1915
1916 static JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1917 JSValueRef value;
1918
1919 switch (type->primitive) {
1920 case sig::boolean_P:
1921 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1922 break;
1923
1924 #define CYFromFFI_(primitive, native) \
1925 case sig::primitive ## _P: \
1926 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1927 break;
1928
1929 CYFromFFI_(uchar, unsigned char)
1930 CYFromFFI_(char, char)
1931 CYFromFFI_(ushort, unsigned short)
1932 CYFromFFI_(short, short)
1933 CYFromFFI_(ulong, unsigned long)
1934 CYFromFFI_(long, long)
1935 CYFromFFI_(uint, unsigned int)
1936 CYFromFFI_(int, int)
1937 CYFromFFI_(ulonglong, unsigned long long)
1938 CYFromFFI_(longlong, long long)
1939 CYFromFFI_(float, float)
1940 CYFromFFI_(double, double)
1941
1942 case sig::object_P: {
1943 if (id object = *reinterpret_cast<id *>(data)) {
1944 value = CYCastJSValue(context, object);
1945 if (initialize)
1946 [object release];
1947 } else goto null;
1948 } break;
1949
1950 case sig::typename_P:
1951 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1952 break;
1953
1954 case sig::selector_P:
1955 if (SEL sel = *reinterpret_cast<SEL *>(data))
1956 value = CYMakeSelector(context, sel);
1957 else goto null;
1958 break;
1959
1960 case sig::pointer_P:
1961 if (void *pointer = *reinterpret_cast<void **>(data))
1962 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1963 else goto null;
1964 break;
1965
1966 case sig::string_P:
1967 if (char *utf8 = *reinterpret_cast<char **>(data))
1968 value = CYCastJSValue(context, utf8);
1969 else goto null;
1970 break;
1971
1972 case sig::struct_P:
1973 value = CYMakeStruct(context, data, type, ffi, owner);
1974 break;
1975
1976 case sig::void_P:
1977 value = CYJSUndefined(context);
1978 break;
1979
1980 null:
1981 value = CYJSNull(context);
1982 break;
1983
1984 default:
1985 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1986 _assert(false);
1987 }
1988
1989 return value;
1990 }
1991
1992 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1993 if (Method method = class_getInstanceMethod(_class, selector)) {
1994 if (!devoid)
1995 return true;
1996 char type[16];
1997 method_getReturnType(method, type, sizeof(type));
1998 if (type[0] != 'v')
1999 return true;
2000 }
2001
2002 // XXX: possibly use a more "awesome" check?
2003 return false;
2004 }
2005
2006 static const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
2007 if (method != NULL)
2008 return method_getTypeEncoding(method);
2009 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2010 return CYPoolCString(pool, type);
2011 else
2012 return NULL;
2013 }
2014
2015 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2016 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2017
2018 JSContextRef context(internal->context_);
2019
2020 size_t count(internal->cif_.nargs);
2021 JSValueRef values[count];
2022
2023 for (size_t index(0); index != count; ++index)
2024 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2025
2026 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
2027 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2028 }
2029
2030 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2031 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
2032
2033 JSContextRef context(internal->context_);
2034
2035 size_t count(internal->cif_.nargs);
2036 JSValueRef values[count];
2037
2038 for (size_t index(0); index != count; ++index)
2039 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2040
2041 JSObjectRef _this(CYCastJSObject(context, values[0]));
2042
2043 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2044 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2045 }
2046
2047 static Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2048 // XXX: in case of exceptions this will leak
2049 // XXX: in point of fact, this may /need/ to leak :(
2050 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2051
2052 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2053 NULL, sizeof(ffi_closure),
2054 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2055 -1, 0
2056 )));
2057
2058 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2059 _assert(status == FFI_OK);
2060
2061 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2062
2063 internal->value_ = closure;
2064
2065 return internal;
2066 }
2067
2068 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2069 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2070 return JSObjectMake(context, Functor_, internal);
2071 }
2072
2073 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2074 JSValueRef exception(NULL);
2075 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2076 CYThrow(context, exception);
2077
2078 if (function) {
2079 JSObjectRef function(CYCastJSObject(context, value));
2080 return CYMakeFunctor(context, function, type);
2081 } else {
2082 void (*function)()(CYCastPointer<void (*)()>(context, value));
2083 return CYMakeFunctor(context, function, type);
2084 }
2085 }
2086
2087 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2088 Message_privateData *internal(new Message_privateData(sel, type, imp));
2089 return JSObjectMake(context, Message_, internal);
2090 }
2091
2092 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2093 JSObjectRef function(CYCastJSObject(context, value));
2094 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2095 return reinterpret_cast<IMP>(internal->GetValue());
2096 }
2097
2098 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2099 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2100 Class _class(internal->GetValue());
2101
2102 CYPool pool;
2103 const char *name(CYPoolCString(pool, property));
2104
2105 if (SEL sel = sel_getUid(name))
2106 if (class_getInstanceMethod(_class, sel) != NULL)
2107 return true;
2108
2109 return false;
2110 }
2111
2112 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2113 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2114 Class _class(internal->GetValue());
2115
2116 CYPool pool;
2117 const char *name(CYPoolCString(pool, property));
2118
2119 if (SEL sel = sel_getUid(name))
2120 if (Method method = class_getInstanceMethod(_class, sel))
2121 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2122
2123 return NULL;
2124 }
2125
2126 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2127 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2128 Class _class(internal->GetValue());
2129
2130 CYPool pool;
2131 const char *name(CYPoolCString(pool, property));
2132
2133 SEL sel(sel_registerName(name));
2134
2135 Method method(class_getInstanceMethod(_class, sel));
2136
2137 const char *type;
2138 IMP imp;
2139
2140 if (JSValueIsObjectOfClass(context, value, Message_)) {
2141 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2142 type = sig::Unparse(pool, &message->signature_);
2143 imp = reinterpret_cast<IMP>(message->GetValue());
2144 } else {
2145 type = CYPoolTypeEncoding(pool, _class, sel, method);
2146 imp = CYMakeMessage(context, value, type);
2147 }
2148
2149 if (method != NULL)
2150 method_setImplementation(method, imp);
2151 else
2152 class_replaceMethod(_class, sel, imp, type);
2153
2154 return true;
2155 }
2156
2157 #if !__OBJC2__
2158 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2159 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2160 Class _class(internal->GetValue());
2161
2162 CYPool pool;
2163 const char *name(CYPoolCString(pool, property));
2164
2165 if (SEL sel = sel_getUid(name))
2166 if (Method method = class_getInstanceMethod(_class, sel)) {
2167 objc_method_list list = {NULL, 1, {method}};
2168 class_removeMethods(_class, &list);
2169 return true;
2170 }
2171
2172 return false;
2173 }
2174 #endif
2175
2176 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2177 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2178 Class _class(internal->GetValue());
2179
2180 unsigned int size;
2181 Method *data(class_copyMethodList(_class, &size));
2182 for (size_t i(0); i != size; ++i)
2183 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2184 free(data);
2185 }
2186
2187 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2188 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2189 id self(internal->GetValue());
2190
2191 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2192 return true;
2193
2194 CYPool pool;
2195 NSString *name(CYCastNSString(pool, property));
2196
2197 if (CYInternal *internal = CYInternal::Get(self))
2198 if (internal->HasProperty(context, property))
2199 return true;
2200
2201 Class _class(object_getClass(self));
2202
2203 CYPoolTry {
2204 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2205 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2206 if ([self cy$hasProperty:name])
2207 return true;
2208 } CYPoolCatch(false)
2209
2210 const char *string(CYPoolCString(pool, name));
2211
2212 if (class_getProperty(_class, string) != NULL)
2213 return true;
2214
2215 if (SEL sel = sel_getUid(string))
2216 if (CYImplements(self, _class, sel, true))
2217 return true;
2218
2219 return false;
2220 }
2221
2222 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2223 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2224 id self(internal->GetValue());
2225
2226 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2227 return Internal::Make(context, self, object);
2228
2229 CYTry {
2230 CYPool pool;
2231 NSString *name(CYCastNSString(pool, property));
2232
2233 if (CYInternal *internal = CYInternal::Get(self))
2234 if (JSValueRef value = internal->GetProperty(context, property))
2235 return value;
2236
2237 CYPoolTry {
2238 if (NSObject *data = [self cy$getProperty:name])
2239 return CYCastJSValue(context, data);
2240 } CYPoolCatch(NULL)
2241
2242 const char *string(CYPoolCString(pool, name));
2243 Class _class(object_getClass(self));
2244
2245 if (objc_property_t property = class_getProperty(_class, string)) {
2246 PropertyAttributes attributes(property);
2247 SEL sel(sel_registerName(attributes.Getter()));
2248 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2249 }
2250
2251 if (SEL sel = sel_getUid(string))
2252 if (CYImplements(self, _class, sel, true))
2253 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2254
2255 return NULL;
2256 } CYCatch
2257 }
2258
2259 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2260 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2261 id self(internal->GetValue());
2262
2263 CYPool pool;
2264
2265 CYTry {
2266 NSString *name(CYCastNSString(pool, property));
2267 NSString *data(CYCastNSObject(pool, context, value));
2268
2269 CYPoolTry {
2270 if ([self cy$setProperty:name to:data])
2271 return true;
2272 } CYPoolCatch(NULL)
2273
2274 const char *string(CYPoolCString(pool, name));
2275 Class _class(object_getClass(self));
2276
2277 if (objc_property_t property = class_getProperty(_class, string)) {
2278 PropertyAttributes attributes(property);
2279 if (const char *setter = attributes.Setter()) {
2280 SEL sel(sel_registerName(setter));
2281 JSValueRef arguments[1] = {value};
2282 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2283 return true;
2284 }
2285 }
2286
2287 size_t length(strlen(string));
2288
2289 char set[length + 5];
2290
2291 set[0] = 's';
2292 set[1] = 'e';
2293 set[2] = 't';
2294
2295 if (string[0] != '\0') {
2296 set[3] = toupper(string[0]);
2297 memcpy(set + 4, string + 1, length - 1);
2298 }
2299
2300 set[length + 3] = ':';
2301 set[length + 4] = '\0';
2302
2303 if (SEL sel = sel_getUid(set))
2304 if (CYImplements(self, _class, sel, false)) {
2305 JSValueRef arguments[1] = {value};
2306 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2307 }
2308
2309 if (CYInternal *internal = CYInternal::Set(self)) {
2310 internal->SetProperty(context, property, value);
2311 return true;
2312 }
2313
2314 return false;
2315 } CYCatch
2316 }
2317
2318 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2319 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2320 id self(internal->GetValue());
2321
2322 CYTry {
2323 CYPoolTry {
2324 NSString *name(CYCastNSString(NULL, property));
2325 return [self cy$deleteProperty:name];
2326 } CYPoolCatch(NULL)
2327 } CYCatch
2328 }
2329
2330 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2331 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2332 id self(internal->GetValue());
2333
2334 CYPool pool;
2335 Class _class(object_getClass(self));
2336
2337 {
2338 unsigned int size;
2339 objc_property_t *data(class_copyPropertyList(_class, &size));
2340 for (size_t i(0); i != size; ++i)
2341 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2342 free(data);
2343 }
2344 }
2345
2346 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2347 CYTry {
2348 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2349 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2350 return value;
2351 } CYCatch
2352 }
2353
2354 static bool CYIsClass(id self) {
2355 // XXX: this is a lame object_isClass
2356 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2357 }
2358
2359 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2360 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2361 Class _class(internal->GetValue());
2362 if (!CYIsClass(_class))
2363 return false;
2364
2365 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2366 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2367 // XXX: this isn't always safe
2368 CYTry {
2369 return [linternal->GetValue() isKindOfClass:_class];
2370 } CYCatch
2371 }
2372
2373 return false;
2374 }
2375
2376 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2377 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2378 CYPool pool;
2379
2380 id self(internal->GetValue());
2381 const char *name(CYPoolCString(pool, property));
2382
2383 if (object_getInstanceVariable(self, name, NULL) != NULL)
2384 return true;
2385
2386 return false;
2387 }
2388
2389 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2390 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2391 CYPool pool;
2392
2393 CYTry {
2394 id self(internal->GetValue());
2395 const char *name(CYPoolCString(pool, property));
2396
2397 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2398 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2399 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2400 }
2401
2402 return NULL;
2403 } CYCatch
2404 }
2405
2406 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2407 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2408 CYPool pool;
2409
2410 CYTry {
2411 id self(internal->GetValue());
2412 const char *name(CYPoolCString(pool, property));
2413
2414 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2415 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2416 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2417 return true;
2418 }
2419
2420 return false;
2421 } CYCatch
2422 }
2423
2424 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2425 if (Class super = class_getSuperclass(_class))
2426 Internal_getPropertyNames_(super, names);
2427
2428 unsigned int size;
2429 Ivar *data(class_copyIvarList(_class, &size));
2430 for (size_t i(0); i != size; ++i)
2431 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2432 free(data);
2433 }
2434
2435 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2436 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2437 CYPool pool;
2438
2439 id self(internal->GetValue());
2440 Class _class(object_getClass(self));
2441
2442 Internal_getPropertyNames_(_class, names);
2443 }
2444
2445 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2446 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2447 return internal->GetOwner();
2448 }
2449
2450 static bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2451 Type_privateData *typical(internal->type_);
2452 sig::Type *type(typical->type_);
2453 if (type == NULL)
2454 return false;
2455
2456 const char *name(CYPoolCString(pool, property));
2457 size_t length(strlen(name));
2458 double number(CYCastDouble(name, length));
2459
2460 size_t count(type->data.signature.count);
2461
2462 if (std::isnan(number)) {
2463 if (property == NULL)
2464 return false;
2465
2466 sig::Element *elements(type->data.signature.elements);
2467
2468 for (size_t local(0); local != count; ++local) {
2469 sig::Element *element(&elements[local]);
2470 if (element->name != NULL && strcmp(name, element->name) == 0) {
2471 index = local;
2472 goto base;
2473 }
2474 }
2475
2476 return false;
2477 } else {
2478 index = static_cast<ssize_t>(number);
2479 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2480 return false;
2481 }
2482
2483 base:
2484 ffi_type **elements(typical->GetFFI()->elements);
2485
2486 base = reinterpret_cast<uint8_t *>(internal->value_);
2487 for (ssize_t local(0); local != index; ++local)
2488 base += elements[local]->size;
2489
2490 return true;
2491 }
2492
2493 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2494 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2495 Type_privateData *typical(internal->type_);
2496
2497 ffi_type *ffi(typical->GetFFI());
2498
2499 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2500 base += ffi->size * index;
2501
2502 JSObjectRef owner(internal->GetOwner() ?: object);
2503
2504 CYTry {
2505 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2506 } CYCatch
2507 }
2508
2509 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2510 CYPool pool;
2511 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2512 Type_privateData *typical(internal->type_);
2513
2514 if (typical->type_ == NULL)
2515 return NULL;
2516
2517 ssize_t offset;
2518 if (!CYGetOffset(pool, property, offset))
2519 return NULL;
2520
2521 return Pointer_getIndex(context, object, offset, exception);
2522 }
2523
2524 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2525 return Pointer_getIndex(context, object, 0, exception);
2526 }
2527
2528 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2529 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2530 Type_privateData *typical(internal->type_);
2531
2532 ffi_type *ffi(typical->GetFFI());
2533
2534 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2535 base += ffi->size * index;
2536
2537 CYTry {
2538 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2539 return true;
2540 } CYCatch
2541 }
2542
2543 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2544 CYPool pool;
2545 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2546 Type_privateData *typical(internal->type_);
2547
2548 if (typical->type_ == NULL)
2549 return NULL;
2550
2551 ssize_t offset;
2552 if (!CYGetOffset(pool, property, offset))
2553 return NULL;
2554
2555 return Pointer_setIndex(context, object, offset, value, exception);
2556 }
2557
2558 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2559 return Pointer_setIndex(context, object, 0, value, exception);
2560 }
2561
2562 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2563 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2564 Type_privateData *typical(internal->type_);
2565 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2566 }
2567
2568 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2569 CYPool pool;
2570 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2571 Type_privateData *typical(internal->type_);
2572
2573 ssize_t index;
2574 uint8_t *base;
2575
2576 if (!Index_(pool, internal, property, index, base))
2577 return NULL;
2578
2579 JSObjectRef owner(internal->GetOwner() ?: object);
2580
2581 CYTry {
2582 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2583 } CYCatch
2584 }
2585
2586 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2587 CYPool pool;
2588 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2589 Type_privateData *typical(internal->type_);
2590
2591 ssize_t index;
2592 uint8_t *base;
2593
2594 if (!Index_(pool, internal, property, index, base))
2595 return false;
2596
2597 CYTry {
2598 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2599 return true;
2600 } CYCatch
2601 }
2602
2603 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2604 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2605 Type_privateData *typical(internal->type_);
2606 sig::Type *type(typical->type_);
2607
2608 if (type == NULL)
2609 return;
2610
2611 size_t count(type->data.signature.count);
2612 sig::Element *elements(type->data.signature.elements);
2613
2614 char number[32];
2615
2616 for (size_t index(0); index != count; ++index) {
2617 const char *name;
2618 name = elements[index].name;
2619
2620 if (name == NULL) {
2621 sprintf(number, "%lu", index);
2622 name = number;
2623 }
2624
2625 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2626 }
2627 }
2628
2629 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)()) {
2630 CYTry {
2631 if (setups + count != signature->count - 1)
2632 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2633
2634 size_t size(setups + count);
2635 void *values[size];
2636 memcpy(values, setup, sizeof(void *) * setups);
2637
2638 for (size_t index(setups); index != size; ++index) {
2639 sig::Element *element(&signature->elements[index + 1]);
2640 ffi_type *ffi(cif->arg_types[index]);
2641 // XXX: alignment?
2642 values[index] = new(pool) uint8_t[ffi->size];
2643 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2644 }
2645
2646 uint8_t value[cif->rtype->size];
2647 ffi_call(cif, function, value, values);
2648
2649 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2650 } CYCatch
2651 }
2652
2653 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2654 CYTry {
2655 CYPool pool;
2656 NSString *name(CYCastNSString(pool, property));
2657 if (Class _class = NSClassFromString(name))
2658 return CYMakeInstance(context, _class, true);
2659 return NULL;
2660 } CYCatch
2661 }
2662
2663 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2664 size_t size(objc_getClassList(NULL, 0));
2665 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2666
2667 get:
2668 size_t writ(objc_getClassList(data, size));
2669 if (size < writ) {
2670 size = writ;
2671 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2672 data = copy;
2673 goto get;
2674 } else goto done;
2675 }
2676
2677 for (size_t i(0); i != writ; ++i)
2678 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2679
2680 done:
2681 free(data);
2682 }
2683
2684 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2685 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2686
2687 CYTry {
2688 CYPool pool;
2689 const char *name(CYPoolCString(pool, property));
2690 unsigned int size;
2691 const char **data(objc_copyClassNamesForImage(internal, &size));
2692 JSValueRef value;
2693 for (size_t i(0); i != size; ++i)
2694 if (strcmp(name, data[i]) == 0) {
2695 if (Class _class = objc_getClass(name)) {
2696 value = CYMakeInstance(context, _class, true);
2697 goto free;
2698 } else
2699 break;
2700 }
2701 value = NULL;
2702 free:
2703 free(data);
2704 return value;
2705 } CYCatch
2706 }
2707
2708 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2709 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2710 unsigned int size;
2711 const char **data(objc_copyClassNamesForImage(internal, &size));
2712 for (size_t i(0); i != size; ++i)
2713 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2714 free(data);
2715 }
2716
2717 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2718 CYTry {
2719 CYPool pool;
2720 const char *name(CYPoolCString(pool, property));
2721 unsigned int size;
2722 const char **data(objc_copyImageNames(&size));
2723 for (size_t i(0); i != size; ++i)
2724 if (strcmp(name, data[i]) == 0) {
2725 name = data[i];
2726 goto free;
2727 }
2728 name = NULL;
2729 free:
2730 free(data);
2731 if (name == NULL)
2732 return NULL;
2733 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2734 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2735 return value;
2736 } CYCatch
2737 }
2738
2739 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2740 unsigned int size;
2741 const char **data(objc_copyImageNames(&size));
2742 for (size_t i(0); i != size; ++i)
2743 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2744 free(data);
2745 }
2746
2747 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2748 CYTry {
2749 CYPool pool;
2750 NSString *name(CYCastNSString(pool, property));
2751 if (Protocol *protocol = NSProtocolFromString(name))
2752 return CYMakeInstance(context, protocol, true);
2753 return NULL;
2754 } CYCatch
2755 }
2756
2757 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2758 unsigned int size;
2759 Protocol **data(objc_copyProtocolList(&size));
2760 for (size_t i(0); i != size; ++i)
2761 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2762 free(data);
2763 }
2764
2765 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
2766 Type_privateData *internal(new Type_privateData(NULL, type));
2767 return JSObjectMake(context, Type_, internal);
2768 }
2769
2770 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
2771 Type_privateData *internal(new Type_privateData(type));
2772 return JSObjectMake(context, Type_, internal);
2773 }
2774
2775 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2776 if (JSStringIsEqualToUTF8CString(property, "nil"))
2777 return Instance::Make(context, nil);
2778
2779 CYTry {
2780 CYPool pool;
2781 NSString *name(CYCastNSString(pool, property));
2782 if (Class _class = NSClassFromString(name))
2783 return CYMakeInstance(context, _class, true);
2784 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2785 switch ([[entry objectAtIndex:0] intValue]) {
2786 case 0:
2787 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2788 case 1:
2789 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2790 case 2:
2791 // XXX: this is horrendously inefficient
2792 sig::Signature signature;
2793 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2794 ffi_cif cif;
2795 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2796 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2797 }
2798 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:name])
2799 switch ([[entry objectAtIndex:0] intValue]) {
2800 // XXX: implement case 0
2801 case 1:
2802 return CYMakeType(context, CYPoolCString(pool, [entry objectAtIndex:1]));
2803 }
2804 return NULL;
2805 } CYCatch
2806 }
2807
2808 static bool stret(ffi_type *ffi_type) {
2809 return ffi_type->type == FFI_TYPE_STRUCT && (
2810 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2811 struct_forward_array[ffi_type->size] != 0
2812 );
2813 }
2814
2815 extern "C" {
2816 int *_NSGetArgc(void);
2817 char ***_NSGetArgv(void);
2818 }
2819
2820 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2821 CYTry {
2822 if (count == 0)
2823 NSLog(@"");
2824 else
2825 NSLog(@"%s", CYCastCString(context, arguments[0]));
2826 return CYJSUndefined(context);
2827 } CYCatch
2828 }
2829
2830 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2831 const char *type;
2832
2833 Class _class(object_getClass(self));
2834 if (Method method = class_getInstanceMethod(_class, _cmd))
2835 type = method_getTypeEncoding(method);
2836 else {
2837 CYTry {
2838 CYPoolTry {
2839 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2840 if (method == nil)
2841 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2842 type = CYPoolCString(pool, [method _typeString]);
2843 } CYPoolCatch(NULL)
2844 } CYCatch
2845 }
2846
2847 void *setup[2];
2848 setup[0] = &self;
2849 setup[1] = &_cmd;
2850
2851 sig::Signature signature;
2852 sig::Parse(pool, &signature, type, &Structor_);
2853
2854 ffi_cif cif;
2855 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2856
2857 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2858 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2859 }
2860
2861 static size_t Nonce_(0);
2862
2863 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2864 char name[16];
2865 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
2866 return CYCastJSValue(context, name);
2867 }
2868
2869 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2870 CYPool pool;
2871
2872 bool uninitialized;
2873
2874 id self;
2875 SEL _cmd;
2876
2877 CYTry {
2878 if (count < 2)
2879 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2880
2881 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2882 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2883 self = internal->GetValue();
2884 uninitialized = internal->IsUninitialized();
2885 if (uninitialized)
2886 internal->value_ = nil;
2887 } else {
2888 self = CYCastNSObject(pool, context, arguments[0]);
2889 uninitialized = false;
2890 }
2891
2892 if (self == nil)
2893 return CYJSNull(context);
2894
2895 _cmd = CYCastSEL(context, arguments[1]);
2896 } CYCatch
2897
2898 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2899 }
2900
2901 /* Hook: objc_registerClassPair {{{ */
2902 // XXX: replace this with associated objects
2903
2904 MSHook(void, CYDealloc, id self, SEL sel) {
2905 CYInternal *internal;
2906 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2907 if (internal != NULL)
2908 delete internal;
2909 _CYDealloc(self, sel);
2910 }
2911
2912 MSHook(void, objc_registerClassPair, Class _class) {
2913 Class super(class_getSuperclass(_class));
2914 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2915 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2916 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2917 }
2918
2919 _objc_registerClassPair(_class);
2920 }
2921
2922 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2923 CYTry {
2924 if (count != 1)
2925 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2926 CYPool pool;
2927 Class _class(CYCastNSObject(pool, context, arguments[0]));
2928 $objc_registerClassPair(_class);
2929 return CYJSUndefined(context);
2930 } CYCatch
2931 }
2932 /* }}} */
2933
2934 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2935 JSGarbageCollect(context);
2936 return CYJSUndefined(context);
2937 }
2938
2939 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2940 JSValueRef setup[count + 2];
2941 setup[0] = _this;
2942 setup[1] = object;
2943 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2944 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2945 }
2946
2947 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2948 CYPool pool;
2949 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2950
2951 // XXX: handle Instance::Uninitialized?
2952 id self(CYCastNSObject(pool, context, _this));
2953
2954 void *setup[2];
2955 setup[0] = &self;
2956 setup[1] = &internal->sel_;
2957
2958 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2959 }
2960
2961 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2962 CYPool pool;
2963 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2964 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2965 }
2966
2967 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2968 CYTry {
2969 if (count != 1)
2970 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2971 const char *name(CYCastCString(context, arguments[0]));
2972 return CYMakeSelector(context, sel_registerName(name));
2973 } CYCatch
2974 }
2975
2976 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2977 CYTry {
2978 if (count != 2)
2979 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2980
2981 void *value(CYCastPointer<void *>(context, arguments[0]));
2982 const char *type(CYCastCString(context, arguments[1]));
2983
2984 CYPool pool;
2985
2986 sig::Signature signature;
2987 sig::Parse(pool, &signature, type, &Structor_);
2988
2989 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2990 } CYCatch
2991 }
2992
2993 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2994 CYTry {
2995 if (count != 1)
2996 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2997 const char *type(CYCastCString(context, arguments[0]));
2998 return CYMakeType(context, type);
2999 } CYCatch
3000 }
3001
3002 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3003 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3004
3005 CYTry {
3006 sig::Type type;
3007
3008 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
3009 type.primitive = sig::pointer_P;
3010 type.data.data.size = 0;
3011 } else {
3012 size_t index(CYGetIndex(NULL, property));
3013 if (index == _not(size_t))
3014 return NULL;
3015 type.primitive = sig::array_P;
3016 type.data.data.size = index;
3017 }
3018
3019 type.name = NULL;
3020 type.flags = 0;
3021
3022 type.data.data.type = internal->type_;
3023
3024 return CYMakeType(context, &type);
3025 } CYCatch
3026 }
3027
3028 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3029 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3030
3031 CYTry {
3032 if (count != 1)
3033 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3034 sig::Type *type(internal->type_);
3035 ffi_type *ffi(internal->GetFFI());
3036 // XXX: alignment?
3037 uint8_t value[ffi->size];
3038 CYPool pool;
3039 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
3040 return CYFromFFI(context, type, ffi, value);
3041 } CYCatch
3042 }
3043
3044 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3045 CYTry {
3046 if (count != 0)
3047 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
3048 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
3049
3050 sig::Type *type(internal->type_);
3051 size_t size;
3052
3053 if (type->primitive != sig::array_P)
3054 size = 0;
3055 else {
3056 size = type->data.data.size;
3057 type = type->data.data.type;
3058 }
3059
3060 void *value(malloc(internal->GetFFI()->size));
3061 return CYMakePointer(context, value, type, NULL, NULL);
3062 } CYCatch
3063 }
3064
3065 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3066 CYTry {
3067 if (count > 1)
3068 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
3069 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
3070 return Instance::Make(context, self);
3071 } CYCatch
3072 }
3073
3074 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3075 CYTry {
3076 if (count != 2)
3077 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
3078 const char *type(CYCastCString(context, arguments[1]));
3079 return CYMakeFunctor(context, arguments[0], type);
3080 } CYCatch
3081 }
3082
3083 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3084 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
3085 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3086 }
3087
3088 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3089 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3090 Type_privateData *typical(internal->GetType());
3091
3092 sig::Type *type;
3093 ffi_type *ffi;
3094
3095 if (typical == NULL) {
3096 type = NULL;
3097 ffi = NULL;
3098 } else {
3099 type = typical->type_;
3100 ffi = typical->ffi_;
3101 }
3102
3103 return CYMakePointer(context, &internal->value_, type, ffi, object);
3104 }
3105
3106 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3107 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3108
3109 CYTry {
3110 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3111 } CYCatch
3112 }
3113
3114 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3115 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3116 }
3117
3118 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3119 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3120 char string[32];
3121 sprintf(string, "%p", internal->value_);
3122
3123 CYTry {
3124 return CYCastJSValue(context, string);
3125 } CYCatch
3126 }
3127
3128 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3129 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3130 return Instance::Make(context, object_getClass(internal->GetValue()));
3131 }
3132
3133 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3134 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3135 id self(internal->GetValue());
3136 if (!CYIsClass(self))
3137 return CYJSUndefined(context);
3138 CYTry {
3139 return CYGetClassPrototype(context, self);
3140 } CYCatch
3141 }
3142
3143 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3144 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3145 id self(internal->GetValue());
3146 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3147 return CYJSUndefined(context);
3148 return Messages::Make(context, self);
3149 }
3150
3151 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3152 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3153 return NULL;
3154
3155 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3156
3157 CYTry {
3158 CYPoolTry {
3159 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
3160 } CYPoolCatch(NULL)
3161 } CYCatch
3162 }
3163
3164 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3165 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3166 return NULL;
3167
3168 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3169
3170 CYTry {
3171 CYPoolTry {
3172 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3173 // XXX: check for support of cy$toJSON?
3174 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3175 } CYPoolCatch(NULL)
3176 } CYCatch
3177 }
3178
3179 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3180 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3181 return NULL;
3182
3183 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3184
3185 CYTry {
3186 CYPoolTry {
3187 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3188 } CYPoolCatch(NULL)
3189 } CYCatch
3190 }
3191
3192 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3193 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3194
3195 CYTry {
3196 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3197 } CYCatch
3198 }
3199
3200 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3201 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3202 }
3203
3204 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3205 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3206 const char *name(sel_getName(internal->GetValue()));
3207
3208 CYTry {
3209 CYPoolTry {
3210 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3211 } CYPoolCatch(NULL)
3212 } CYCatch
3213 }
3214
3215 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3216 CYTry {
3217 if (count != 1)
3218 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
3219 CYPool pool;
3220 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3221 Class _class(CYCastNSObject(pool, context, arguments[0]));
3222 SEL sel(internal->GetValue());
3223 Method method(class_getInstanceMethod(_class, sel));
3224 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3225 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3226 } CYCatch
3227 }
3228
3229 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3230 CYTry {
3231 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3232 CYPool pool;
3233 const char *type(sig::Unparse(pool, internal->type_));
3234 CYPoolTry {
3235 return CYCastJSValue(context, CYJSString(type));
3236 } CYPoolCatch(NULL)
3237 } CYCatch
3238 }
3239
3240 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3241 CYTry {
3242 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3243 CYPool pool;
3244 const char *type(sig::Unparse(pool, internal->type_));
3245 CYPoolTry {
3246 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
3247 } CYPoolCatch(NULL)
3248 } CYCatch
3249 }
3250
3251 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3252 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3253 }
3254
3255 static JSStaticValue CYValue_staticValues[2] = {
3256 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3257 {NULL, NULL, NULL, 0}
3258 };
3259
3260 static JSStaticValue Pointer_staticValues[2] = {
3261 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3262 {NULL, NULL, NULL, 0}
3263 };
3264
3265 static JSStaticFunction Pointer_staticFunctions[4] = {
3266 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3267 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3268 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3269 {NULL, NULL, 0}
3270 };
3271
3272 static JSStaticFunction Struct_staticFunctions[2] = {
3273 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3274 {NULL, NULL, 0}
3275 };
3276
3277 static JSStaticFunction Functor_staticFunctions[4] = {
3278 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3279 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3280 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3281 {NULL, NULL, 0}
3282 };
3283
3284 static JSStaticValue Instance_staticValues[5] = {
3285 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3286 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3287 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3288 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3289 {NULL, NULL, NULL, 0}
3290 };
3291
3292 static JSStaticFunction Instance_staticFunctions[5] = {
3293 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3294 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3295 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3296 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3297 {NULL, NULL, 0}
3298 };
3299
3300 static JSStaticFunction Internal_staticFunctions[2] = {
3301 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3302 {NULL, NULL, 0}
3303 };
3304
3305 static JSStaticFunction Selector_staticFunctions[5] = {
3306 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3307 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3308 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3309 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3310 {NULL, NULL, 0}
3311 };
3312
3313 static JSStaticFunction Type_staticFunctions[4] = {
3314 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3315 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3316 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3317 {NULL, NULL, 0}
3318 };
3319
3320 CYDriver::CYDriver(const std::string &filename) :
3321 state_(CYClear),
3322 data_(NULL),
3323 size_(0),
3324 file_(NULL),
3325 strict_(false),
3326 filename_(filename),
3327 program_(NULL)
3328 {
3329 ScannerInit();
3330 }
3331
3332 CYDriver::~CYDriver() {
3333 ScannerDestroy();
3334 }
3335
3336 void CYDriver::Warning(const cy::location &location, const char *message) {
3337 if (!strict_)
3338 return;
3339
3340 CYDriver::Error error;
3341 error.warning_ = true;
3342 error.location_ = location;
3343 error.message_ = message;
3344 errors_.push_back(error);
3345 }
3346
3347 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
3348 CYDriver::Error error;
3349 error.warning_ = false;
3350 error.location_ = location;
3351 error.message_ = message;
3352 driver.errors_.push_back(error);
3353 }
3354
3355 void CYSetArgs(int argc, const char *argv[]) {
3356 JSContextRef context(CYGetJSContext());
3357 JSValueRef args[argc];
3358 for (int i(0); i != argc; ++i)
3359 args[i] = CYCastJSValue(context, argv[i]);
3360 JSValueRef exception(NULL);
3361 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3362 CYThrow(context, exception);
3363 CYSetProperty(context, System_, CYJSString("args"), array);
3364 }
3365
3366 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3367 return JSContextGetGlobalObject(context);
3368 }
3369
3370 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3371 JSContextRef context(CYGetJSContext());
3372 JSValueRef exception(NULL), result;
3373
3374 try {
3375 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3376 } catch (const char *error) {
3377 return error;
3378 }
3379
3380 if (exception != NULL) { error:
3381 result = exception;
3382 exception = NULL;
3383 }
3384
3385 if (JSValueIsUndefined(context, result))
3386 return NULL;
3387
3388 const char *json;
3389
3390 try {
3391 json = CYPoolCCYON(pool, context, result, &exception);
3392 } catch (const char *error) {
3393 return error;
3394 }
3395
3396 if (exception != NULL)
3397 goto error;
3398
3399 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3400 return json;
3401 }
3402
3403 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
3404 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
3405 data += writ;
3406 size -= writ;
3407 } else
3408 return false;
3409 return true;
3410 }
3411
3412 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
3413 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
3414 data += writ;
3415 size -= writ;
3416 } else
3417 return false;
3418 return true;
3419 }
3420
3421 static apr_pool_t *Pool_;
3422
3423 struct CYExecute_ {
3424 apr_pool_t *pool_;
3425 const char * volatile data_;
3426 };
3427
3428 // XXX: this is "tre lame"
3429 @interface CYClient_ : NSObject {
3430 }
3431
3432 - (void) execute:(NSValue *)value;
3433
3434 @end
3435
3436 @implementation CYClient_
3437
3438 - (void) execute:(NSValue *)value {
3439 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3440 const char *data(execute->data_);
3441 execute->data_ = NULL;
3442 execute->data_ = CYExecute(execute->pool_, data);
3443 }
3444
3445 @end
3446
3447 struct CYClient :
3448 CYData
3449 {
3450 int socket_;
3451 apr_thread_t *thread_;
3452
3453 CYClient(int socket) :
3454 socket_(socket)
3455 {
3456 }
3457
3458 ~CYClient() {
3459 _syscall(close(socket_));
3460 }
3461
3462 void Handle() { _pooled
3463 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3464
3465 for (;;) {
3466 size_t size;
3467 if (!CYRecvAll(socket_, &size, sizeof(size)))
3468 return;
3469
3470 CYPool pool;
3471 char *data(new(pool) char[size + 1]);
3472 if (!CYRecvAll(socket_, data, size))
3473 return;
3474 data[size] = '\0';
3475
3476 CYDriver driver("");
3477 cy::parser parser(driver);
3478
3479 driver.data_ = data;
3480 driver.size_ = size;
3481
3482 const char *json;
3483 if (parser.parse() != 0 || !driver.errors_.empty()) {
3484 json = NULL;
3485 size = _not(size_t);
3486 } else {
3487 std::ostringstream str;
3488 CYOutput out(str);
3489 out << *driver.program_;
3490 std::string code(str.str());
3491 CYExecute_ execute = {pool, code.c_str()};
3492 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3493 json = execute.data_;
3494 size = json == NULL ? _not(size_t) : strlen(json);
3495 }
3496
3497 if (!CYSendAll(socket_, &size, sizeof(size)))
3498 return;
3499 if (json != NULL)
3500 if (!CYSendAll(socket_, json, size))
3501 return;
3502 }
3503 }
3504 };
3505
3506 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3507 CYClient *client(reinterpret_cast<CYClient *>(data));
3508 client->Handle();
3509 delete client;
3510 return NULL;
3511 }
3512
3513 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3514 CYClient *client(new(pool) CYClient(socket));
3515 apr_threadattr_t *attr;
3516 _aprcall(apr_threadattr_create(&attr, client->pool_));
3517 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3518 }
3519
3520 MSInitialize { _pooled
3521 _aprcall(apr_initialize());
3522 _aprcall(apr_pool_create(&Pool_, NULL));
3523
3524 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3525 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3526
3527 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3528
3529 NSArray_ = objc_getClass("NSArray");
3530 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3531 NSCFType_ = objc_getClass("NSCFType");
3532 NSDictionary_ = objc_getClass("NSDictonary");
3533 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3534 NSZombie_ = objc_getClass("_NSZombie_");
3535 Object_ = objc_getClass("Object");
3536 }
3537
3538 JSGlobalContextRef CYGetJSContext() {
3539 if (Context_ == NULL) {
3540 JSClassDefinition definition;
3541
3542 definition = kJSClassDefinitionEmpty;
3543 definition.className = "Functor";
3544 definition.staticFunctions = Functor_staticFunctions;
3545 definition.callAsFunction = &Functor_callAsFunction;
3546 definition.finalize = &Finalize;
3547 Functor_ = JSClassCreate(&definition);
3548
3549 definition = kJSClassDefinitionEmpty;
3550 definition.className = "Instance";
3551 definition.staticValues = Instance_staticValues;
3552 definition.staticFunctions = Instance_staticFunctions;
3553 definition.hasProperty = &Instance_hasProperty;
3554 definition.getProperty = &Instance_getProperty;
3555 definition.setProperty = &Instance_setProperty;
3556 definition.deleteProperty = &Instance_deleteProperty;
3557 definition.getPropertyNames = &Instance_getPropertyNames;
3558 definition.callAsConstructor = &Instance_callAsConstructor;
3559 definition.hasInstance = &Instance_hasInstance;
3560 definition.finalize = &Finalize;
3561 Instance_ = JSClassCreate(&definition);
3562
3563 definition = kJSClassDefinitionEmpty;
3564 definition.className = "Internal";
3565 definition.staticFunctions = Internal_staticFunctions;
3566 definition.hasProperty = &Internal_hasProperty;
3567 definition.getProperty = &Internal_getProperty;
3568 definition.setProperty = &Internal_setProperty;
3569 definition.getPropertyNames = &Internal_getPropertyNames;
3570 definition.finalize = &Finalize;
3571 Internal_ = JSClassCreate(&definition);
3572
3573 definition = kJSClassDefinitionEmpty;
3574 definition.className = "Message";
3575 definition.staticFunctions = Functor_staticFunctions;
3576 definition.callAsFunction = &Message_callAsFunction;
3577 definition.finalize = &Finalize;
3578 Message_ = JSClassCreate(&definition);
3579
3580 definition = kJSClassDefinitionEmpty;
3581 definition.className = "Messages";
3582 definition.hasProperty = &Messages_hasProperty;
3583 definition.getProperty = &Messages_getProperty;
3584 definition.setProperty = &Messages_setProperty;
3585 #if !__OBJC2__
3586 definition.deleteProperty = &Messages_deleteProperty;
3587 #endif
3588 definition.getPropertyNames = &Messages_getPropertyNames;
3589 definition.finalize = &Finalize;
3590 Messages_ = JSClassCreate(&definition);
3591
3592 definition = kJSClassDefinitionEmpty;
3593 definition.className = "NSArrayPrototype";
3594 //definition.hasProperty = &NSArrayPrototype_hasProperty;
3595 //definition.getProperty = &NSArrayPrototype_getProperty;
3596 //definition.setProperty = &NSArrayPrototype_setProperty;
3597 //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
3598 //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
3599 NSArrayPrototype_ = JSClassCreate(&definition);
3600
3601 definition = kJSClassDefinitionEmpty;
3602 definition.className = "Pointer";
3603 definition.staticValues = Pointer_staticValues;
3604 definition.staticFunctions = Pointer_staticFunctions;
3605 definition.getProperty = &Pointer_getProperty;
3606 definition.setProperty = &Pointer_setProperty;
3607 definition.finalize = &Finalize;
3608 Pointer_ = JSClassCreate(&definition);
3609
3610 definition = kJSClassDefinitionEmpty;
3611 definition.className = "Selector";
3612 definition.staticValues = CYValue_staticValues;
3613 definition.staticFunctions = Selector_staticFunctions;
3614 definition.callAsFunction = &Selector_callAsFunction;
3615 definition.finalize = &Finalize;
3616 Selector_ = JSClassCreate(&definition);
3617
3618 definition = kJSClassDefinitionEmpty;
3619 definition.className = "Struct";
3620 definition.staticFunctions = Struct_staticFunctions;
3621 definition.getProperty = &Struct_getProperty;
3622 definition.setProperty = &Struct_setProperty;
3623 definition.getPropertyNames = &Struct_getPropertyNames;
3624 definition.finalize = &Finalize;
3625 Struct_ = JSClassCreate(&definition);
3626
3627 definition = kJSClassDefinitionEmpty;
3628 definition.className = "Type";
3629 definition.staticFunctions = Type_staticFunctions;
3630 definition.getProperty = &Type_getProperty;
3631 definition.callAsFunction = &Type_callAsFunction;
3632 definition.callAsConstructor = &Type_callAsConstructor;
3633 definition.finalize = &Finalize;
3634 Type_ = JSClassCreate(&definition);
3635
3636 definition = kJSClassDefinitionEmpty;
3637 definition.className = "Runtime";
3638 definition.getProperty = &Runtime_getProperty;
3639 Runtime_ = JSClassCreate(&definition);
3640
3641 definition = kJSClassDefinitionEmpty;
3642 definition.className = "ObjectiveC::Classes";
3643 definition.getProperty = &ObjectiveC_Classes_getProperty;
3644 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3645 ObjectiveC_Classes_ = JSClassCreate(&definition);
3646
3647 definition = kJSClassDefinitionEmpty;
3648 definition.className = "ObjectiveC::Images";
3649 definition.getProperty = &ObjectiveC_Images_getProperty;
3650 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3651 ObjectiveC_Images_ = JSClassCreate(&definition);
3652
3653 definition = kJSClassDefinitionEmpty;
3654 definition.className = "ObjectiveC::Image::Classes";
3655 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3656 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3657 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3658
3659 definition = kJSClassDefinitionEmpty;
3660 definition.className = "ObjectiveC::Protocols";
3661 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3662 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3663 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3664
3665 definition = kJSClassDefinitionEmpty;
3666 //definition.getProperty = &Global_getProperty;
3667 JSClassRef Global(JSClassCreate(&definition));
3668
3669 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3670 Context_ = context;
3671
3672 JSObjectRef global(CYGetGlobalObject(context));
3673
3674 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3675 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3676 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3677
3678 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3679 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3680 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3681
3682 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3683 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3684 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3685
3686 length_ = JSStringCreateWithUTF8CString("length");
3687 message_ = JSStringCreateWithUTF8CString("message");
3688 name_ = JSStringCreateWithUTF8CString("name");
3689 prototype_ = JSStringCreateWithUTF8CString("prototype");
3690 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3691 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3692
3693 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3694 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3695
3696 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3697 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3698 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3699 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3700
3701 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3702 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3703 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3704 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3705
3706 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3707
3708 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3709 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3710 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3711 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3712
3713 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3714 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3715 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3716 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3717 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3718
3719 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3720
3721 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3722
3723 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
3724 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
3725 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
3726
3727 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3728 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3729 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3730
3731 System_ = JSObjectMake(context, NULL, NULL);
3732 CYSetProperty(context, global, CYJSString("system"), System_);
3733 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3734 //CYSetProperty(context, System_, CYJSString("global"), global);
3735
3736 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3737
3738 Result_ = JSStringCreateWithUTF8CString("_");
3739
3740 JSValueProtect(context, Array_);
3741 JSValueProtect(context, Function_);
3742 JSValueProtect(context, String_);
3743
3744 JSValueProtect(context, Instance_prototype_);
3745 JSValueProtect(context, Object_prototype_);
3746
3747 JSValueProtect(context, Array_prototype_);
3748 JSValueProtect(context, Array_pop_);
3749 JSValueProtect(context, Array_push_);
3750 JSValueProtect(context, Array_splice_);
3751 }
3752
3753 return Context_;
3754 }