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