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