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