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