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